简体   繁体   中英

How do I insert an object data array into a database with AJAX

I want to insert data from an array into a database table in the submit() function where the sql syntax is at. I want to insert the data then redirect to another page after successful. I don't know how to do this with ajax.

I tried to make ajax syntax but I don't know if i'm passing the data correctly for obj.name and obj.books corresponding to their own values in the array.

example: [{"name":"book1","books":["thisBook1.1","thisBook1.2"]},{"name":"book2","books":["thisBook2.1","thisBook2.2","thisBook2.3"]}]

function submit(){
    var arr = [];
    for(i = 1; i <= authors; i++){
        var obj = {};
        obj.name = $("#author" + i).val();
        obj.books = [];
        $(".auth" + i).each(function(){
            var data = $(this).val();
            obj.books.push(data);
        });
        //sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
        //mysqli_query(sql);
        arr.push(obj);
    }

    $("#result").html(JSON.stringify(arr));
}
/////////////////////////////////
//I tried this:
$.ajax({
   type: "POST",
   data: {arr: arr},
   url: "next.php",
   success: function(){

   }
});
/////////////////////////////////

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <style type="text/css"> <!-- #main { max-width: 800px; margin: 0 auto; } --> </style> </head> <body> <div id="main"> <h1>Add or Remove text boxes with jQuery</h1> <div class="my-form"> <form action"next.php" method="post"> <button onclick="addAuthor()">Add Author</button> <br> <br> <div id="addAuth"></div> <br> <br> <button onclick="submit()">Submit</button> </form> </div> <div id="result"></div> </div> <script type="text/javascript"> var authors = 0; function addAuthor() { authors++; var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\\'auth' + authors + '\\')" >Add Book</button>' + '</div>'; $("#addAuth").append(str); } var count = 0; function addMore(id) { count++; var str = '<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\\'bookDiv' + count + '\\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">Remove</span>' + '</div>'; $("#" + id).append(str); } function removeDiv(id) { //var val = confirm("Are you sure ..?"); //if(val){ $("#" + id).slideUp(function() { $("#" + id).remove(); }); //} } function submit() { var arr = []; for (i = 1; i <= authors; i++) { var obj = {}; obj.name = $("#author" + i).val(); obj.books = []; $(".auth" + i).each(function() { var data = $(this).val(); obj.books.push(data); }); // sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')"); // mysqli_query(sql); arr.push(obj); } $("#result").html(JSON.stringify(arr)); } </script> </body> </html> 

Send your array to server ,stringify array before sending it to server so in server you can decode json and recover your array, and then insert received data to database
JS

function submit(){
    var arr = [];
    for(i = 1; i <= authors; i++){
        var obj = {};
        obj.name = $("#author" + i).val();
        obj.books = [];
        $(".auth" + i).each(function(){
            var data = $(this).val();
            obj.books.push(data);
        });

        //sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
        //mysqli_query(sql);
        arr.push(obj);
    }
    sendToServer(arr)
    $("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
   $.ajax({
      type: "POST",
      data: {arr: JSON.stringify(data)},
      url: "next.php",
      success: function(){

      }
   });
}

PHP (next.php)

$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
   echo $d;
   // insert to db
}

Please Keep the following in mind

Javascript/JQuery is client side and hence cannot access the database which is on the server.

You can Send data via AJAX to next.php and then use this data to insert into your database.

To improve debugging, use the following code to ensure the correct data is being delivered in next.php

   var_dump($_POST);

Your SQL statements must be executed in next.php using the data passed by $_POST (since your "type" of AJAX request is post).

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