1

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?

4
  • 1
    You're just missing the $ at the beginning of $i in the subscripts. Commented Apr 14, 2013 at 2:02
  • Did you try just doing print_r($_POST['productIds']) to see what's in there? Commented Apr 14, 2013 at 2:04
  • Show the output of var_dump($_POST). Commented Apr 14, 2013 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? Commented Apr 14, 2013 at 2:24

3 Answers 3

2

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
  }  
});
Sign up to request clarification or add additional context in comments.

5 Comments

And then I should be able to access them on the PHP script like I have written in my question?
@zeckdude Yep, with your foreach and $_POST['productIds'][$i]
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 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?
@zeckdude remove dataType: "json", since your response is not json.
1

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;
}

1 Comment

Thanks! Can you give me a code example for the PHP side? I am not exactly following.
0

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
});

1 Comment

This looks interesting but I cannot see how to implement this on the javascript side. Can you help me out with that?

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.