I am making the following jquery ajax call to a codeigniter php function:
$.ajax({
type:"POST",
url: "AjaxUpdate/getHtml",
data:{ u : 'http://stackoverflow.com/' },
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR,textStatus, errorThrown);
}
});
The requested php function is :
public function getHtml() {
$url = $_POST['u'];
$result = file_get_contents($url);
return json_encode($result);
}
How can I fix this?
edit: the error in the console shows:
error
reply_detail:4667 Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…} "parsererror" SyntaxError: Unexpected end of input {stack: (...), message: "Unexpected end of input"}message: "Unexpected end of input"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
Some things may be happening.
I don't know PHP, but is getHtml REALLY returning a JSON?
Maybe it is failing to parse the returning content. There are other options in the JQuery $.ajax dataType property.
It isn't executing the success function, because it might be failing at some point. Try adding an error function and log the data. The JQuery documentation is very helpful and rich.
Also, try to change to data: JSON.stringify({ u : 'http://stackoverflow.com/' }), at least in ASP.NET I have to do it every time.
Are you sure you are calling the function inside the file?
You need to invoke the function by calling it.
getHtml();
Related
I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.
I have declared success and error callbacks, but in case of status code 200 also it calls error callback only.
I have been making curl call to some other php file too inside registry.php.
Here what i tried:
$.ajax({
type: "POST"
,data: {
action: "blah"
,mobileNo: that.mobNo
,token: that.key
}
,url: "http://90.8.41.232/localhost/registry.php"
,cache: false
,dataType: "json"
,success: function (response) {
console.log("success");
}
,error: function () {
console.log("error");
}
});
I have read in documentation that we don't have to call success callback explicitly, hope it's correct.
Any idea how to call success callback when it is 200 status code.
RESPONSE
hope this will help, this I copied from chrome console, not printed by console.log().
bort: (statusText)
always: ()
complete: ()
done: ()
error: ()
fail: ()
getAllResponseHeaders: ()
getResponseHeader: (key)
overrideMimeType: (type)
pipe: ()
progress: ()
promise: (obj)
readyState: 4
responseText: "{"success":"Mobile No 9535746622 is approved"} {"report":true}"
setRequestHeader: (name,value)
state: ()
status: 200
statusCode: (map)
statusText: "OK"
success: ()
then: ()
As you have mentioned that you are making a curl call to some other php, what happens is whenever you make curl call you have to return the response of the curl to the client. So to transfer the return value of curl call, you have to set an option curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);.
This will sort your problem. Hope so.
First, checkout the real error you get (not certain you really get a 200 status ?)
error: function (err) {
console.error("error");
console.log(err);
console.log(err.stack);
throw err;
}
Show us the resulting log please.
I did that a few weeks ago and for me it works if I call it like
$.ajax(
{
type: "POST",
data: { action: "blah", mobileNo: that.mobNo, token: that.key },
url: "http://90.8.41.232/localhost/registry.php",
cache: false,
dataType: json,
})
.success (function (data, status, jqxhr)
{
// do your stuff
})
.error (function(x, status, jqxhr)
{
// handle your errors
});
I have an AJAX call:
$('#testyo').click(function(){
$.ajax({
type: 'GET',
url: "../messages/drew",
dataType: 'JSON',
success:function(data){
alert(data);
},
error: function(data)
{
console.log(data);
alert("Error: "+data);
}
});
return false;
});
It should be successful, but I get the alert("Error: "+data) alert. The data is [object Object]. So the alert just says Error: [object Object]
In my console.log(data)
Object {readyState: 4,
getResponseHeader: function,
getAllResponseHeaders: function,
setRequestHeader: function,
overrideMimeType: function…}
abort: function ( statusText ) {always: function () {complete: function () {done: function () {error: function () {fail: function () {getAllResponseHeaders: function () {getResponseHeader: function ( key ) {overrideMimeType: function ( type ) {pipe: function ( /* fnDone, fnFail, fnProgress */ ) {progress: function () {promise: function ( obj ) {readyState: 4responseText: "drew"setRequestHeader: function ( name, value ) {arguments: nullcaller: nulllength: 2name: ""prototype: Object__proto__: function Empty() {}<function scope>state: function () {status: 200statusCode: function ( map ) {statusText: "OK"success: function () {arguments: nullcaller: nulllength: 0name: ""prototype: Object__proto__: function Empty() {}<function scope>then: function ( /* fnDone, fnFail, fnProgress */ ) {__proto__: Object
As you can see it does show the responseText: "drew" which is what I want. I'm just curious to know why is passing through my fail function, and not my success. Please let me know if there is anything else you would need to help me solve this.
According to the jquery documentation, the error parameter takes three inputs as parameters:
error:
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error."
The errormessage, and the error can be viewed if you modify the error function to take three parameters input and access the second argument to know what the error string is.
If you do this, it becomes easy to spot the error and know why the request failed. Once you spot the error, it becomes easy to fix it.
unexpected token probably means you've got a corrupted JSON response from the server. Also make sure the response the server component sends is of type JSON.
Set the response type in the server, for example, if the response is json:
response.setContentType("application/json");
See Also:
What is the correct JSON content type?
Refer: http://api.jquery.com/jquery.ajax/
I see you get a 200 response but probably your server returns the wrong content type for json or it's completely invalid json.
In Firefox with firebug or chrome try to inspect the response and response headers like content type.
https://stackoverflow.com/a/11112320/1641941
When your responseText returns "drew", your response is not JSON, but String. Remove dataType: 'JSON' and jQuery will use auto detection. Then success function will be called.
JSON should be something like {"myText": "drew"}.
. Hello y'all. I am trying to gather a few variables and send it to my controller. I keep getting a 500 error and can't figure out where exactly I'm going wrong other than I'm pretty sure its server side. Any pointers about where I went wrong or better practices would be greatly appreciated! Thank yall so much!
Route:
/*Ajax Edit Price on Price Page*/
Route::post('edit_price', array(
'as' => 'edit_price',
'uses' => 'PriceController#edit_price'
));
Controller:
public function price_edit(){
console.log($id_and_db);
}
JS:
/*Ajax edit prices*/
$(document).ready(function(){
$('.edit_button').click(function(e){
e.preventDefault();
var id_and_db = $(this).prop('name').replace('edit', 'newprice'),
new_price = $('[name=' + id_and_db + ']').val();
$('#test').val(id_and_db);
$.ajax({
url: 'edit_price',
type: "POST",
data: {
"id_and_db": id_and_db,
"new_price": new_price,
},
success: function(data){
$("#edit_results").html(data);
$("#edit_results").addClass('panel callout radius');
console.log(data);
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
},
});
});
});
Error Message:
POST http://localhost/local/example/public/edit_price 500 (Internal Server Error) jquery.min.js:4
XHR finished loading: POST "http://localhost/local/example/public/edit_price". jquery.min.js:4
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
price_index_admin.js:40
error price_index_admin.js:41
Internal Server Error
You did
'uses' => 'PriceController#edit_price'
but your controller method is price_edit().
Try change your controller method to
public function edit_price() {
This is not valid for a controller - it looks like you are trying to run java inside php:
public function price_edit(){
console.log($id_and_db);
}
it should be something like this
public function price_edit(){
return Response::json(['your response here']);
}
Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});