I am quite new as web developer, I find myself trying to resolve a problem.
I would like to pass a value JavaScript to PHP without using any form method.
Her
You can pass the variables using form. There is no other way to pass the php variables other than forms.
<form id="WOW" action="" method="get">
<input id="Num" name="clicked_id" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(document).ready(function){
$('#WOW').submit(function(event){
event.preventDefault();
$data = $('#WOW').serialize();
$url = $('#WOW').attr('action');
//your variable is posted to that file!
$.post($url,$data,function(data){
console.log('Veriables sent! and data recieved is:' + data);
});
});
});
function getIdImage(clicked_id)
{
$('#Num').val(clicked_id);
$('#WOW').submit();
}
</script>
If you're using a standard setup, your PHP code will run from start to finish each time a request is made to the server. It won't run "on demand" like the Javascript code you have on your page. In order to pass a value to a PHP script, you therefore have to send a request to your server (where the PHP code resides) passing the desired value(s) inside the request payload. The request can be sent through a simple link, regular form or an XHR. If you don't want the page to reload, but you want to run some code on the server and, when that is done, do some stuff on the browser then your tool of choice is the XHR.
In order to send an XHR you could build it yourself from scratch or you can use one of the many libraries available out there, which is of course the recommended route. Let's say you want to use jQuery:
function getIdImage(clicked_id)
{
jQuery.ajax({
url: '/url/to/my/script.php',
type: 'POST',
dataType: 'json',
data: { clicked_id: clicked_id },
success: function(result) {
// This function will be called when the server returns a success (200 OK) response
console.log(result);
alert('Yay!');
},
error: function(xhr) {
// This function is called when the server fails to process the request, for whatever reason
console.log(xhr);
alert('Nay!');
}
});
}
On your server you'll have a script to process this request, the one you pointed at in the URL, and you'll be able to use whatever payload was passed to the script in the request
<?php
$data = json_decode($_POST);
echo "The ID of the clicked image is: " . $data->clicked_id;
Of course this example won't do much, it will just return the echoed string a response. Depending on what you want to do, you'll need to build a response after doing some meaningful computation, and the response should probably be itself in JSON format (using the good old json_encode
builtin PHP function).
You need to send a request which hold your data you can use AJAX as mentioned in comment.
Here JQuery ajax example :
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
// Available informations
});