简体   繁体   中英

Ajax won't send data to PHP

SOLVED: The code posted here was correct, but some of the PHP code connecting to the database needed fixing, I have it working now. I used Quentin 's suggestions in the comments to fix my problem.

I'm trying to send a JSON of an array through ajax to a PHP file, then have the php file run. This is my ajax:

    $('#submit').click(function() {
  $.ajax({
    method: "POST",
    url: "submit.php",
    data: {selectedImageArray: selectedImageArray}
  }).done(function( msg ) {
    alert( "Data Saved: " + selectedImageArray );

  });
});

In my PHP file I connect to a database then have this:

$array = $_POST['selectedImageArray'];
    $sql = $dbh->prepare("INSERT INTO pending_trades (steam_id, trade_items, is_giving, is_receiving, has_started) VALUES (:steamid, :itemlist, '1', '0', '0')");
    $sql->bindParam(':steamid', $steamprofile['steamid']);
    $sql->bindParam(':itemlist', $array);

    $sql->execute();

I want this to send the "selectedImageArray" json to the php and run the msql query using it on the press of this button:

<button id="submit" class="button1" >Submit<span></span></button>

When the button is clicked, I get the "data saved: array data " message, but the php code isn't run. Why isn't this working?

EDIT: I set data: {selectedImageArray: selectedImageArray} instead of data: selectedImageArray because I was told it makes it into JSON format, is that correct?

you are adding in database an array not an string try to use:

$sql->bindParam(':itemlist', json_encode($array));

and when you get the data just run:

$array = json_decode($itemlist);

You can add content type JSON. other wise it will consider as text.

var data = JSON.stringify({selectedImageArray: selectedImageArray});
 $.ajax({
method: "POST",
dataType: 'json', // If your response is JSON
contentType: "application/json",
url: "submit.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + selectedImageArray );
include ('submit.php');
});

First of all look at your browser debugger of what is really sent to the php file. Second thing: You will send JSON to it. That means, that you have an POST form Array like this:

[{
   "key1": "value1",
   "key2": "value2"
}]

So, in conclusion this does not work:

$array = $_POST['selectedImageArray'];

You need to access eg $_POST['key1'] directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM