0

I have seen many examples, but for whatever reason, none seem to work for me.

I have the following sent from a app, via ajax, to a php file. This is how it looks when its sent:


    obj:{"ClientData":
    [{
        "firstName":"Master",
        "lastName":"Tester",
        "email":"[email protected]",
        "dob":"1973-01-22",
        "age":"51",
    }],
    "HealthData":
    [
        "condition : Prone to Fainting / Dizziness",
        "condition : Allergic Response to Plasters",
    ],
    "someData":
    [{
        "firstName":"Male",
        "lastName":"checking",
    }]
    }

Here is how it looks in debugger

Code as is:

{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"[email protected]","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}

This comes in one long line into a php file, here is the code:

<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
//var_dump($_POST['obj']);

$Ojb = json_decode($_POST['obj'],true);

$clientData = $Ojb['ClientData'];
$healthData = $Ojb->HealthData;
$someData = $Ojb->someData;

print_r($clientData['firstName']);    
?>

No matter what I have tried, I am unable to see any of the information, I don't even get an error, just blank! Please can someone point me in the right direction.

Thank you :)

UPDATE

Here is the code that creates the object:

ClientObject = {

        ClientData : [
            {
                firstName : localStorage.getItem('cfn'),
                lastName : localStorage.getItem('cln'),
                email : localStorage.getItem('cem'),
                dob : localStorage.getItem('cdo'),
                age : localStorage.getItem('cag'),
                pierceType : localStorage.getItem('cpt'),
                street : localStorage.getItem('cst'),
                city : localStorage.getItem('cci'),
                county : localStorage.getItem('cco'),
                postcode : localStorage.getItem('cpc')
            }
        ],

        HealthData : health,

        PiercerData : [
        {
                firstName : localStorage.getItem('pfn'),
                lastName : localStorage.getItem('pln'),
                pierceDate : localStorage.getItem('pda'),
                jewelleryType : localStorage.getItem('pjt'),
                jewelleryDesign : localStorage.getItem('pjd'),
                jewellerySize : localStorage.getItem('pjs'),
                idChecked: localStorage.getItem('pid'),
                medicalChecked: localStorage.getItem('pmh'),
                notes: localStorage.getItem('poi')
        }
        ]

    };

And here is how its sent:

function senddata() {
    $.ajax({
        url: 'http://domain.com/app.php',
        type: 'POST',
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        dataType: 'jsonp',              
        data: 'obj='+JSON.stringify(ClientObject),

        success : function(res) {
            console.log(res);

        },
        error: function(err) {

        }
    });
}
12
  • 1
    This doesn't look like valid json to me. Commented Apr 2, 2014 at 13:29
  • what happens if you var_dump($Ojb)? If you get null, then json is invalid. If you still get blank page, then there is PHP error. You might not have the json module installed on the server. Commented Apr 2, 2014 at 13:31
  • possible duplicate stackoverflow.com/questions/16828647/… Commented Apr 2, 2014 at 13:34
  • @quano I do get Null, so that must mean the Json is not valid ? Commented Apr 2, 2014 at 13:40
  • try: $data = file_get_contents('php://input'); var_dump($data);. And post what you get (if anything). (I'm guessing the data is not sent in a way that php can populate the $_POST array with.) Commented Apr 2, 2014 at 13:42

2 Answers 2

3

There are a few things that will cause problems:

  1. why dataType: 'jsonp'? If you don't intend to utilize jsonp, don't instruct jQuery to do this. See the docs: https://api.jquery.com/jQuery.ajax/

    "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

  2. 'obj='+JSON.stringify(ClientObject), this will guarantee invalid json.

For reference, have a look at this question: jQuery ajax, how to send JSON instead of QueryString on how to send json with jquery.


That said, try the following:

function senddata() {
  $.ajax({
    url: 'app.php',
    type: 'POST',
    crossDomain: true,
    contentType: 'application/json; charset=utf-8"',
    data: JSON.stringify(ClientObject),
    success : function(res) {
      console.log(res);
    },
    error: function(err) {
    }
  });
}

And in app.php use

$input = json_decode(file_get_contents('php://input'));

to get the data. Use it like:

var_dump($input->ClientData[0]->firstName); // => string(6) "Master"
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this is exactly the issue is !!
@Yoshi Thank you for the above, and it did print what you put above. The reason I just jsonp is it get around the Access Control error i was getting. Which I again got with your code, but i changed the header and its working
3
$Ojb = json_decode($_POST['obj'],true);

makes it array so u need to get them using array index instead of object

UPDATE1

With your update here how it could be done

$str ='{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"[email protected]","‌​dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["‌​condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDat‌​e":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"‌​Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}' ;

$obj = json_decode($str,true);

echo $obj["ClientData"][0]["firstName"];

You can get other elements as above

UPDATE2

You are sending the data as JSONP and this will make the request as

?callback=jQuery17108448240196903967_1396448041102&{"ClientData"

Now you are also adding data: 'obj=' which is not correct.

You can simply send as json not jsonp

and on the php file you can do as

$Ojb = json_decode(file_get_contents('php://input'),true);

6 Comments

so I would use something like: $Ojb = (array) json_decode($_POST['obj'],true); ?
no no need to use (array) also it does not look like a valid json please post the json string that u received.
Okay @Yoshi But the real data is already above. But will post it without me cleaning it up. I only did that to make it easy to read.
That comes back with a blank screen :(
did u use $Ojb = json_decode($_POST['obj'],true); ? since you are sending data as POST ?
|

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.