Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a site where users can order items. I am currently sending various bits of information to the PHP script so they can be added to the database from there:

$.ajax ({
  type: "POST",
  url: "./pay.php",
  dataType: "json",
  data: {
    "firstName" : firstName,
    "lastName" : lastName,
    "email" : email,
    "price" : price
  }  
});

This is working well. Now I would like to send over two arrays that contain the id's and quantities of products that were ordered. Since I don't know how many products there are at any given point or what their id is, I cannot add them as individual items as I have done above. Currently I have the product ID's and their corresponding quantities in separate arrays as such:

productIds: ["6", "1"]
quantities: ["1", "4"]

I would like to send these arrays to the PHP script along with the rest of the variables so I can loop through those arrays and insert the information into the database.

Can I do that like this?

$.ajax ({
      type: "POST",
      url: "./pay.php",
      dataType: "json",
      data: {
        "firstName" : firstName,
        "lastName" : lastName,
        "email" : email,
        "price" : price,
        "productIds" : productIds,
        "quantities" : quantities
      }  
 });

The non-array variables I am currently able to access like this in the PHP script:

$email = $_POST['email'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$price = $_POST['price'];

I would like to loop through the productIds array in the PHP script something like this, but I think I am missing something:

$i = 1;
foreach ($_POST['productIds'] as $value) {
  $sql = 'INSERT INTO orders SET
  product_id = "'.$_POST['productIds'][$i].'",
  quantity = "'.$_POST['quantities'][$i].'"';

  $result = $conn->query($sql);
  $i++;
}

How can I send a javascript array to a PHP script using Ajax along with other non-array data?

share|improve this question
1  
You're just missing the $ at the beginning of $i in the subscripts. –  Barmar Apr 14 '13 at 2:02
    
Thanks. I have updated my example. –  zeckdude Apr 14 '13 at 2:03
    
Did you try just doing print_r($_POST['productIds']) to see what's in there? –  FluffyJack Apr 14 '13 at 2:04
    
Show the output of var_dump($_POST). –  Barmar Apr 14 '13 at 2:04
    
I am trying to print_r or var_dump but the ajax won't work when I try those. I am assuming I receiving an error on the PHP side. I thought those PHP errors would appear in the Console, but I don't see them there? How can I view those errors? –  zeckdude Apr 14 '13 at 2:24

3 Answers 3

PHP will accept array parameters, but you must send parameters in its acceptable form,

<?php
    $str = "first=value&arr[]=foo+bar&arr[]=baz";
    parse_str($str);
    echo $first;  // value
    echo $arr[0]; // foo bar
    echo $arr[1]; // baz

    parse_str($str, $output);
    echo $output['first'];  // value
    echo $output['arr'][0]; // foo bar
    echo $output['arr'][1]; // baz
?>

For HTTP posts, you can simply visit the array through $_POST variable.

On JavaScript side, the code is like this,

$.post(url, {'arr[]': array}, function(data){
    // do something with received data
});
share|improve this answer
    
This looks interesting but I cannot see how to implement this on the javascript side. Can you help me out with that? –  zeckdude Apr 14 '13 at 2:32
    
@zeckdude I've edited my answer. –  Davidsun Apr 14 '13 at 12:34

You can form a JavaScript object right when you're collecting the form data. Send that object directly to PHP. Something like so:

//Your object could look like this
var data = {
    name: 'blah',
    product_data: {
        '<some product id>': '<some product name>',
        '<another product id>': '<another product name>'
    }
}

On the PHP side, you can access the product data as an associative array by the key product_data from the $_POST array. Now it's up to you how to collect the form data.

Update:

$products = $_POST['product_data'];
foreach($products as $product_id => $product_name){
    echo $product_id.', '.$product_name;
}
share|improve this answer
    
Thanks! Can you give me a code example for the PHP side? I am not exactly following. –  zeckdude Apr 14 '13 at 2:32
    
Check now... I've updated the answer. –  Rutwick Gangurde Apr 14 '13 at 2:56

Just pass the arrays to the data parameter

var productIds = ["6", "1"];
var quantities = ["1", "4"];
$.ajax ({
  type: "POST",
  url: "./pay.php",
  dataType: "json",
  data: {
    "firstName" : firstName,
    "lastName" : lastName,
    "email" : email,
    "price" : price,
    "productIds": productIds,
    "quantities": quantities
  }  
});
share|improve this answer
    
And then I should be able to access them on the PHP script like I have written in my question? –  zeckdude Apr 14 '13 at 2:07
1  
@zeckdude Yep, with your foreach and $_POST['productIds'][$i] –  Ian Apr 14 '13 at 2:32
    
I am trying to send the arrays as you have shown above, but when I try to print_r the array on the PHP side, I receive an ajax error response. I assume there is a PHP error on the PHP side I cannot see. Any ideas how I can see those? –  zeckdude Apr 14 '13 at 2:34
    
@zeckdude Well why are you trying to print_r the array? That means it'll be included in the response back to AJAX. Are you sure you want that to be returned to the Javascript? –  Ian Apr 14 '13 at 2:39
    
@zeckdude remove dataType: "json", since your response is not json. –  Musa Apr 14 '13 at 5:19

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.