AJAX, JSON, jQuery, and PHP - 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'];

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

POST data not appearing in CakePHP controller

I'm using AJAX on a knockout.js form to post some information that CakePHP should receive, however, Cake doesn't seem to find anything. Also, the alert isn't appearing despite a 200 status (OK) from the POST.
Here's the AJAX
$.ajax({
url: "/orders/finalize_payment",
type: "POST",
dataType: "json",
contentType: "json",
data: JSON.stringify({"customer": customer_id}),
success: function(){
alert("success");
}
});
Here's the corresponding action in the orders controller. Right now, I completely stripped it to just the bare minimum.
function finalize_payment($id = null){
$this->layout = false;
$this->autoRender = false;
if($this->request->is('post')){ //the user has submitted which status to view
print_r($this->request->data);
echo "test"; //just to make sure it's reaching this point
}
}
When I open up the network tab in chrome, it shows the request payload as
customer: 1
The POST shows as success, status 200. I checked the response headers and it just shows
array
(
)
test
Despite chrome showing a payload being sent, CakePHP isn't finding it apparently.
Update
I changed the request from AJAX to $.post and it worked. I still have no clue why
$.post("/orders/finalize_payment",{"customer_id":customer_id},function(data){
alert('success');
});
Don't encode post data as json
The code in the question won't appear in any php script, the reason is this:
contentType: "json"
It's not a form-url-encoded request, so e.g. the following code:
print_r($_POST);
print_r(file_get_contents('php://input'));
will output:
Array()
'{"customer":123}'
If you want to submit data as json, you'll need to read the raw request body:
$data = json_decode(file_get_contents('php://input'));
There might be times when that's desirable (api usage), but that isn't the normal way to use $.post.
The normal way
The normal way to submit data, is to let jQuery take care of encoding things for you:
$.ajax({
url: "/orders/finalize_payment",
type: "POST",
dataType: "json", // this is optional - indicates the expected response format
data: {"customer": customer_id},
success: function(){
alert("success");
}
});
This will submit the post data as application/x-www-form-urlencoded and be available as $this->request->data in the controller.
Why $.post works
I changed the request from AJAX to $.post and it worked. I still have no clue why
Implicitly with the updated code in the question you have:
removed the JSON.stringify call
changed from submitting json to submitting application/x-www-form-urlencoded
As such, it's not that $.post works and $.ajax didn't ($.post infact just calls $.ajax) - it's that the parameters for the resultant $.ajax call are correct with the syntax in the question.
As you're using CakePHP you may find adding RequestHandler to your components fixes the problem.
public $components = array([snip], 'RequestHandler');
Doing this allowed me to transparently access JSON posted data using $this->request->data. The other answer's advice to not encode POST data as JSON becomes a bit awkward, given that certain JS frameworks, such as Angular, post JSON as default.
Using raw data and json you can use:
$data = $this->request->input('json_decode');
**Data is an object now, not an array.
Then you can use:
$this->MyModel->save($data).
Nicely formatted question :)
I'm pretty sure I have the answer, though I could be wrong... Basically, $this->request is an object in Cake, and $this->request->data is a variable/array that's a property of the object.
The data you're sending to Cake is going straight into the object (if this is even possible), not into the data array. This is why when Cake generates forms using the HtmlHelper, the names are, for example data[User][username].
I think, if you put JSON.stringify({"customer": customer_id}) into a 'data' array and send that, it should work.
Have a look at this post. You're data string probably isn't correct. Therefore CakePHP might not be able to put it in $this->request->data.
Use print_r($this->request->params);
function finalize_payment($id = null){
$this->layout = false;
$this->autoRender = false;
if($this->request->is('post')){ view
print_r($this->request->params);
} }

How to retrieve values from a JSON Object in 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

Jquery variables in JSON to PHP

I'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://example/ajax",
data: { test: test },
cache: false,
async: true,
success: function( json ){
$.each( json.rows, function( i, object ){
//Example: object.date
<?php date('g:ia', $objectDate ) ?>;
});
}
});
What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?
PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.
You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.
In summary what you should do is:
Pass some data from client to server with an AJAX call
PHP processes these data and returns a JSON object
JS processes the JSON object and, for instance, modifies the HTML of the page.
If you need to further process newly generated data with PHP do other AJAX calls.
Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.
Here's a basic rundown of going from JS to PHP, and PHP to JS:
To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:
var data = { message: "Hello" };
$.ajax({
data: { data: JSON.stringify(data) },
// ...
});
Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:
$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"
To send JSON back as the response to the browser (for your success callback), use json_encode like so:
header('Content-type: application/json');
echo json_encode(array(
'message' => 'Hello, back'
));

Is this a jQuery bug, or am I missing something?

I am using jquery-1.3.2 in an AJAX web application. I use the jQuery ajax $.post() method to submit requests to the server.
On the server I am using php to build an array and then json_encode the answer. Then on the client I use the callback function of the AJAX post method to process the response.
All works well until I use the $.post() method to send variables to the server. If I send variables to the server, the response I get back is [object Object] and therefore I am unable to parse it. I have a work around at the moment that when posting variables I request a HTML response and then I parse that.
So the code involved taken from my site is:
The Jax call:
$.post("inc/sendfeedback.php", {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment}, function(data) {PostData(data);}, "json");
So the PostData code looks like this:
function ProcessData(data)
{
//alert(data);
var jo = eval("(" + data + ")");
if(jo.result == "true")
{
if(jo.data != "" && jo.element != "")
{
$(jo.element).html(jo.data);
}
}
SMessage(jo.error);
}
If I uncomment the above code the alert with have in it [object Object].
if I remove the Post variables from the call it works fine.
The server code look like this:
$arr = array ("result" => $result,"data" => $data,"error" => $error,"element" => $element);
echo(json_encode($arr));
Is this a bug with the jQuery library, I tried it with the 1.2 version however its was still present there? I also search the jQuery site and can not find anyone having this issue.
So I assume I am missing something. But what?
$.ajax({
url: "script.php",
global: false,
type: "POST",
data: {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment},
dataType: "json",
contentType: "application/json",
success: function(data){
alert(data.result);
}
}
No need to eval, jQuery evals/parses it before calling the success callback.
eval = pure evil
http://docs.jquery.com/Ajax/jQuery.ajax#options
Because you are using an associative PHP array, json_encode will return a string representation of a Javascript Object and not a Javascript Array. However, you should still be able to process it in a similar fashion to an array:
for (var key in data)
{
var item = data[key];
}
I would strongly recommend you download Firefox+Firebug addon and use the console API for debugging/dumping what is being returned by the server.
I have since registered and now can't post comments into this thread without reputation and can not see any easy method to claim this question as mine.
Deviant, your suggestion of using the $.ajax() method worked. Reason it didnt work for me the first time was I submitted the post data as a JSON object when the server code was expecting POST data.
So I fixed my javascript to call the server script correctly and everything works exactly as it should.
So the conclusion is, the $.post() method has a bug in it. I have not tracked it down but line 3633 is were the post method makes the call. I started digging however have not yet found the issue.
I qualify this by the fact the $.ajax() to the same server script and the same javascript processes the response and it all works, use the $.post method and my script fails with the return even through the return object appears to be a valid JSON object.
Thanks for the help guys. Now to go and remove all my $.post calls for $.ajax calls.
The result of all this can be seen at www.pygames.net
Cheers
Shane
a.k.a FrogSkin

Categories