JSON PHP decode not working - php

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":"me#me.com",
"dob":"1973-01-22",
"age":"51",
}],
"HealthData":
[
"condition : Prone to Fainting / Dizziness",
"condition : Allergic Response to Plasters",
],
"someData":
[{
"firstName":"Male",
"lastName":"checking",
}]
}
Code as is:
{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","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) {
}
});
}

There are a few things that will cause problems:
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.
'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"

$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":"me#me.com","‌​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);

Related

Passing a jQuery array to PHP (POST)

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

jQuery AJAX request returns object

I have the following AJAX request:
$(function(){
$("#MPrzezn").typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'test',
displayKey: 'value',
source: function(query, process){
$.ajax({
url: 'sprawdzKraj.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
console.log(data);
}
});
}
});
});
... and the following php on backend:
<?php
require_once 'core/init.php';
$user = new User(); //current User
if($user->isLoggedIn()){
if(isset($_POST['query'])){
$query = $_POST['query'];
$delegacja = new Delegacja();
$dataListaDelegacji = $delegacja->listujMiasta($query);
header('Content-Type: application/json');
$json_response = json_encode($dataListaDelegacji);
echo $json_response;
}
} else {
$isLoggedIn = false;
$smarty->assign("userid","",true);
$smarty->assign("isLoggedIn",$isLoggedIn,true);
Redirect::to('login.php');
}
The php script returns a proper json:
[{"ID":"66","IDKraju":"117","NazwaMiasta":"Inowroc\u0142aw","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"251","IDKraju":"117","NazwaMiasta":"\u015awinouj\u015bcie","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"2222","IDKraju":"74","NazwaMiasta":"Rhinow","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"3508","IDKraju":"94","NazwaMiasta":"San Bernardino","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null}]
The picture below shows how the json is being picked up by browser:
There are 4 cities that match the query - each object is a city entry
My goal is to pass values of "NazwaMiasta" to a typeahead input, but I get "undefined" entries. I tried different things but it always keeps showing undefined like this:
Red arrows show all 4 json nodes
I hope I described my problem well. I understand that I'm pretty close, but I cannot find the solution myself. I'll appreciate any help.
Thanks
You have to put right displayKey value!
insted of :
displayKey: 'value',
set :
displayKey: 'NazwaMiasta',
EDIT :
Detailed explanation : When you return data via ajax call, typeahead doesn't know what value to display. So you must set where is value for that key. Your return array of object that have structure like this :
['key1':'value1', 'key2':'value2',...]
By setting ie 'key1' , typeahead knows how to access value ie :
currentElement['key1']...
and than put that value to html.

Resource POST Acting as GET method angularjs

I am trying to learn angularjs, so today i tryed using resource.
looks like it all went good at syntax and method calling,
Please open the FIDDLE first
Initially i tried with $http POST, looks like it worked
$http({url: '/register.php', method: "POST",
data: { 'message' : {userName:'ravi'}}});
With PHP code:
$data = file_get_contents("php://input");
$objData = json_decode($data);
....
....
//insert stmt to mysql
Next, When i tried with $resource, with
In registerController
authProviders.saveUser($scope.newuser);
In authProviders service :
return $resource(AppConstants.ServerPath + '/register.php/:registerId',
{registerId: '#registerId'},{
saveUser: {
method: 'POST',
params: { message: {userName:'ravi'} },
isArray: false
}
});
The call is going like get method.
Can any Body of you please Correct me in these.
My question question :
When you fill the form and submit which is in fiddle, the URL in the console look like
http://fiddle.jshell.net/register.php?message=%7B%22userName%22:%22ravi%22%7D
Which looks like GET method, even through the method type is POST
Thanks in Advance.
Remove params from Resources:
return $resource(AppConstants.ServerPath + '/register.php/:registerId',
{registerId: '#registerId'},{
saveUser: {
method: 'POST',
params: { message: {userName:'ravi'} }, //Remove This
isArray: false
}
});
If you want to use the GET method, then you have to say
method: 'GET',
params: { message: {userName:'ravi'} },
If you want to make it as POST, then
method: 'POST',
data: { message: {userName:'ravi'} },

ExtJs4 Trouble with null JSON server side on store.sync

here is my store code:
var sql = Ext.create('Ext.data.Store', {
model: 'SQL',
groupField: 'project',
proxy: {
type:'ajax',
api: {
read: 'data/showText.php', // Called when reading existing records
update: 'data/saveRollout.php' // Called when updating existing records
},
actionMethods: {
read : 'GET',
update : 'POST'
},
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json'
}
},
autoSync: true,
autoLoad: true
});
It sends right json code
{
"projectId":102,
"project":"2G Rollout and Performance",
"taskId":123,
"description":"2)Capacity Sites Delta",
"january":123,
"february":0,
"march":0,
"april":0,
"may":0,
"june":0,
"july":0,
"august":0,
"september":0,
"october":0,
"november":0,
"december":0,
"id":null
}
But there is NULL on response in php file
var_dump(json_decode($_POST, true));// shows NULL on response
You are actually sending your data to the server via the request body, not via the url.
Using:
$iRequestBody = file_get_contents('php://input');
Will work.
See similar issue and some (additional) excellent answers.
Have you tried taking out:
writer: {
type: 'json'
}
To see if it handles regular text sent to the server, maybe your server is not handling the JSON encoding well.

Simple jQuery, PHP and JSONP example?

I am facing the same-origin policy problem, and by researching the subject, I found that the best way for my particular project would be to use JSONP to do cross-origin requests.
I've been reading this article from IBM about JSONP, however I am not 100% clear on what is going on.
All I am asking for here, is a simple jQuery>PHP JSONP request (or whatever the terminology may be ;) ) - something like this (obviously it is incorrect, its just so you can get an idea of what I am trying to achieve :) ):
jQuery:
$.post('http://MySite.com/MyHandler.php',{firstname:'Jeff'},function(res){
alert('Your name is '+res);
});
PHP:
<?php
$fname = $_POST['firstname'];
if($fname=='Jeff')
{
echo 'Jeff Hansen';
}
?>
How would I go about converting this into a proper JSONP request? And if I were to store HTML in the result to be returned, would that work too?
When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here
If you look at the source code you can see that I am calling the Twitter API using .getJSON.
So your example would be:
THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)
//JAVASCRIPT
$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
alert('Your name is '+res.fullname);
});
//SERVER SIDE
<?php
$fname = $_GET['firstname'];
if($fname=='Jeff')
{
//header("Content-Type: application/json");
echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
}
?>
Note the ?callback=? and +res.fullname
First of all you can't make a POST request using JSONP.
What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.
Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.
This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.
The best thing to do is adding &callback=? to you url.
At the server side you've got to make sure that your data is wrapped in this callback function.
ie.
echo $_GET['callback'] . '(' . $data . ')';
EDIT:
Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.
Replace Liam's line
echo "{'fullname' : 'Jeff Hansen'}";
with
echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
More Suggestion
JavaScript:
$.ajax({
url: "http://FullUrl",
dataType: 'jsonp',
success: function (data) {
//Data from the server in the in the variable "data"
//In the form of an array
}
});
PHP CallBack:
<?php
$array = array(
'0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
'1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);
if(isset ($_GET['callback']))
{
header("Content-Type: application/json");
echo $_GET['callback']."(".json_encode($array).")";
}
?>
To make the server respond with a valid JSONP array, wrap the JSON in brackets () and preprend the callback:
echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";
Using json_encode() will convert a native PHP array into JSON:
$array = array(
'fullname' => 'Jeff Hansen',
'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";
Simple jQuery, PHP and JSONP example is below:
window.onload = function(){
$.ajax({
cache: false,
url: "https://jsonplaceholder.typicode.com/users/2",
dataType: 'jsonp',
type: 'GET',
success: function(data){
console.log('data', data)
},
error: function(data){
console.log(data);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$.ajax({
type: "GET",
url: '<?php echo Base_url("user/your function");?>',
data: {name: mail},
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'chekEmailTaken',
success: function(msg){
}
});
return true;
In controller:
public function ajax_checkjp(){
$checkType = $_GET['name'];
echo $_GET['callback']. '(' . json_encode($result) . ');';
}
Use this ..
$str = rawurldecode($_SERVER['REQUEST_URI']);
$arr = explode("{",$str);
$arr1 = explode("}", $arr[1]);
$jsS = '{'.$arr1[0].'}';
$data = json_decode($jsS,true);
Now ..
use $data['elemname'] to access the values.
send jsonp request with JSON Object.
Request format :
$.ajax({
method : 'POST',
url : 'xxx.com',
data : JSONDataObj, //Use JSON.stringfy before sending data
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
success : function(response){
console.log(response);
}
})

Categories