简体   繁体   中英

How to send multiple data fields via Ajax to php page?

i have a problem, I want to send 2 posts to my author php page by using ajax

thats my code :

$.ajax({
type: "POST",
url: "includes/get_competitions.php",
data:'sport=<?php echo $_GET['sports']; ?>',
success: function(data){
    $("#competitions-list").html(data);
}

and this what i want to do :

$.ajax({
type: "POST",
url: "includes/get_competitions.php",
data:'sport1=<?php echo $_GET['sports1']; ?>, sport2=<?php echo $_GET['sports2']; ?>',
success: function(data){
    $("#competitions-list").html(data);
}

but it didn't work

You can try this

data: $('#myForm').serialize()   <---- your form name

This will send all the form data

Multiple parameters in a data string are separated by & , not , (it's just like the syntax of parameters in a URL).

However, if you're using jQuery it's best to use an object. $.ajax will automatically convert it to the properly encoded query string. And you can use json_encode() to convert a PHP value to the corresponding JavaScript literal.

$.ajax({
    type: "POST",
    url: "includes/get_competitions.php",
    data: {
        sport1: <?php echo json_encode($_GET['sports1']); ?>, 
        sport2: <?php echo json_encode($_GET['sports2']); ?>
    },
    success: function(data){
        $("#competitions-list").html(data);
}

You could also make a single sports array, rather than numbering the parameters.

$.ajax({
    type: "POST",
    url: "includes/get_competitions.php",
    data: {
        sports: [<?php echo json_encode($_GET['sports1']); ?>, 
                 <?php echo json_encode($_GET['sports2']); ?>]
    },
    success: function(data){
        $("#competitions-list").html(data);
}

Then in get_competitions.php , $_POST['sports'] will be an array.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM