Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
2  
Can you provide the print_r() of the modules variable? – Pat Burke Jan 28 at 17:59
use implode(',', $modules); or json_decode() – mamdouh alramadan Jan 28 at 18:02
1  
Use PDO instead of mysql_query. – Blazemonger Jan 28 at 18:02

1 Answer

up vote 0 down vote accepted

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/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.