简体   繁体   中英

How to pass javascript array to php array using Ajax and Jquery

I'm trying to pass a Javascript array into a PHP array through jQuery and Ajax. The PHP script should then write the array into a MySQL database, with each individual entry in the array being assigned to a separate column in the database. This is the code I'm currently using (which doesn't work!)

Javascript:

The array is contained in a variable called 'modules'

   $.ajax({
        url: "newaccount.php",
        type: "POST",
        data: {modules: modules},
        success: function(){
         modules.length = 0;
         $("#result").html("Success");
         },
     });

PHP:

 $modules = $_POST['modules'];

 if(mysql_query ("INSERT INTO level3 (mod1, mod2, mod3, mod4) VALUES ('$modules')")) {
  echo "Successfully inserted";
 }
 else {
  echo "Insertion Failed";
 }

This is a simplified version - usually there are other values inserted into the database alongside this which are not contained in arrays. These seem to be working fine, but when I try to insert the array values nothing goes in - the database columns remain as 'null'

Please help! I've been banging my head against this brick wall all day!

What you are looking for is called serialization technique. You should serialize the javascript variable and send it to php, where it can deserialize it again. You can refer to following posts which will help you to find out the solution.

Serializing to JSON in jQuery

serialize javascript array

http://api.jquery.com/serializeArray/

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