Issues with passing a variable with jQuery to PHP -
i have 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 variable in url called id (for example http://www.url.com?id=1) , i'm trying send page called api.php have database query. i'm trying corresponding value of id (in case path) , return it. seems variable id not being passed api.php. have hardcoded id variable in api.php ($id = 1), query working fine , after i'm able value database, when in api.php put following:
<?php if($_post) { $id = $_post['id']; } ?>
then it's not working. i'm not sure if $.post() method not working or reason i'm not able value of id variable in php script.
can me solve out?
regards, ivan
first of all, $.post()
call has no callback, though post request made, there no code execute when it's successful.
your second, $.ajax()
call not specify type
parameter (or data call), , result use get
. inside api.php
file, you're checking $_post
super-global, of course not contain value id
, since you're using get
, not post
.
you should update $.ajax()
call follows:
$.ajax({ url: 'api.php', data: { 'id': <?php echo $_get['id'] ?> }, datatype: 'json', type: 'post' }).done(function(data) { var path = data[0]; alert(path); });
(you don't need first $.post()
call, think have confused usage of function).
also, you'll need output api.php
in order access in js, example:
<?php if( isset($_post['id']) ) { echo $_post['id']; } ?>
Comments
Post a Comment