I have a javascript code that gives a link to a page, if the page does not answer it gives error and try again. I want to receive the error display a message on the screen
I found some questions about it here but could not apply them in my code. This is my code where I can insert the code so that if there is error, show an image on the screen using document.write
window.setInterval(function() {
requestURL = "https://api.spark.io/v1/devices/" + deviceID1 + "/" + getFunc + "/?access_token=" + accessToken;
$.getJSON(requestURL, function(json) {
var vdadosdospark=json.result;//coloca resultado do json na variavel
var vdadosdospark=vdadosdospark.replace("-", '')//exclui caractere -
var resultadoA = vdadosdospark.substr(9, 6);//seleciona os caracteres referentes a amperagem
var resultadoB = vdadosdospark.substr(24, 1);
if (resultadoB==1){
document.write("<IMG ALIGN='center' "+
"style='position:absolute; left: 400; top: 100' " +
"SRC='http://www.uairobotics.com/tomada/Images/farol.png'> " +
"<BR><BR>")
}else
{
document.write("<IMG ALIGN='center' "+
"style='position:absolute; left: 400; top: 100' " +
"SRC='http://www.uairobotics.com/tomada/Images/f.png'> " +
"<BR><BR>");
}
});
}, 5000);
use the .done()/.fail() methods of
jQuery.getJSON().
//first call
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function(data) {
$('#log').append('got data in first call<br>');
})
.fail(function(jqxhr, textStatus, error) {
$('#log').append('got error in first call<br>');
});
//second call
$.getJSON("willFail.js", {
name: "John",
time: "2pm"
})
.done(function(json) {
$('#log').append('got data in second call<br>');
})
.fail(function(jqxhr, textStatus, error) {
$('#log').append('got error in second call<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="log"></p>
Related
I have a small weather app. I get the weather data via "POST" request and append it to the document, that works good.
The users can query the weather by City, now I wanted to load an image of that city with a separate jQuery $Ajax() request.
However, I always get the same result.
The app relevant app structure looks like this:
<input id="getIt" name="cityajax" type="text" class="ghost-input"
placeholder="Enter a City" required> // get user input, querying a city
<button id="submit">Submit</button>
<span class="humidLogo">Current humidity:</span> <i class="fas fa-temperature-low" ></i> <span class="apiHumidity"> % </span>
<div class="FlickResponse"></div> // flickrResposnse gets appended here
</div>
The CSS is not relevant, so I follow up with the relevant JS function right away:
var destination = $("#getIt").val(); // cache the user input, I am not sure I have to listen for a change event here and then update the state.
var flickerAPI =
"https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=" +
destination; // the url to get access the api
$.ajax({
url: flickerAPI,
dataType: "jsonp", // jsonp
jsonpCallback: "jsonFlickrFeed", // add this property
success: function(result, status, xhr) {
$(".FlickResponse").html(""); // here I want to empty the contents of the target div, but this never happens
$.each(result.items, function(i, item) {
$("<img>")
.attr("src", item.media.m)
.addClass("oneSizeFitsAll")
.appendTo(".FlickResponse");
if (i === 1) {
return false;
}
});
},
error: function(xhr, status, error) {
console.log(xhr);
$(".FlickResponse").html(
"Result: " +
status +
" " +
error +
" " +
xhr.status +
" " +
xhr.statusText
);
}
});
That is all. So why do I always get the same response from the API? Do I have to listen to change events on the input field? Because the POSt request work without a change event listener.
Is it because I am querying 2 APIs and I am using the same input field for the value(stupid question, but you never know x).?
Here is a Codepen with the full code, just enter a city and click the submit button:
https://codepen.io/damPop/pen/qLgRvp?editors=1010
I would pull the image retrieval (and weather lookup) into another function as shown below, then you're good!
I've forked to another codepen: updated example
function loadDestinationImage() {
var destination = ($("#getIt").val());
var flickerAPI = "https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=" + destination;
$.ajax({
url: flickerAPI,
dataType: "jsonp", // jsonp
jsonpCallback: 'jsonFlickrFeed', // add this property
success: function (result, status, xhr) {
$(".FlickResponse").html("");
$.each(result.items, function (i, item) {
$("<img>").attr("src", item.media.m).addClass("oneSizeFitsAll").appendTo(".FlickResponse");
if (i === 1) {
return false;
}
});
},
error: function (xhr, status, error) {
console.log(xhr)
$(".FlickResponse").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
}
I'd do the same with the weather:
function loadWeather() {
var destination = ($("#getIt").val());
$.post("https://api.openweathermap.org/data/2.5/weather?q=" +
destination +
"&units=metric&appid=15c9456e587b8b790a9092494bdec5ff",
function (result, status, xhr) {
var APIresponded = result["main"]["temp"];
var APIweather = result["weather"][0]["description"];
var sunGoing = result["sys"]["sunset"];
var output = destination.capitalize();
var humidValue = result["main"]["humidity"];
var windy = result["wind"]["speed"];
var windDirection = result["wind"]["deg"];
if (windDirection <= 90) {
windDirection = "southwest"
}
if (windDirection <= 180) {
windDirection = "northwest"
}
if (windDirection <= 270) {
windDirection = "northeast"
}
if (windDirection <= 360) {
windDirection = "southeast"
}
if (APIweather.includes("snow")) {
$('#displaySky').addClass('far fa-snowflake');
}
if (APIweather.includes("rain")) {
$('#displaySky').addClass('fas fa-cloud-rain');
}
if (APIweather.includes("overcast")) {
$('#displaySky').addClass('fas fa-smog');
}
if (APIweather.includes("sun") || APIweather.includes("clear")) {
$('#displaySky').addClass('fas fa-sun');
}
if (APIweather.includes("scattered")) {
$('#displaySky').addClass('fas fa-cloud-sun');
}
$("#message").html("The temperature in " + output + " is : " + APIresponded + " degrees. The sky looks like this: ");
$(".apiHumidity").text(humidValue + " %");
$('.apiWind').html(windy + 'km per hour. The wind direction is ' + windDirection);
console.log(APIweather);
}
).fail(function (xhr, status, error) {
alert("Result: " + status + " " + error + " " +
xhr.status + " " + xhr.statusText);
});
}
And call from the submit function:
$("#submit").click(function (e) {
loadDestinationImage();
loadWeather();
});
I'm trying to grab the title of the youtube video and print it on a page, under the thumbnail of this video.
Everything works fine, I got the API key, and the titles are printing to the console. But It's done with Ajax so I have to make everything wait for the title to come. And that's where I'm stuck.
So how do I make the code/loop wait for Ajax to finish it's doing?
My simplified code. I tried posting it on code pen but no luck with making js work.
https://codepen.io/anon/pen/JyYzwM
Link to a live page with it. It works there and you can see the console returns the titles.
http://boiling-everglades-49375.herokuapp.com/video.php
$('.category-shape').on('click', function () {
var documentary = ["siAPGGuvPxA", 'i6Hgldw1yS0', 'Omg1gMNtVpY', 'MfWHPnxrDI4', 'aT0HduxW8KY'];
showVideos(documentary);
}
function showVideos(channel) {
if (!isFirstPass) {
$('#addedContent').remove();
}
$('#dropdownVideoPicker').append('<div id="addedContent"></div>');
console.log(" ");
for (var i = 0; i < channel.length; i++) {
var title = getTitle(channel[i]);
$.when(getTitle(channel[i])).done( function () {
var pageCode = generatePageCode(channel[i], title);
console.log(getTitle(channel[i]));
$('#addedContent').append(pageCode);
});
}
$('#addedContent').hide();
$('#addedContent').slideDown();
isFirstPass = false;
$("html, body").animate({scrollTop: ($('.category-shape:nth-of-type(6)').offset().top)}, 1000);
grabYtId();
}
function grabYtId() {
$('.videoThumbnail').on('click', function () {
var $ytId = $(this).attr('src').slice(27, -6);
showModalWindow($ytId);
});
}
function showModalWindow(Id) {
var $theModal = $("#videoModal"),
iframe = $("#iframe")[0],
videoSRC = 'https://www.youtube.com/embed/' + Id,
videoSRCauto = videoSRC + "?autoplay=1&rel=0&controls=1&showinfo=0";
$(iframe).attr('src', videoSRCauto);
$('button.close').click(function () {
$(iframe).attr('src', videoSRC);
});
$theModal.on("hidden.bs.modal", function () {
$(iframe).attr('src', videoSRC);
});
}
And that's the function that grabs the titles
function getTitle(videoId) {
$.ajax({
url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + "AIzaSyCDyE576FU2QRbkHivxHfrjbEjPwartzKo" + "&fields=items(snippet(title))&part=snippet",
dataType: "jsonp",
success: function (data) {
var title = data.items[0].snippet.title;
console.debug("function: " + title);
var titleLoaded = new CustomEvent('titleLoaded', {
detail: {
loaded: true
}
});
$('body')[0].dispatchEvent(titleLoaded);
return title;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus, +' | ' + errorThrown);
}
});
}
And yes, I know that giving an API key to the public is a bad idea but I'll change it add a website restriction in google.
You can push the ajax deffered objects in an array and call $.when.apply($,arr) to wait for all the call to be processed:
function showVideos(channel) {
if (!isFirstPass) {
$('#addedContent').remove();
}
$('#dropdownVideoPicker').append('<div id="addedContent"></div>');
var arr = $.map(channel, function(data) {
getTitle(data);
});
$.when.apply($, arr).then(function() {
$('#addedContent').hide();
$('#addedContent').slideDown();
isFirstPass = false;
$("html, body").animate({
scrollTop: ($('.category-shape:nth-of-type(6)').offset().top)
}, 1000);
grabYtId();
});
}
function getTitle(videoId) {
return $.ajax({
url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + "AIzaSyCDyE576FU2QRbkHivxHfrjbEjPwartzKo" + "&fields=items(snippet(title))&part=snippet",
dataType: "json",
success: function(data, status, jqxr) {
var title = data.items[0].snippet.title;
var titleLoaded = new CustomEvent('titleLoaded', {
detail: {
loaded: true
}
});
$('body')[0].dispatchEvent(titleLoaded);
var pageCode = generatePageCode(videoId, title);
console.log(title);
$('#addedContent').append(pageCode);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus, +' | ' + errorThrown);
}
});
}
You can find a fiddle here
Can anyone help me with this code? I would like to convert this async ajax to sync ajax. How do I do it? Here is the code that is written below. The system just lags when I leave it for 20 mins without even doing anything. So, maybe the problem is within the code.
function addmsg20(type, msg, data) {
$('#display20').html(data);
}
function waitForMsg20() {
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
var data = JSON.parse(data);
if(data.data.length > 0){
var res = data.data;
var printed = "<ul class='menu'>";
$.each(res, function(k, v){
var empext = v.employee_ext;
if(empext == null){
empext = "";
}else{
empext = v.employee_ext;
}
printed += "<li>" +
"<a href='#'>" +
"<h4>" +
" "+v.employee_fname + " " +
v.employee_mname+" "+v.employee_lname+" " +empext+ "<small>" +
v.status_desc+ "</small>" +"</h4>" +
"<p>" + v.subj_name + "</p>" +
"</a></li>";
})
printed += "</ul>";
}else{
printed = "";
}
addmsg20("new", data.count, printed);
setTimeout(
waitForMsg20,
1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg20("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg20,
15000);
}
});
};
$(document).ready(function() {
waitForMsg20();
});
I am completely new to Javascript and/or AJAX so I really need help about this.
To make the AJAX call synchronous, just set async to false:
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: false,
cache: false,
timeout: 50000,
.
.
.
Hello i have a problem with ajax and two callbacks code look like that
loadTasks(function(tasks) {
taskhtml = whatStatus(tasks);
loadSupportList(function(tasks) {
supporthtml = support(tasks);
$("#devtask-table").html(
titleDraw() + "<tbody>" + supporthtml + taskhtml
+ "</tbody>");
hideCurtain();
});
});
And it's work fine when loadSupportList or loadTasks have records. But when one of them don't i get Error, status = parsererror, error thrown: SyntaxError: Unexpected end of input. And it jump off function and leave me with nothing. My ajax function looks that way :
function loadSupportList(callback) {
$.ajax({
type : "POST",
url : url,
data : {
userId : userId,
sessionId : sessionId
},
success : function(data) {
callback(data['tasks']);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log("Error, status = " + textStatus + ", " + "error thrown: "
+ errorThrown);
}
});
}
And i dont know what to change, to ignore(?) or made some json with ('success')? Is there a way? Thanks for your time.
I make something silly, but its work so it's not silly
loadTasks(function(tasks) {
taskhtml = whatStatus(tasks);
$("#devtask-table").html(
titleDraw() + "<tbody>" + supporthtml + taskhtml
+ "</tbody>");
loadSupportList(function(tasks) {
supporthtml = support(tasks);
$("#devtask-table").html(
titleDraw() + "<tbody>" + supporthtml + taskhtml
+ "</tbody>");
hideCurtain();
});
});
assuming tasks returns an array... update your loadSupportList function like this..
success : function(data) {
var ret = [];
if(
'object' == typeof data &&
'undefined' != typeof data.tasks
) ret = data.tasks;
callback(ret);
}
I am trying to detect wither a database entry has been successfully input by sending the new inserted ID and a JSON variable to an AJAX call but it is not working in phonegAP, however it is fine in all browsers and I can see that the data is being inserted in the db successfully. All comments/ help appreciated, thanks.
AJAX code -
function InsertQnA() {
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total", Total) + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
alert('this alert is invoked successfully');
if (data.Success == true) {
alert('this alert is not being invoked successfully');
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href='evaluation.html' target='_self'>evaluation.</a>");
}
else if (data.Success==false)
{
alert('this alert is not being invoked either');
viewModel.UserId("Your entry has not been saved, please try again.");
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
mvc function
//
// POST: /Result/Create
[HttpPost]
public ActionResult Create(Result result)
{
if (ModelState.IsValid)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (Request.IsAjaxRequest())
{
int ResultId = result.ResultId;
try
{ //valid database entry..send back new ResultId
return Json(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
return Json(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
}
return RedirectToAction("Index");
}
return View(result);
}
Found two issues with the code:
1.localStorage.getItem("Total", Total) should be localStorage.getItem("Total")
2.dataType : "json" not explicitly mentioned.
I have posted with the relevant corrections.Try this if it helps and also share if if you get any errors.
function InsertQnA() {
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
dataType : "json",
success: function (data) {
alert('this alert is invoked successfully');
try {
if (data.Success == true) {
alert('this alert is not being invoked successfully');
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href='evaluation.html' target='_self'>evaluation.</a>");
}
else if (data.Success==false)
{
alert('this alert is not being invoked either');
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
Make these changes in your server side code.
var json = "";
try
{ //valid database entry..send back new ResultId
json = Json.Encode(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
json = Json.Encode(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
Response.Write(json);
From what I have gathered (over the past two days) an MVC ActionResult does not seem to easily serve a webapp with data. I got round this by duplicating the ActionResult with a string method and it works fine now. Probably not the best solution but I have heard that its better to create two action methods instead of having one when serving a web view and a web app. Many thanks to everyone who posted.
MVC Action -
[HttpPost]
public string CreateResult(Result result)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (result == null)
{
// User entity does not exist in db, return 0
return JsonConvert.SerializeObject(0);
}
else
{
// Success return user
return JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}
}
AJAX -
$.ajax({
url: Domain + '/Result/CreateResult',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
try {
if (data != 0) {
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href=evaluation.html target=_self>evaluation.<a/>");
//reset locals
ResetLocalStorage();
//count number of entities for User
CountUserEntitiesInResults();
}
else
{
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});