I have a function where the user inputs are stored in a variable in javascript.
$('#btnsubmit').click(function() { var seat = [], item; $.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); seat.push(item); }); var bookseats = seat; $.ajax({ type: 'POST', url: 'confirm.php', data: {'bookseats': bookseats}, }); });
When the user clicks on the #btnsubmit
button, I want to send this variable(actually an array) to a PHP file named confirm.php.
<form method="POST" action="confirm.php"> <div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div> </form>
In my PHP file, I've written the code to get the sent variable as follows.
$bookseats = "";
if(isset($_POST['bookseats']))
{
$bookseats = $_POST["bookseats"];
print_r($bookseats);
}
When executed, nothing happens in the PHP file(doesn't print the bookseats
).Is there something wrong with this code?
You're not using a "success" callback to get the output of the PHP code. See success
callback
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
success: function(data) {
console.log(data); // or alert(data);
}
});
Also, I think you should stop the propagation of the default behavior of the button, to prevent the browser to redirect the page to the form's action URL:
$('#btnsubmit').click(function(ev) {
ev.preventDefault();
As @Malovich pointed out, as of jQuery 1.8, you could also use .then()
:
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats}
}).then(function(data) {
console.log(data); // or alert(data);
}, function(){
console.log("Error");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.