Combine AJAX and API calls - ajax

I am working with APIs. My logic is 1st add a grade (POST), 2nd get the gradeID (GET), 3rd add grades to students (PUT). My problem is that I have to use the gradeID in the API call to add the grades.
How do I do using AJAX to get the result from one call and then pass to another call?
here is my ajax:
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) {
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
$("#responseFieldLabel").removeClass('hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
Is there a way tho have an ajax inside of other?

Related

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

How to get(handle) Error (Not Acceptable & Internal Server Error) Exception content in Ajax

I added internal Error (throw exception) in server side. Now I want to handle this error in client side. However , I get error content undefined.
I am using Postman , and see my response is JSON format, it has response parameter like "Message". I tried to parse JSON , and again I got Cannot read property 'Message' of undefined
Ajax function defined like this:
function Ajax(url, method, json, successFunction, errorFunction, skipErrorDlg) {
$.ajax({
url: url,
data: json,
type: method,
contentType: 'application/json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', GlobalAuthToken);
},
processData: false,
dataType: 'json',
success: function (data) {
successFunction(data);
},
error: function(event, jqxhr, settings, thrownError) {
if (errorFunction != null) {
errorFunction();
}
}
});
}
I used this function in my code , error part like this, In this function how can I get exception content?
function(event, jqxhr, settings, thrownError)
{
alert("ERROR HAPPENED");
var responseString = JSON.stringify(event);
alert(responseString.Message);
alert("event" + event.Message);
},
Postman Result:
{
"Message": "Please select corresponding template."}
Expected Result should be : Please select corresponding template.
I solved the problem, if you face this kind problem , trying like this:
function showAjaxError(event, jqxhr, settings, thrownError) {
var msg = "";
if (event.hasOwnProperty('responseJSON')) {
var resp = event['responseJSON'];
msg = (resp && resp.hasOwnProperty('Message')) ? resp.Message : "";
msg = msg + ((resp && resp.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.ExceptionMessage : "");
if (resp && resp.hasOwnProperty('InnerException')) {
msg = msg + ((resp && resp.InnerException.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.InnerException.ExceptionMessage : "");
}
} else {
msg = event.responseText;
}
}

Using a list of Json results as parameters for a mvc actionresult, to return objects from database with Linq and Lambda

There is an Api method called via Ajax. After parsing and other necessary things has been finished, I get the following result.
["IG4","E1 ","E16"]
As soon as the results received, it calls another MVC ActionResult to display data from the database, where the postcode attribute of the object contains one of these Json results. However it does not work.
public ActionResult SearchResult(JsonResult postcode)
{
var posts = db.Posts.Where(p => p.PostCode.Contains(postcode));
return PartialView("postlist", posts);
}
When the ActionResult is called via Ajax, I checked what url is being called and got the following result
SearchResult?postcode%5B%5D=IG4&postcode%5B%5D=E1+&postcode%5B%5D=E16
$('#searchBtn').on('click', function () {
var _postcode = $('#searchPostcode').val();
var _distance = $('#searchDistance').val();
alert("postcode " + _postcode + " distance " + _distance);
var _url = '#Url.Action("GetPostcodesWithin", "Api/PostcodeApi")'; // don't hard code url's
$.ajax({
type: "GET",
url: _url,
data: { postcode: _postcode, distance: _distance },
success: function(data) {
alert("search ok");
$.ajax({
type: "GET",
url: '#Url.Action("SearchResult", "Posts")',
data: { postcode: data },
success: function (data) {
alert("Post results called");
$("#postList").html(data).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
Json data returned from GetPostcodesWithin method is displayed on the top, which is passed onto SearchResult
You first need to change the method to
public ActionResult SearchResult(IEnumerable<string> postcode)
Then change the 2nd ajax call to
$.ajax({
type: "GET",
url: '#Url.Action("SearchResult", "Posts")',
data: { postcode: data },
traditional: true, // add this
success: function (data) {
....
}
})
The parameter postcode in the SearchResult() method will then contain the 3 string values from your array.
Because you now have a collection of strings, your query now needs to be
var posts = db.Posts.Where(p => postcode.Contains(p.PostCode));
Side note: Your second value contains a space ("EF ") which may need to be trimmed?

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

Jquery and live act wired but act ok after force refresh in IE

somthing is wrong with my code and i can't get what it is...
i have a div id = "personaltab"
i have a form in side it to login the user with username and password. if success the jquery empty the div and puts in the form of the bidding.
if the user try to bid the other ajax that assign to the button is working but for some reason skips the empty and just adding the responded ajax to the div
i have checked that in IE and chrome and it is working fine in chrome
here are my codes
$("#login").click(function() {
var id = $("input#pid").val();
var user = $("input#puser").val();
var pass = $("input#ppass").val();
var dataString = 'id='+ id + '&user='+ user + '&pass=' + pass;
if (user == "") {
alert("error");
$("input#puser").focus();
return false;
}
if (pass == "") {
alert("error");
$("input#ppass").focus();
return false;
}
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
if (msg=="False") {
alert("error");
$("#personaltab").show();
}
else {
$("#personaltab").fadeOut("normal",function(){
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").slideDown();
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
return false;
});
$("#sendbid").live("click", function(){
var startat = $("input[name=startat]").val();
var sprice = $("input[name=sprice]").val();
if (parseInt(sprice)<=parseInt(startat)) {
alert("error");
$("input[name=sprice]").focus();
return false;
}
else {
var payment = $("select[name=payment]").val();
if ($('input[name=credit]').is(':checked') ){
var credit = true;
}
var prodid = $("input[name=id]").val();
var dataString = 'id='+ prodid + '&price='+ sprice + '&payment=' + payment + '&credit=' + credit;
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
}
return false;
});
Solved:
i had inside a and for some reason the div that need to get the ajax by his id was duplicated
don't ask :-)

Resources