I have the following code:
<?php
$id = $_GET['id'];
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<script>
var id = $.urlParam('id');
var id = <?php echo $id; ?>;
$.post("api.php", { id: id });
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var path = data[0];
alert(path);
}
});
</script>
</body>
</html>
I have a variable in the URL called id (for example http://www.url.com?id=1) and I'm trying to send it to a page called api.php where I have the database query. Then I'm trying to get the corresponding value of this id (in my case path) and return it. However it seems that the variable id is not being passed to api.php. I have hardcoded the id variable in api.php ($id = 1), the query is working fine and after that I'm able to get the value from the database, but when in api.php I put the following:
<?php
if($_POST) {
$id = $_POST['id'];
}
?>
Then it's not working. I'm not sure if the $.post() method is not working or for some reason I'm not able to get the value of the id variable in the PHP script.
Can somebody help me to solve this out?
Regards, Ivan
idtwice in JS. If you look at ajax request is the value there?$.ajax()does a get request, not post. that means $_POST will NOT be set when you do your .ajax() call.$.urlParam('id')if you haven't included that plugin function in page. Will throw exceptions and break your code. Also you have back to back ajax requests...the second with no data and a GET and the first one has no done callbacktype : 'post'