Issue with my JSON callback - php

I am using the following code to get json from my web service while the service is outputing the correct values I cannot access it I get an error stating that its undefined when I try to alert part of the object. How can I fix this issue?
My code is below
jQuery
var durl = "a valid url";
$.ajax({
type: "GET",
url: durl,
data: "Pass="+avalidid,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "callback",
contentType: "application/json",
crossDomain: "true",
}).done(function(){
}).fail(function(){
$.mobile.changePage("errorpage");
})
});
//callback function
function callback(rtndata)
{
alert(rtndata.name);
}
Web service
The last few lines to return json
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($posts) . ")";
Lastly it should be mentioned that I mapped my array so that it can return all of my results
$posts[] = array_map('utf8_encode',$post);

Related

AJAX request returning error

I have an AJAX request that is throwing an error.
It's part of a larger system that I've inherited, so I can't post the files in their entirety, but I've tried to isolate the relevant code:
$.ajax(
{
url: ajax_url, // Valid URL
data: jsonData, // Valid JSON
dataType: 'json',
contentType: 'application/json',
type: POST,
async:true,
success: function(data)
{
console.log(data);
parsedData = JSON.parse(data);
console.log(parsedData);
// Here I am trying to log successful output
},
error: function(jsonData)
{
console.log("error");
console.log(jsonData);
}
});
In the PHP, values are added to an array and returned:
$data['status']=200;
$data['new_id']=$insert_id;
return json_encode($data);
All I am logging at the moment is 'error'. Apologies again for incomplete code, I have tried to supply the code where I think the error is caused.

Cross Domain jQuery Ajax call - Syntax missing error

I couldn't access the webservice call from cross domain. Please advice. I have pasted my source here.
PHP: webservice response
$data['response'] = 2;
header('Content-type: application/json');
echo json_encode($data);
jQuery Ajax Call:
$.ajax({
type: 'GET',
url: cross-domain-url,
data:{ param1:'123', param2:'123' },
dataType:'jsonp',
crossDomain: 'true',
async: true,
success:function (data) {
alert('success');
},
error:function(){
alert('error');
}
});
Cross Domain URL response:
{"ResultCode":2}
Always I am getting Error only. I don't know why. I can see the following message in Firefox inspect area.
SyntaxError: missing ; before statement
{"ResultCode":2}
Please help me.
Solution:
Modify the line like,
echo 'someCallBackString('.json_encode($data).');';
instead of echo json_encode($data);
Created the function someCallBackString and proceeded my implementations.
You are telling jQuery to make a JSON-P request (dataType:'jsonp'), but your server is returning JSON.
Consequently the browser is trying to execute a JSON text as if it was a JavaScript program (and it can't because it isn't).
Either:
Remove the dataType property from the object so that jQuery will use the HTTP Content-Type to determine that it is JSON and add access control headers to permit your site to access the data on the other domain or
Return JSON-P instead of JSON
Ok the problem is in the JSONP data, when you send a request the JSON response would send a response as
callbackFunctionName(jsonData)
You do not have anything as such so is the issue you need to format the code as below
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'your cross domain file',
dataType:'jsonp',
crossDomain: 'true',
jsonpCallback: 'MyCallback',
async: true,
success:function (data) {
console.log(data);
},
error:function(data){
console.log('error');
}
});
function MyCallback(data) {
}
});
Now in the response the data needs to be formatted as
$data['response'] = 2;
header('Content-type: application/json');
$json_data = json_encode($data);
echo "MyCallback" . '(' . $json_data . ');';
You can now check your console and see the data is coming through
You can check more on this here http://remysharp.com/2007/10/08/what-is-jsonp/
change your ajax to this code:
Solution
$.ajax({
type: 'GET',
url: cross-domain-url,
data:{ param1:'123', param2:'123' },
dataType:'JSON',
success:function (data) {
alert('success');
},
error:function(){
alert('error');
}
});
Hope it will work....

Jquery ajax response error

Here is a partial example of what I am trying to achieve.
I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:
PHP:
$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);
Javascript/jQuery:
var ID = 1
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
datatype: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
});
The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}
This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..
Your error is here:
datatype: 'json',
Javascript is case sensitive and the property is dataType:
dataType: 'json',
Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.
You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
} // Maybe your forgot this
});
in other words - Basic Debugging
in your PHP page put this on top of the page (you are accepting only json response but probably your response headers content type is text/html
header('Content-type: application/json');

Passing Parameters in Ajax to JSON web service

I am using AJAX to request some information from a PHP built web service however the parameters I am passing doesn't seem to go to the web service my code is below:
$(document).on( "pageinit", "#player", function( e ) {
var passedId = (passDataObject.selectedHref != null ? passDataObject.selectedHref : window.location.href).replace( /.*id=/, "" );
alert(passedId); // test passedId has the correct value within it
var surl = "a working url";
$.ajax({
type: "GET",
url: surl,
data: "&Track="+passedId,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "trackcallback",
crossDomain: "true",
success: function(response) {
alert('tracks function');
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
});
//callback function for player page
function trackcallback(rtndata)
{
alert(rtndata.track_name); // show up as undefined
}
The passedId has the correct value within it and the URL is fine however the web service does not produce a result even though the SQL statement is fine. I am assuming the issue is within this line within my php web service $id = $_REQUEST['Track']; as this gets the value from the JavaScript to execute the SQL.
Can anyone solve this issue?
See this code below, there is no "&" before the parameter name:
$.ajax({
url: homeUrl + "/Getsomething",
data: "parameterhere=" +$(element).attr('attrHere'),
type: 'GET',
contentType: "application/json",
dataType: "json",
cache: false,
success: function (result) {
//do stuff
},
error: function (xhr, ajaxOptions, thrownError) {
//error handling
}
});
What happens if you do you ajax get like the code above?

PHP isn't recognizing data posted by ajax

I'm sending an ajax call to my PHP script as follows:
function load(){
var request = {};
request['action'] = 'load';
request['file'] = 'lorem_ipsum.txt';
$.ajax({
type: 'POST',
url: cgi_file,
data: JSON.stringify(request),
processData: false,
dataType: 'html',
contentType: 'application/html',
success:function(response){
console.log("received " + response);
}
});
}
and my PHP script is as follows:
$content_dir = '/static/content/';
$action = $_POST['action'];
switch ($action){
case 'load':
$file = $_POST['filename'];
echo file_get_contents($content_dir . $file);
exit();
}
The PHP is responding with the following failure:
Notice: Undefined index: action in /var/www/river/api.php on line 5
What's the issue here?
Try ditch processData: false and contentType: 'application/html' and it should work
$.ajax({
type: 'POST',
url: cgi_file,
data: request,
dataType: 'html',
success:function(response){
console.log("received " + response);
}
});
Just leave data as it is:
data: request,
You don't need to stringify it.
Also, your file parameter allows an attacker to read arbitrary files from your filesystem. Sanitize it.
A few things wrong here, firstly the contentType property is for the data you are sending to the server, secondly dataType should be set to text as that is what you are recieveing from the server. If you want to receive the data in the $_POST array your javascript should look like this,
$.ajax({
type: 'POST',
url: cgi_file,
data: {
action: "load",
file: "lorem_ipsum.txt";
},
dataType: 'text',
success:function(response){
console.log("received " + response);
}
});
Jquery will send your data as a standard post to your server side code.

Categories