0

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!

3
  • 2
    Can you provide the print_r() of the modules variable? Commented Jan 28, 2013 at 17:59
  • use implode(',', $modules); or json_decode() Commented Jan 28, 2013 at 18:02
  • 1
    Use PDO instead of mysql_query. Commented Jan 28, 2013 at 18:02

1 Answer 1

0

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.