简体   繁体   中英

not able to pass json data to php via ajax

This is the following code that I am using.

Javascript

    <script type="text/javascript">
    var stuff = new Object();
    stuff[0] = {'id':'0','value':'no','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
    stuff[1] = {'id':'1','value':'yes','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
    stuff[2] = {'id':'2','value':'yes','type':'img','filename':'hsdssssdfhe.jpg','filesize':'0.4356 MB','fileformat':'png','change':'0','caption':'description 2 of the image'};
    stuff[3] = {'id':'3','value':'yes','type':'vid','filename':'hehehehe.mp4','filesize':'56 MB','fileformat':'mp4','change':'0','caption':'this is video'};
    console.log(stuff);

    $.ajax({
    type: "POST",
    dataType: "json",
    url: "test1.php",
    data: stuff,
    success: function(data){
        alert('Items added');
    },
    error: function(e){
        console.log(e.message);
    }
    });
    </script>

test1.php

    <?php
    $arr = json_decode($_POST['data'], true);
    print_r($arr);
    ?>

The console on Chrome shows the object but php shows undefined.. How can I use the json data in PHP?? 在此输入图像描述

Several things are "wrong" with your code.
Firstly the JS:

stuff = new Object();

Now this isn't wrong as such, but it's generally recommended not to call object constructors like this. You should instead get into the habit of using the literal notations. Seeing as calling constructors may cause unexpected results:

var arr = new Array(10);
var arr2 = [10];
console.log(arr2.length);//logs 1, the array looks like this [10]
console.log(arr.length);//logs 10, arr is [undefined, undefined, undefined,...]
//but at the same time:
var arr3 = new Array(1,2);//is identical to:
var arr4 = [1,2];//both create an array containing 2 numbers: [1,2]

Same goes for Object :

var o = new Object();//same as var o = {};
var o2 = new Object('foobar');
console.log(o2);//String {0: 'f', 1: 'o', 2: 'o', ...}
//and so on:
new Object(true);// === new Boolean(true)
new Object(123);// === new Number(123);

But you're then using this Object as an Array !! That doesn't make sense, instead, just write:

stuff = [];
//or
stuff = [ {id: 0, ...}];//initialize array from the off

JS doesn't complain when you use an object as an array, because arrays are instances of Object :

console.log(Object.getPrototypeOf(Array.prototype));//Object!

An Array is an augmented Object , basically

Next, the PHP side:

$_POST['data'];

As I've shown above, you're just sending an array to your PHP script. An array with numeric indexes does not have a "data" key . Try:

var_dump($_POST);

And you'll see what you're actually sending to your server.
All in all, what you're actually trying to do, I think is this:

$.ajax({ url: 'your.php',
    data: {data: stuff},//send an object, with property data
    success: function(data)
    {
        console.log(data);//log the PHP response
    }
});

You also seem to be forgetting that AJAX requests are asynchonous . The undefined that shows up in your console is a JS thing, the result of console.log , which returns undefined.
The AJAX request hasn't been performed yet. To see what your request is actually doing, open the Network tab (third from the left) in your console. On the bottom, you'll see XHR somewhere. Click that, and you should see a POST request go out. You can click on it, and see the headers, the response and what not...

You are reading a post parameter called data but it is not send

Try

data: {
    data: JSON.stringify(stuff)
}

Since you are transferring json data look at sending the data as request body like

$.ajax({
    type: "POST",
    dataType: "json",
    url: "test1.php",
    contentType: 'application/json',
    data: JSON.stringify(stuff),
    success: function (data) {
        alert('Items added');
    },
    error: function (e) {
        console.log(e.message);
    }
});

then in server side(not a PHP guy so not sure) using http-get-request-body

$arr = json_decode(http_get_request_body(), true);

I was able to make it working.. thnks to all of you for suggestions.. only minor changes..

JS

    <script type="text/javascript">
    var stuff = [];   // changed from var stuff = new object();
    stuff[0] = {'id':'0','value':'no','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
    stuff[1] = {'id':'1','value':'yes','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
     stuff[2] = {'id':'2','value':'yes','type':'img','filename':'hsdssssdfhe.jpg','filesize':'0.4356 MB','fileformat':'png','change':'0','caption':'description 2 of the image'};
     stuff[3] = {'id':'3','value':'yes','type':'vid','filename':'hehehehe.mp4','filesize':'56 MB','fileformat':'mp4','change':'0','caption':'this is video'};
     console.log(stuff);
    var a = JSON.stringify(stuff);  //this is required otherwise it sends the object to php rather JSON string.
    $.ajax({
    type: "POST",
    dataType: "json",
    url: "test1.php",
    data: a,
    success: function(data){

    },
    error: function(e){
        console.log(e.responseText);   //changed from e.message no message argument in error response . thanks to @user555 valuable suggestion
    }
    });
    </script>

test1.php

    <?php  $data = $_POST['data'];
    $arr = json_decode($data, true);
    echo $arr[3]['type'];
    ?>    

The output is vid in console. It is properly returning the array value. It will show the result in the console. This is a working example, anyone can copy and paste for exploring more. It has helped me a lot, it will definitely help you too..

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