js code to define an ajax call:
function InitDataServices()
{
amplify.request.decoders.myDecoder =
function (data, status, xhr, success, error)
{
if (status === "success") {
success(data);
} else if (status === "fail" || status === "error") {
error(message, status);
} else {
error(message, "fatal");
}
};
amplify.request.define("Emision_FiltrarSeguros", "ajax", {
url: "http://localhost:63721/api/emision/filtrar",
type: "POST",
dataType: "json",
decoder: "myDecoder"
});
}
Then the code to make the actual ajax call is:
function Emision_FiltrarSeguros(requestData,okFunction, failFunction)
{
amplify.request({
resourceId: "Emision_FiltrarSeguros",
contentType: "application/json",
data: JSON.stringify(requestData),
success: function (data) {
okFunction(data);
},
error: function (message, level) {
failFunction(message,level);
}
});
};
And finally this code in the page to make the call:
function FiltrarSeguros()
{
this.request = {Ramo:-1,
NroSocio: 107701,
NroSeguro:-1,
NroEndoso:-1,
Vigentes:0,
Patente:"" };
Emision_FiltrarSeguros(request,okFiltrarSeguros, failFiltrarSeguros);
}
The controller code is this:
public List<FiltroSeguroResponse> Filtrar(FiltroSeguroRequest request)
{
return DLL.Service.EmisionService.FiltrarSeguros(request, "jdh");
}
The problem is that the data that i POST from the page never get mapped to the request (of type FiltroSeguroRequest, whose properties are the same as the object literal I build in the ajax call) parameter.
What is wrong??? Thanks.
Add the content-type to where you define your amplify request like this:
amplify.request.define("Emision_FiltrarSeguros", "ajax", {
url: "http://localhost:63721/api/emision/filtrar",
type: "POST",
dataType: "json",
decoder: "myDecoder",
contentType: 'application/json; charset=utf-8',
});
Related
Was try to implement another ajax call based on the first two results with Jquery $.When method. Basically, all three Ajax will populate a carousel on the page based on the results. Therefore I choose $.When for continuous checking. But the third Ajax which under Done() method is not called even there was no result from above two APIs or with initial values zero(0). Not sure if I missed anything!
jQuery:
let itemCat1Count = 0;
let itemCat2Count = 0;
$.when(
$.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
$.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
).done(function (xhrSavedRings, xhrShoppingBagItems) {
if (itemCat1Count == 0 && itemCat2Count == 0) {
$.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (jObject) {
console.log(jObject);
// carousel inital codes
},
error: function (jqXHR, status, error) {}
});
}
});
Few things to highlight - $.when() requires promises as arguments. $.when does not have the powers to know when functions you passing are done or completed
From the official documentation of $.when You have return promises or return something from your ajax calls.
Here what its says => In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.
I have assigned a retrun value from each $.ajax call you are making. $.when will know check if there is something coming from return and is resolved then it will go to .done
Run snippet below to see the console log on .done
let itemCat1Count = 0;
let itemCat2Count = 0;
function first() {
return $.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
console.log(data.ResponseObject.Items.length)
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
function second() {
return $.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
$.when.apply(first(), second()).done(function() {
console.log("First and Second is done running - I am from done");
if (itemCat1Count == 0 && itemCat2Count == 0) {
return $.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(jObject) {
console.log(jObject);
// carousel inital codes
},
error: function(jqXHR, status, error) {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have this ajax call below
$(function(){
$.ajax({
type: "GET",
url: '/CafeTableDetails/GetTotalItems',
data: '{"url":"test"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger
alert("some error");
}
});
});
and it can call the action method of my controller in C# MVC /CafeTableDetails/GetTotalItems
public ActionResult GetTotalItems()
{
bool isSuccess = true;
return Json(new { isUpdateSuccess = isSuccess, JsonRequestBehavior.AllowGet });
}
But as the action method return it back as Json, it falls into error. The XMLHttpRequest return state is 4, textStatus = "Error" and errorThrown is "Internal Server Error". How do I troubleshoot this further?
Your ajax method should be :
$.ajax({
type: "GET",
url: "/CafeTableDetails/GetTotalItems",
data: JSON.stringify({ url: 'test' }),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText);
}
});
and your controller action method will be:
[HttpGet]
public JsonResult GetTotalItems(string url)
{
// some business logic and return
return Json(url, JsonRequestBehavior.AllowGet);
}
I'm trying to get my server-side code to play nicely with some page templates we got from a design agency. All is good except that I'm struggling to implement the correct behaviour with the results of the form submission.
What should happen is, if the form submits successfully, some JQuery is triggered to animate into a success message. If not, the user should be redirected to an error page.
Here's the form submit script:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
And here's the controller action that it posts to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(User userObject)
{
bool userExists;
try
{
if (ModelState.IsValid)
{
userExists = InsertUser(userObject); //calls a sproc
}
else
{
return CollectValidationErrors(); // collects all validation errors into a string
}
}
catch(Exception ex)
{
ViewBag.ErrorMessage = "Sorry! There has been an error " + ex.Message;
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
if(userExists)
{
ViewBag.ErrorMessage = "This user already exists";
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
What happens is that the form submission is received and the code inside executed successfully. But if an error state is returned, there's no redirect.
What am I doing wrong?
Try to use error property of ajax call:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Do Something
},
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
You do not send an error.
You can throw an Exception (forces HTTP Status 500 Internal Server Error) in the Controller Action. It will result that the success is not invoked, but the error function of ajax.
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
},
error: function(function (xhr, status, errorThrown)){
// Do Redirect
}
});
I have a javascript code that calls a web service from another server, it's working, but i need to call it from code behind due to an http call request issue, following my code :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://10.8.111.12:7181/CatchEventLink.asmx/CollectDataLink",
data: JSON.stringify({ "pDataDictionnary": lDataCollected }),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
//alert('success');
}
},
error: function (exception) {
//alert('Exeption : ' + exception);
}
});
Any suggestions please??
I have a Post call. After the result I want to do another get CALL to check the status. But only if the status is FINISHED.
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
.. now I want to do the polling on the status
jQuery.ajax({
type: "GET",
dataType: "json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
// to continue only if status if Finished
},
error: function() {
}
});
}
});
$.ajax returns a deferred object.
You can do something like below. More info here
var doSomething = $.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
function doneCallback(){
// Handle exit condition here.
doSomething();
}
function failCallback(){
// Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)
Just set your code in a function:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
doPoll();
}
});
var doPoll = function() {
jQuery.ajax({
type: "GET",
contentType: "application/json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
//do stuff
doPoll();
},
error: function() {
//handle error
}
});
}
You can try to export the ajax call to a function and use recursion to pool.
Note: You should have a max counter so that you do not flood server with infinite calls.
var max_count = 20;
var counter = 0;
function getStatus() {
jQuery.ajax({
type: "GET ",
contentType: "application / json ",
url: " / getStatusUrl,
success: function(data, textStatus, response) {
// to continue only if status if Finished
if (textStatus != "status" && ++counter < max_count) {
getStatus();
}
},
error: function() {}
});
}