简体   繁体   中英

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.

JS Script

$("#save_groups").click( function() {

var ids = [];

$.each($('input'), function() {
    var id = $(this).attr('value');
    //Put ID in array.
    ids.push(id);
    console.log('IDs'+ids);
});

$.ajax({        

       type: "POST",
       url: "inc/insert.php",
       data: {grouparray: ids },
       success: function() {
            $("#saved").fadeOut('slow');   
                    console.log('Success on ' + ids);
       }
    }); 


});

PHP Section

<?php
include ('connect.php');

$grouparray = $_POST['grouparray'];

$user_ID = '9';

$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";

$result=mysql_query($sql);

if ($result === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysql_error();
}
?>

You cannot send an array trough an ajax call.

First, use something like:

var idString = JSON.stringify(ids);

And use it: data: {grouparray: idString },

On the PHP side:

$array = json_decode($_POST['grouparray']);
print_r($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