1

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?? enter image description here

6
  • don't you need to jsonencode stuff before you post it as you're just posting an array of json data to php which php obviously can't decode as its an array not a jsonencoded array of json data. Commented Dec 16, 2013 at 12:21
  • 1
    try with 'var stuff = new Array()' instead of 'var stuff = new Object()'; Commented Dec 16, 2013 at 12:21
  • A simple google search led me to this question. Commented Dec 16, 2013 at 12:21
  • @anand4tech still same msg 'undefined' Commented Dec 16, 2013 at 12:27
  • @anand4tech: try not to use new in JS when there is a shorter, more consistent alternative (var stuff = []; or var stuff = {}) Commented Dec 16, 2013 at 12:30

3 Answers 3

3

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...

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for such a knowledgeable answer. Im new to this stuff and this will be quite a help.. I changed to var stuff= {}; and changed the ajax data:{data: stuff}, and also the php.. it returned 'data' => string '[object Object]'.. but still not showed the data..
@Parminder: But stuff is used as an array, don't declare it as an object, change it to an array declaration: var stuff = [];. The fact that you're getting [object Object] tells me that, somewhere down the line, your array of objects is getting coerced to a string, not JSON stringified... Is the code you posted the actual, real, full code?
yes i've copy pasted the code which i am trying. what should i do make it working? This is my first time with json data..
@Parminder: Just enlarged your screenshot: PHP isn't showing undefined. That's JS. Ajax is Asynchronous. Whatever PHP returns, will be dealt with in the success or error callback functions. You'll have to wait for the server to respond, and add console.log statements in the success and error functions. Add a console.log(arguments) statement to both functions, to see what arguments are being passed to those functions, and see if the response you're looking for is one of those arguments...
@Parminder Your error callback function is wrong. There is no e.message. e returns the jqXHR object and it has no property named message, therefore your console.log outputs unidentified.
|
1

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

6 Comments

You don't stringify. Look at this question which I just answered a few hours ago: stackoverflow.com/questions/20607905/…
I would refrain from using http_get_request_body() since it depends on the PECL extension pecl_http. It's $_POST['data'] in PHP.
@user555 haven't used PHP at all... since I was saying about request body just did a google search and copy pasted the code... can you suggest a better solution
@ArunPJohny Just replace http_get_request_body() with $_POST['data'].
@user555 that won't work because it looks for a request parameter called data but there are no parameters when we are using request body... we need to read request body as a string... not a request parameter
|
0

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..

Comments

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.