How to use dojo.xhrPost properly? - php

Here is my JS:
<script>
dojo.require("dijit.form.Button");
function sendText(){
var button = dijit.byId("submitButton2");
dojo.connect(button, "onClick", function(event){
// The parameters to pass to xhrPost, the message, and the url to send it to
// Also, how to handle the return and callbacks.
var xhrArgs = {
//type: "POST",
url: "http://testjson.php",
content: dojo.toJson({key1:"value1",key2:"value2"},true),
handleAs: "text",
load: function(newContent){
dojo.byId("response2").innerHTML = newContent;
},
error: function(error){
// We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
// docs server.
dojo.byId("response2").innerHTML = "Message posted.";
}
}
dojo.byId("response2").innerHTML = "Message being sent..."
// Call the asynchronous xhrPost
var deferred = dojo.xhrPost(xhrArgs);
});
}
dojo.ready(sendText);
</script>
Here is my PHP:
<?php
foreach($_POST as $key => $val) echo '$_POST["'.$key.'"]='.$val.'<br />';
?>
The problem is that nothing is being returned.
If I put content instead of postData I have $_POST[0]='{', $_POST[1]='k' etc character by character, limited to 1000. This is a big problem.
Please can somebody tell me what I'm doing wrong? I got this code right from the dojo website, so it should be alright.

The php $_POST array only shows form encoded data. In your example you are POSTing json, so it won't directly show up in $_POST.
You have a couple options here. You could continue to post the data as json and read the POSTed json directly from the php input stream: $data = json_decode(file_get_contents('php://input'));. This is probably the easiest, and it replaces accessing the $_POST array for the data.
Other options include not POSTing json (just send form encoded data) and POSTing json as form encoded data:
In that case, your content would become something like
content: 'my_post_data='+dojo.toJson({key1:"value1",key2:"value2"}, true), (you may need to change handleAs fyi)
Then on the server side you would likely see something like
$_POST['my_post_data']= '{"key1":"value1","key2":"value2"}' which could be processed by json_decode()

I believe your content is being sent character by character because you are converting your content object into JSON. According to the dojo.xhrPost documentation, the content property is expected to be a JavaScript Object. I hope this helps solve your problem.
It should be noted that this module is deprecated in favor of dojo/request/xhr, so it is better to use that unless you have lower version requirements.

Related

Cross Origin Resource Sharing using AJAX methods and PHP

I just started to work on calls to a php file which is present in a different server. I am aware of CORS which is essential for cross domain requests. I have been trying to call this file through ajax methods refering to other websites and tutorials and I have seen discussions to find a solution but they are not working for me. Please help.
here is my calling method:
$.ajax({
type: "GET",
url: "http://cs-server.usc.edu:27952/ResponseProg.php?callback=?", //Relative or absolute path to response.php file
datatype: "jsonp",
data: dataInput,
jsonp:'jsoncallback',
crossDomain:true,
success: function(data)
{
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found")
{
var paginate=setPager(0);
$("#pgn").html(paginate);
}
},
error: function() {
$("#rtrn").html("Data not retrieved successfully");
}
});
Here is my PHP code snippet:
<?php
#code for data processing...
$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES);
echo $_GET['jsoncallback']."(".$rsltjson.");";
?>
I am trying to accomplish this by using JSONP. Should I have any headers?
Are there any errors in my code?....How can I accomplish this? dataInput is the serialized form of form data
The CORS way
You need to put the appropriate header in your php script and output only the JSON:
<?php
header('Access-Control-Allow-Origin: *');
// rest of the code
// output JSON only
echo $rsltjson;
?>
Then using a XMLHttpRequest/ajax call should retrieve the data just fine as JSON without resorting to JSONP.
Mozilla has plenty to read about it
The JSONP way
Since the whole point of JSONP is to bypass cross-domain restrictions, calling a JSONP resource with XMLHttpRequest/ajax, a method in which cross-domain security is fully applied (presumably), is completely useless.
JSONP works by injecting code directly into your page, calling a function that you defined, which is why a JSONP url takes an argument. Therefore, the correct way to call your JSONP url is this:
<script>
function myDataFunc(data) {
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found") {
var paginate=setPager(0);
$("#pgn").html(paginate);
}
}
</script>
<script src="http://cs-server.usc.edu:27952/ResponseProg.php?jsoncallback=myDataFunc"></script>
The JSONP url will return something that looks like this:
myDataFunc({"a":"fhsfg","b":"qfdgers","c":"difgij"});
Since it is included as a script, it will be executed directly in your page, calling the function myDataFunc() that you defined earlier.
Also note that your php file use the GET parameter jsoncallback while your javascript calls the url with the parameter callback, which would not work.
Finally, you use jQuery.parseJSON(), which produces this error from your code:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The reason can be found in the jQuery docs:
jQuery.parseJSON( json )
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown.
Your php script feeds your callback with a JSON object
{"a":"fhsfg","b":"qfdgers","c":"difgij"}
rather than a string representing a JSON object
'{"a":"fhsfg","b":"qfdgers","c":"difgij"}'
Note the surrounding quotes, which makes this data a string. We fix this in php by adding the quotes around the data:
echo $_GET['jsoncallback']."('".$rsltjson."');";
Obviously if your JSON data contains single quotes, you will have to escape them.

Under what circumstances can a JSON encoded array become a string?

I have some PHP 5 code that is similar to this:
$result = myFunction(...); // return false, or doit action
$reply = array();
if ($result) {
$reply['doit'] = $result;
$reply['status'] = "a status html string";
} else {
$reply['content'] = "Some html text";
$reply['menu'] = "Some other html text";
$reply['status'] = "a different status html string";
}
return $reply;
The caller includes the fragment
$reply = somefunction();
echo json_encode($reply);
This reply is then sent to the client, where jquery passes it to my function
function handleReply(reply) {
if (reply.doit) {
handle action
}
if (reply.content) document.getElementById('content').innerHTML=reply.content;
if (reply.menu) document.getElementById('menu').innerHTML=reply.menu;
if (reply.status) document.getElementById('status').innerHTML=reply.status;
}
What I have been struggling with is that, when the doit branch of the if statement is executed, ($result is a string) the reply given to me by jquery is a string. When the content/menu/status side is taken ($result is false) then reply is an object.
I have added a second second index to the array and the result is the same. Although all strings are ASCII I have tried passing them through UTF8_encode. I have changed the name of the 'doit' index from 'action' in case that was triggering some behaviour in jquery.
Just to be clear, the reply, when it is wrong is (for example).
"{"doit":"obj=session&act=show&ID=3","status":"<p>Nic: Ian<br\/>Reseller: Coachmaster.co.uk<br\/>Status: SysAdmin <\/p>"}"
Which is a string. I expected:
{"doit":"obj=session&act=show&ID=3","status":"<p>Nic: Ian<br\/>Reseller: Coachmaster.co.uk<br\/>Status: SysAdmin <\/p>"}
Which is an object/array. This is also what my logging showed as being echoed.
I'm using php5.4.3 under windows 7 and Apache and php 5.3.10 under linux and nginx with the same results. jquery is version v1.7.2 in both. Also loaded is jQuery UI - v1.10.3 - 2013-07-02.
If it is a bug in jquery, its a very strange one. How can I prove it?
I think you rely on jQuery autodetection. Try:
header('Content-Type: application/json');
Once you get the string into JavaScript, you'd have to eval() it to turn it into a JSON object:
var reply_json = eval( reply );
Then you can access reply_json.content, reply_json.menu, and so on.
Obviously be careful about what it is you're eval'ing, make sure it's from a trusted source and so forth.
Maybe you can try:
jQuery.parseJSON()
Do you use $.getJSON() jquery method or $.ajax()?
When using $.ajax() method, if you don't specify dataType: "json" option when you are making ajax request, jQuery will use "intelligent guess" (by searching for response MIME type) to figure how to interpret server response (xml, html, plain, json object...). If it is unable to figure that automatically it will assume response is plain text and regular string will be returned in success handle.
You should use either $.getJSON() or specify dataType: "json":
$.ajax({
url: "....",
dataType: "json",
success: function(reply) { // success handle
// if not specifying dataType: "json",
// and if not using response headers to specify MIME type "application/json",
// reply will not be object but a string!
}
});
or, as Marek posted in his answer, specify MIME type in response headers.

JQuery .post - $_POST empty

I know ajax calls and $_POST have been around a lot lately, nevertheless i could not find an answer to my current problem.
In my Javascript, I have a two-dimensional data array:
var postData = new Array(new Array());
postData[0]['type'] = 'grid';
postData[0]['data'] = gridData;
I then try to send this array to a PHP script:
function export_report_pdf(postData){
console.log(postData);
$.post('/ajax/ExportReportPDF.ajax.php',{data: JSON.stringify(postData)},
function(postData){
console.log("Successfully requested report export.");
});
}
I have tried to receive the array in my PHP script:
print_r($_POST);
var_dump(json_decode(file_get_contents("php://input")));
but all I get in my $_POST is an empty two-dimensional array. When I do the console.log(postData) in the beginning of my function, the data is there.
I have also checked $_REQUEST and tried removing the JSON.stringify.
Your inner variable type should be an object instead of an array, otherwise it won't get serialized properly:
var postData = [];
postData.push({
type: 'grid',
data: gridData
});
have you tried using get instead of post.
try that that would atleast ensure that data is getting passed from client to server and problem is with POST request only.
Also when u try GET than check in console if u are getting any error.
Don't JSON.stringify your post data. jQuery will do that for you, regardless of whether you've done it yourself, so it's winding up double-encoded. If you check your logs, you'll see that, after unencoding the data, PHP has a single POST parameter that is all of your data, JSON encoded.
Your could should look like this:
$.post('/ajax/ExportReportPDF.ajax.php', {data: postData}, ...
function export_report_pdf(postData){
console.log(postData);
$.ajax(url:'/ajax/ExportReportPDF.ajax.php',type:'POST',{data: JSON.stringify(postData)},
success:function(postData){
console.log("Successfully requested report export.");
});
}
try this.
and make sure you have latest jquery included.

Proper way to format user-entered text input for sending via JSON/AJAX to PHP?

I'm running into some problems with user-entered input that I want to send to PHP as JSON via AJAX that contains special characters, like ", ', etc. I'm sending the contents of an array (used for slickgrid), and everything works fine unless those characters are included. I know that PHP has the handy function mysql_real_escape_string, but is there any sort of jquery analogue? Here is the relevant code:
req = $.ajax({
url: url,
dataType: "text",
data: {"data": $.JSON.encode(data)},
type: "post",
success: onSaveSuccess,
error: onSaveError
});
Here's the PHP it is submitted to:
<?php
//$data = array();
//if (isset($_POST['data']))
//{
//$data = json_decode($_POST['data']);
//}
//header('Content-Type: text/javascript');
//echo json_encode($data);
print_r($_POST);
?>
To be clearer, when special characters are included, neither the success nor error events are triggered.
I looked in firebug and it doesn't appear to send anything at all when the special characters are included... Of course, it does when it's just letters or something.
It was due to the script from here apparently failing on certain kinds of input. Switching to json2.js and using JSON.stringify has solved the problem.
data: {"data": $.JSON.encode(data)},
Passes up a more complex JSON object than you need.
$data = json_decode($_POST['data']);
Is looking for a serialized JSON object but jQuery is doing a lot of work for you in the background.
Try this
data: $.JSON.encode(data),
In your AJAX call. Then in PHP
$data['myPostValue'] = $_POST['myPostValue'];
You're sending a JSON object to the $.ajax call, and it is changing it into the name value pair that the server would normally get from a post.
javascript has an escape() function. you can $.JSON.encode(escape(data)) might work

Sending PHP json_encode array to jQuery

ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})

Categories