I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};
Related
Hello I am not good with ajax.I want to check my login info and return either 'success' or 'fail'.Buy my ajax seems to have an error.
var user = $('.username').value();
var pass = $('.password').value();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username': user,
'password': pass
},
beforeSend: function() {
$("#Loading").show();
},
success : function(response) {
if(response=="success" && response!=="fail") {
$('.status').html("Success! Now logging in ......");
setTimeout(' window.location.href = "index.php"; ',4000);
} else {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(' window.location.href = "login.php"; ',4000);
}
}
});
Can anyone points me out?
The reason you are getting error is because your javascript is getting break(giving error) at $('.username').value(); as there is no value() function. If you open console you get this error. So because of this rest of script is not working. So change $('.username').value(); to this $('.username').val(); and same for the var pass = $('.password').value(); change to var pass = $('.password').val(); and also you don't need if condition as mention in comment. Your final code will be something like this.
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type: 'POST',
url: //some url
data: {
'username': user,
'password': pass,
},
beforeSend: function() {
//some code
},
success: function(response) {
// some code which you want to excute on success of api
},
error: function(xhr, status, error) {
// some code which you want to excute on failure of api
}
});
I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username':user,
'password':pass,
},
beforeSend: function()
{
$("#Loading").show();
},
success : function(response)
{
$('.status').html("Success! Now logging in ......");
setTimeout(()=>{ window.location.href = "index.php"; },4000);
},
error: function(xhr, status, error) {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(()=>{ window.location.href = "login.php"},4000);
}
});
Your response needs to be a PHP echo that returns a string with a value of either ”success” or ”fail”.
Your PHP response after successful login:
echo(‘success’);
Your PHP response after failed login:
echo(‘fail’);
When first opening the mobile app homepage it returns an error
"TypeError: Jqueryxxxxxx is not a function" although it shows the API
callback results
"jQuery111309512500500950475_1459208158307({"code":1,"msg":"Ok","details":{"data"..."
according to Firebug.
I have to open different app pages then return to homepage to see Featured Merchants parsed.
JS Code
case "page-home":
callAjax('getFeaturedMerchant','');
break;
case "getFeaturedMerchant":
displayFeaturedRestaurant( data.details.data ,'list-featured');
break;
case "getFeaturedMerchant":
createElement('list-featured','');
break;
API PHP Code
public function actiongetFeaturedMerchant()
{
$DbExt=new DbExt;
$DbExt->qry("SET SQL_BIG_SELECTS=1");
$start=0;
$limit=200;
$and='';
if (isset($this->data['restaurant_name'])){
$and=" AND restaurant_name LIKE '".$this->data['restaurant_name']."%'";
}
$stmt="SELECT a.*,
(
select option_value
from
{{option}}
WHERE
merchant_id=a.merchant_id
and
option_name='merchant_photo'
) as merchant_logo
FROM
{{view_merchant}} a
WHERE is_featured='2'
AND is_ready ='2'
AND status in ('active')
$and
ORDER BY sort_featured ASC
LIMIT $start,$limit
";
if (isset($_GET['debug'])){
dump($stmt);
}
if ($res=$DbExt->rst($stmt)){
$data='';
foreach ($res as $val) {
$data[]=array(
'merchant_id'=>$val['merchant_id'],
'restaurant_name'=>$val['restaurant_name'],
'logo'=>AddonMobileApp::getMerchantLogo($val['merchant_id']),
);
}
$this->details=array(
'data'=>$data
);
$this->code=1;$this->msg="Ok";
$this->output();
} else $this->msg=$this->t("No Featured Restaurant found");
$this->output();
}
I'm stuck and confused what's causing this error and how to resolve it.
EDIT: Added the full callAjax Function
function callAjax(action,params)
{
/*add language use parameters*/
params+="&lang_id="+getStorage("default_lang");
dump(ajax_url+"/"+action+"?"+params);
ajax_request = $.ajax({
url: ajax_url+"/"+action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function() {
if(ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
} else {
},
complete: function(data) {
ajax_request=null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code==1){
switch (action)
{
case "getFeaturedMerchant":
displayFeaturedRestaurant( data.details.data ,'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total+" "+ getTrans("Featured Restaurants found",'restaurant_found') );
break
)
else {
/*failed condition*/
switch(action)
{
case "getFeaturedMerchant":
createElement('list-featured','');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request,error) {
hideAllModal();
if ( action=="getLanguageSettings" || action=="registerMobile"){
} else {
onsenAlert( getTrans("Network error has occurred please try again!",'network_error') );
}
}
}};
Calling URL is:
http://domain.com/mobileapp/api/getFeaturedMerchant?
This is actually an issue with the way jQuery handles the abort method when using JSONP, which I have encountered before.
Basically, JSONP works by adding a script tag to the DOM, and adding a callback it will fire when it executes.
Unlike AJAX, the request generated by a script tag cannot be cancelled, so when you call abort like below, it only sort-of works.
ajax_request.abort();
jQuery will unset the global callback it registered, jQuery111309512500500950475_1459208158307 in your case, but it cannot stop the script from trying to run it when it loads. Thus, when it tries to call the now-undefined function, you get the error.
Personally, I think jQuery should set, or have an option to set, these global handlers to an empty function or something instead, but it doesn't. In your case, if possible, I would recommend avoiding making the request if you only plan to abort it before sending it.
Edit:
Two issues I see:
Your code bracing is wrong leading to some unintended execution paths.
You are trying to call .abort() on a JSONP request which is not supported. Doing so will cause the callback function to be removed BEFORE the JSONP script loads that tries to call that callback function. The .abort() will stop the processing of the request, but leave you with the type of script error you see reported.
Here are the notes on the code bracing:
It appears like your code bracing is wrong so you are executing the success callback too soon. When I put your callAjax through a code formatter, it looks like this (see the spot marked "problem area"
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
} else {}, // <========== problem here
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
switch (action) {
case "getFeaturedMerchant":
displayFeaturedRestaurant(data.details.data, 'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total + " " + getTrans("Featured Restaurants found", 'restaurant_found'));
break
) // <========== problem starts here
else {
/*failed condition*/
switch (action) {
case "getFeaturedMerchant":
createElement('list-featured', '');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request, error) {
hideAllModal();
if (action == "getLanguageSettings" || action == "registerMobile") {} else {
onsenAlert(getTrans("Network error has occurred please try again!", 'network_error'));
}
}
}
};
Add a missing brace in the problem area and you get this. But this is still not really correct. The two switch statements in the success handler are not correct syntax so they need to be fixed too. I think your issue is that you had some counteracting syntax errors that allowed the code to somehow run, but not execute in the proper way.
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
}
}, // <======== Added this brace to close off the function
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
switch (action) {
case "getFeaturedMerchant":
displayFeaturedRestaurant(data.details.data, 'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total + " " + getTrans("Featured Restaurants found", 'restaurant_found'));
break
) // <============= This is out of place and so are the next few lines
else {
/*failed condition*/
switch (action) {
case "getFeaturedMerchant":
createElement('list-featured', '');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request, error) {
hideAllModal();
if (action == "getLanguageSettings" || action == "registerMobile") {} else {
onsenAlert(getTrans("Network error has occurred please try again!", 'network_error'));
}
}
}
}
});
}
One possible way to approach fixing this is to fix the missing brace in the beforeSend: handler, then remove most of the success handler code to this stub and then add back in the proper code in the success handler under a careful eye:
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request !== null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
}
}, // <======== Added this brace to close off the function
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
// <=========== Removed faulty code in here
}
}
});
}
Original Answer
That particular error and network response looks like your client wants some data from the server. The client (for some reason) decides that it needs to use JSONP to get the response from the server so the server is sending back JSONP, but the client code that sent the request did not properly prepare for the JSONP request by defining the appropriate callback function that the JSONP script can call.
You will either have to switch to a regular Ajax call that is not JSONP or we will have to see the details of your callAjax() implementation to see why the JSONP response is not working.
I have a project in MVC4 with C#. In this project, one of my controllers has a method to be called by an Ajax function:
[HttpPost]
public string EditPackage(int id, string newPkgName)
{
try{
//do logic here
return "OK";
}catch(Exception exc){
return "An error occurred, please try later! " + exc.Message;
}
}
This method is called by the following Ajax functions, using jQuery:
$.ajax({
url: $(this).data('url'),
type: 'POST',
contentType: 'application/json; charset=utf-8',
traditional: true,
data: JSON.stringify({ id: id, newPkgName: newPkgName}),
success: function () {
location.reload(true);
successNotification("Package edited successfuly!");
},
error: function (message) {
errorNotification(message);
}
});
The problem with this code, is that even if the server returns the return "An error occurred, please try later! " + exc.Message; message in the catch, the success function is the one always called.
In order words, I never run the error function no matter what I do.
To fix this I checked the official documentation:
http://api.jquery.com/jQuery.ajax/
However, since I am failry new to this I can't understand any of the parameters, nor how to use them effectively.
How can I create a good error message with all the possible information using Ajax, jQuery and my controller?
The error part of the $.ajax call only fires if the returned status code is anything other than 200 OK. In your case you are returning a plaintext response which will therefore be 200. You can change this behaviour like this:
try {
// do logic here
return "OK";
}
catch (Exception exc) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
error: function (jqXHR, textStatus, errorThrown) {
errorNotification(textStatus);
}
You can change the HttpStatusCode to whatever suits your need.
Alternatively, you can keep the 200 response and return JSON with a flag to indicate whether or not the request was successful:
[HttpPost]
public ActionResult EditPackage(int id, string newPkgName)
{
try {
//do logic here
return Json(new { Success = true, Message = "OK"});
}
catch (Exception exc) {
return Json(new { Success = false, Message = "An error occurred, please try later! " + exc.Message });
}
}
Then you can remove the error handler, and check the state of the flag in your success handler:
success: function(response) {
if (response.Success) {
location.reload(true);
successNotification("Package edited successfuly!");
}
else {
errorNotification(response.Message);
}
},
I do the following, it might not be the best approach but it works for what I try to do.
[HttpPost]
public ActionResult EditPackage(int id, string newPkgName)
{
try{
//do logic here
return Json(new {Success = true, Message = "OK"});
}catch(Exception exc){
return Json(new {Success = false, Message = "An error occurred, please try later! " + exc.Message});
}
}
Then my Ajax looks as follows:
$.ajax({
url: $(this).data('url'),
type: 'POST',
contentType: 'application/json; charset=utf-8',
traditional: true,
data: JSON.stringify({ id: id, newPkgName: newPkgName}),
success: function (data) {
if(data.Success)
{
location.reload(true);
successNotification("Package edited successfuly!");
}
else
{
errorNotification(data.Message);
}
},
error: function (message) {
errorNotification(message);
}
});
I do this so that you have the standard error catching http errors from the server, but it means you can pass a success or failure back in a way that is more useful. It also means that if your update fails for a validation reason or something you can pass that message back nicely.
I need to execute an ajax function, the detail here is that i want to execute this function until another ajax function return success.
This is the function that will i have to wait to return success (try..catch block)
Ajaxfunction1
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
try {
var jsonObject = JSON.parse(msg);
console.debug(msg);
//SendToDMS(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
},
failure : function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
}
});
I want something like this:
while ( Ajaxfunction1 != success ) { // while the previous ajax function not return success execute this another ajax function
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
// something on success
},
failure : function(msg) {
// something when comes an error
}
});
}
How can I accomplish this? Thanks for your help
You can use the returned Deferred from $.ajax and check it's state() to see if it's resolved, rejected or pending, so something like this with a recursive function should do what you want.
var waitFor = $.ajax({
type : "GET",
url : url,
data : parameters
}).done(function(msg) {
try {
var jsonObject = JSON.parse(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
}).fail(function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
});
(function rec() {
$.ajax({
type : "GET",
url : url,
data : parameters
}).always(function() {
if (waitFor.state() != 'resolved') rec();
}).done(function(msg) {
// something on success
}).fail(function(msg) {
// something when comes an error
});
})();
I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9
The JavaScript :
var newCustomer = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '#Url.Content("~/CustomerHeader/CreateCustomerHeader")',
cache: false,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newCustomer),
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
and this is my controller :
public JsonResult CreateCustomerHeader(CustomerHeader record)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
RepositoryHeader.Update(record);
return Json(new { Result = "OK", Record = record});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.
UPDATE : New method trying using $.post
function CreateNewCustomer(newCustomer) {
$.post("/CustomerHeader/CreateCustomerHeader",
newCustomer,
function (response, status, jqxhr) {
console.log(response.toString())
});
}
Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):
var data = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.post({
'#Url.Action("CreateCustomerHeader", "CustomerHeader")',
data,
function(response, status, jqxhr){
// do something with the response data
}).success(function () {
$("#message").html("Success");
}).error(function () {
$("#message").html("Save failed");
});
$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.
response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.
first of all I would like to apologize #Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.
The full script :
try{ ..
var newCustomer =
{
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '/CustomerHeader/CreateCustomerHeader',
cache: false,
type: "POST",
dataType: "json",
data: JSON.stringify(newCustomer),
contentType: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
}
catch(Error) {
console.log(Error.toString());
}
//$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!
I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.
Thanks for all the efforts in solving my problem guys :-)