0

I want to send an array to PHP (POST method) using jQuery.

This is my code to send a POST request:

$.post("insert.php", {
    // Arrays
    customerID: customer,
    actionID: action
})

This is my PHP code to read the POST data:

$variable = $_POST['customerID']; // I know this is vulnerable to SQLi

If I try to read the array passed with $.post, I only get the first element. If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".

How can I get the complete array in PHP?

Thanks for your help.

Tom Pažourek
  • 9,582
  • 8
  • 66
  • 107
letsTry420
  • 11
  • 1
  • 6
  • 2
    What error you are getting? and also show your php code – Pankaj Makwana Feb 14 '18 at 13:11
  • 1
    Possible duplicate of [jQuery Ajax POST example with PHP](https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – Julien Ambos Feb 14 '18 at 13:15
  • i dont get an error in my IDE. I get an "HTTP status 500" error if i inspect post data with fiddler. – letsTry420 Feb 14 '18 at 13:22
  • 1
    If you get a Status 500, then there is an error message somewhere! – rollstuhlfahrer Feb 14 '18 at 13:24
  • A 500 usually means the web server handling the POST has encountered an abnormal condition. You should verify that the server is configure appropriately if you can. Otherwise there isn't much you can do. –  Feb 14 '18 at 15:16

1 Answers1

0

To send data from JS to PHP you can use $.ajax :

1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.

JS:

var array = {
                'customerID': customer,
                'actionID'  : action
            };

$.ajax({
    type: "POST",
    dataType: "json",
    url: "insert.php",
    data:
        {
            "data" : array    

        },
    success: function (response) {
        // Do something if it works
    },
    error:    function(x,e,t){
       // Do something if it doesn't works
    }
});

PHP:

<?php

$result['message'] = "";
$result['type']    = "";

$array = $_POST['data']; // your array 

// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';


// now do what you want with your array and send back some JSON data in your JS if all is ok, for example : 

$result['message'] = "All is ok !";
$result['type']    = "success";

echo json_encode($result);

Is it what you are looking for?

Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36