How to retrieve values from a JSON Object in PHP - php

I've tried this many times now, using difference methods and none of them have worked for me, so I'm asking this question.
I have a small form that takes in 4 pieces of information, a persons title, first name, middle name and last name. When I hit a button, a JSON Object is formed, and sent as post data through a jQuery.ajax method.
JSON Sent to PHP file:
{
"title": "Mr",
"firstName":"Banana",
"middleName":"Slippy",
"lastName":"McDougle"
}
Ajax call on button press:
function insertPerson(obj, callback){
$.ajax({
type: "POST",
data: "json=" + JSON.stringify(obj),
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
}
I pass in a Javascript Object that is then stringyfied and posted as a parameter name 'json'.
In my php file I assign the posted string to a variable, name $json, I then decode using json_decode(), do some funky business, and send a response back to the browser.
insertData.php:
require ('connect.php');
header('Content-type: application/json');
$json_string = $_POST['json'];
$json = json_decode($json_string);
...do server related inserts/selects etc...
echo json_encode($json->title);
At the moment I just want to return the title property of the json object that was sent in the post request, but anything I return comes back as null. If I echo back the string, without decoding it, then I get the following:
{\"title\":\"Mr\",\"firstName\":\"Banana\",\"middleName\":\"Slippy\",\"lastName\":\"McDougle\"}
If I try to extract values using:
$title = $json->title;
and put that into a MYSQL statement, it's inserted as null or blank, nothing gets input.
Am I doing something wrong? Or have I somehow got an outdated version of PHP to handle JSON? And help is greatly appreciated.

Why do you want to send JSON to the PHP script? What's wrong with using a query string?
$.ajax({
type: "POST",
data: obj,
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
This will convert obj to a query string, and then you can just do $_POST['firstName'] and $_POST['lastName'].

I think this is the best shot for you.
jQuery Ajax POST example with PHP

Related

Extracted json url from example.com/myjsonsql.php to jquery mobile fail to return value

i am a new php developers i was trying to create a simple system where i use php to extract database from mysql and use json in jquery mobile.
So here is the situation,
I've created a custom .php json (to extract data from mysql) on my website and i've successfully upload it onto my website eg: www.example.com/mysqljson.php
This is my code extracting mysql data `
header('content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('mydb');
$select = mysql_query('SELECT * FROM sample');
$rows=array();
while($row=mysql_fetch_array($select))
{
$rows[] = array('id'=>$row['id'], 'id'=>$row['id'], 'username'=>$row['username'], 'mobileno'=>$row['mobileno'], 'gangsa'=>$row['gangsa'], 'total'=>$row['total']);
}
echo json_encode($rows);`
Which in returns gives me the following json # http://i.imgur.com/d4HIxAA.png?1
Everything seems fine, but when i try to use the json url for extraction on jquery mobile it doesn't return any value.
i extract the json by using the following code;
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
},
error: function(e) {
console.log(e.message);
}
});
}
The json.id # #current_temp and json.id.username # #current_sum dint return any result on my jquery mobile page.
I suspected i didn't extracted the json url correctly, but im not sure, could anyone help me identify the problem?
Thank you.
jsonp expects a callback function to be defined in the json being retrieved - for ecample see here.
Your data print screen is actually plain old fashioned json, not jsonp.
So I see 2 options:
change the php data to render jsonp (this assumes you have control over data source).
change your jquery request to expect plain old fastioned json (this assumes client and server are on same domain, otherwise CORS error happen), e.g,,
$.get(forecastURL)
.then(function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
})
.fail(function(e) {
console.log(e.message);
});
First of all, you don't have to use jsonp to retrieve JSON. You could just do a simple Ajax Call. jQuery convert automatically your json string to a json object if your HTTP response contains the good Content-Type. And you did this good in your PHP call.
I think your problem comes from your json data analysis in your javascript success callback. The json generated is an array containing some user objects. In your code you don't work on one item of the array but you directly call .id or .username on the array. So javascript give you undefined values.
Here is an example displaying the data for the first item (index 0) of your json array. You have after that to choose for your own purpose how to treat your array objects but it's an example:
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
success: function(json) {
console.log(json);
// See, I use [0] to get the first item of the array.
$("#current_temp").html(json[0].id);
$("#current_summ").html(json[0].username);
},
error: function(e) {
console.log(e.message);
}
});
}

JS Ajax calling PHP and getting ajax call data

I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)

Why is this ajax post giving me an error? Does an ajax post require "true" or "false" to be returned?

$.ajax({
url:"http://www.xxxxxxxxxxxxxx.com/cc/validate",
type:"POST",
dataType:"json",
data: JSON.encode($parts),
complete: function(){
},
success: function(n)
{
console.log(n);
console.log(n.object);
console.log("ajax complete");
},
error: function(){
console.log("error");
}
});
This gets an array defined above the ajax post call and posts an encoded json array to a php file. The problem is determining why the post will only let me return "true" or "false". If i try to return any string, i get the error in the ajax. I want to be able to return a string created in the php and not only "true" or "false".
are you on a local host? well if so you might have to change your mime headers (application/json) ... your javascript is expecting json but your php is echoing html.
header('Content-type: application/json');
if you want to be able to return something else then json you have to delete or change the content type in your ajax call. the content type is for giving jquery a hint of what to expect from the server. if you tell it will receive json data you need to give it json or you'll have a parse error.
your code is alright
just make sure your php file return an echo json_encode($arrayOFdata)
dataType:"json",
means the data recived from php will be parsed as a json object
it doesn't mean you will send a json object

AJAX, POST, JSON, and PHP: How do I do it?

How do I send AJAX data through $.ajax() in JavaScript via type: "POST" using JSON data formatting and how do I receive the data in a PHP script (through $_POST??) and put it into an array so I can use it? I've been kicking at this for hours and I have no idea what I'm doing wrong. If someone could post the JS and PHP code for sending and receiving JSON formatted data, I would be eternally grateful!!!!!
JS Code:
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"value1": 1,
"value2": 2,
"value3": 3,
"value4": 4,
"value5": 5
},
dataType: "json"
});
PHP Code:
I was just using $_POST["value1"], etc., to get that value. On that note, is there a way to make the ajax request GET instead AND open up a new window with that GET data on it so I can see what's going on??
The idea is to create a php page the outputs data in JSON form. This data is taken from an array and echoed using the json_encode function. Using the $.ajax() method from jQuery, you send a request to that page and manipulate the data in the success: function.
Example.
PHP - array.php
$array = ("flag" => 1);
echo json_encode($array);
JavaScript
$.ajax({
url : '/array.php', // page containing JSON data
dataType : 'json', // must be specified for JSON manipulation in success
success : function(data) {
// this function is called if the call to test.php is successful
// access the data using object dot syntax
alert(data.flag); // should display '1'
}
});
// Send data to server this way
PHP - test.php
echo $_POST['data'];
JavaScript
$.ajax({
url : '/test.php',
dataType : 'text',
type : 'post',
data : { data : 'Hello, World!'},
success : function(data)
alert(data); // should display 'Hello, World'
}
});
As far as I know you can't POST data in a JSON format. Only as a query string, like GET. You can however return data from the PHP script in a JSON format.
Eg.
$.ajax({
url: "script.php",
dataType: 'json', // Tell jQuery/JS that the returned data from script.php is JSON format
data: 'id='+Id, // will become $_POST['id'] with the value of Id (js var)
success: function(data){
// data is JSON formatted
}
Now, in your PHP script, you receive a POST variable called $_POST['id'].
Let's say that $_POST['id'] is needed to request a certain customer from the database. Its data can be stored in an array and then json encoded and then send back to the page with the ajax request.

AJAX, JSON, jQuery, and PHP

I know there are alot of different questions about this but none of them seem to pertain to me. I have an ajax request as follows:
var responsePacket;
$.ajax({
dataType: 'json',
type:'POST',
data:{
"updatePacket":{
"job":"name-update",
"firstName":firstName,
"lastName":lastName
}
},
processData: false,
url:'modify.php',
success: function(json){
console.log(json);
responsePacket = json;
if(responsePacket.updateStatus==true){
genAlertAlignAndShow('Name Successfully Updated', false, 4000);
}
else{
genErrorAlignAndShow('Name Update Failed!', false, 4000);
}
}
})
And my PHP on the other end are as follows:
$updatePacket = json_decode($_POST['updatePacket'], true);
//and I access variables from the JSON Object like this:
$job = $updatePacket['job'];
In response to the AJAX, the PHP file will punch out a simple JSON object, and yes my headers are set to application/json. This is how I a output a JSON response, I have tested it and it appears to get back to the AJAX Request when I rig it to return a static response:
$responsePacket = array("updateStatus"=>true);
echo json_encode($responsePacket);
But Here Is The Problem
As you can see I output the data to the console, but all it says is null which I have deduced is indicative of the JSON not getting to the PHP correctly. So, is there a proper way to create JSON Objects and prepare an AJAX request that will get the data to the PHP script intact.
I have been grappling with this problem for about 3 hours now, ANY suggestions are welcome.
I believe $_POST['updatePacket'] is not actually a json string. Try to access it like this instead:
$updatePacket = $_POST['updatePacket'];
$job = $updatePacket['job'];
No need to json_decode() it. From the json_decode() manual (return value):
NULL is returned if the json cannot be decoded...
Give it a try. As mentioned in the comments, var_dump($_POST); should be the first thing you try, to ensure you're getting what you think you are.
I figured it out. Here is my AJAX Requst:
$.post('modify.php', { job: "name-update", lastName: lastName }, function(data){
console.log(data);
})
The Problem:
When declaring data for an AJAX Post request putting quotes on the variable names will make the variables inaccessible to the receiving script.
You can easily make the time consuming issue of getting form data in a clean way with jquery, or javascript alone.
All you need to do is .serialize() the data. An example is here.
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});
Once it is done you can transform a string that looks like this.
"param1=someVal&param2=someOtherVal"
with this
$params = array();
parse_str($_GET, $params);
with this usage you also want to filter the data and you should do this prior to the above.
http://php.net/manual/en/function.filter-input.php
Do this is less time consuming then listing each one individually in your ajax. You can also create a function to do this so you aren't continually writing ajax boilerplate code.
You are doing it wrong. You don't send a JSON object to the server, you send key/value pairs. And it's what jQuery expects. Do it like this instead:
data: {
"job": "name-update",
"firstName": firstName,
"lastName": lastName
},
and access the values like this:
$job = $_POST['job'];

Categories