AJAX request returning error - php

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.

Related

CORS Ajax POST variables empty in live server but work in local server

After days (and a bit of spamming here and there), I did get CORS to work for my CodeIgniter applications. However, POST variables are empty in the PHP side in live server. the whole $_POST array is empty for some reason. Here is my ajax code:
var postForm = {'e':'sammy'}; //data to process
$.ajax({
type: "POST",
url: "http://www.abc.ca/types/add",
data: postForm,
dataType : "json",
cache: "false",
contentType: "application/json",
success: function (result) {
//result here is blank
alert(result);
},
fail: function (result){
alert(result);
}
});
and the called php function (without the whole controller class):
function add() {
//Add new a biz type
file_put_contents('trial.txt',implode(" | ",$_POST));
echo $this->input->post('e');
}
Am I missing something? the response from server are ok. but still the file created contains no data and echo prints empty. Any tips please? I have already tried method:'POST' instead of type:'POST'. Get variables pass away successfully.
Is this CI issue or Ajax because it is constant across ff,chrome and Opera
Try This Ajax :
$.ajax({
type: "POST",
url: "http://www.abc.ca/types/add",
data: postForm,
cache: "false",
success: function (result) {
//result here is blank
alert(result);
},
fail: function (result){
alert(result);
}
});

jQuery AJAX get fields back from PHP

The following code sends some data to a PHP file. That PHP file encodes to a JSON object and echoes three variables error, success, and action.
However, neither the success function here, nor the error function appear to be returning that JSON object.
How would one get the values for these three keys back.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: ua['url'],
data: { sconnect: 'email', email : $('#semail').val(), hack:86 },
dataType: 'json',
success: function (data) {
alert(data['success']); alert(data['error']); alert(data['action']);
},
error: function(data){
alert(data['success']); alert(data['error']); alert(data['action']);
}
});

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

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?

JQuery/Ajax: Error Handling

$.ajax({
type: 'POST',
url: 'doSomething.php',
data: $('#form').serialize(),
dataType: "json",
success: function(data) {
//Success Message
},
error: function() {
//Error Message
}
});
I have a form input going to a PHP page which I error check on that page. My question is can I send errors (data array) through error: function(data) { or is it ONLY for actual errors with Ajax not going through correctly?
If that's the case would I be able to send the error array the success function?
Not sure on how to go about this.
If I could send data from my PHP page to the error function, I wouldn't even know how on the PHP page.
You can raise your own errors, if you do this:
$.ajax({
type: 'POST',
url: 'doSomething.php',
data: $('#form').serialize(),
dataType: "json",
success: function(data) {
//Success Message
},
error: function(req, status, error) {
alert(req.responseText);
}
});
when you throw an exception in your app it will be alerted out. For instance, in PHP you could do:
throw new Exception("Something bad happened");
You can see more about exceptions here

Categories