How to handle API call error with jQuery AJAX? - javascript

I am making a weather app as a school project. I have an input through which the user is supposed to enter a name of a city to get the weather from an API. If the user misspells the name of the city I get an error in the console. I'd like to catch this when it happens and display some message to inform the user to correct the input. I searched other questions on StackOverflow and jQuery site as well, but didn't get my answer so that's why I'm here.
My code looks like this:
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (weatherData) {...//code}
I tried putting the ajax inside a try/catch block and added error: function().. beneath success, it still doesn't display an error message.
Why isn't this working? Is this easier to do in plain javascript?

Add an if statement to your success function to check if the list has elements in it. Otherwise you will get an error trying to get the name of an element that doesn't exist.
success: function (weatherData) {
if (weatherData.list.length > 0)
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((weatherData.list[0].name)));
}

From your comment it seems that you go and use this:
weatherData.list[0].name
your response as you mentioned is like this
"message":"like","cod":"200","count":0,"list":[]
You should check your response in order to see if you have any server errors.
My guess from what you have provided seems like you don't take into consideration neither the response code nor the number of items. You should change your ajax success handler to something like the following.
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (result) {
// Error handling
if (result.code != '200'){
alert('some kind of error');
return false;
}
// Checking the number of list items
if (result.list.length > 0){
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((result.list[0].name)));
}
}
});

Related

Getting null in return when executing Ajax request

Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.

Accessing a global dictionary in a function

My webpage uses ajax requests to fetch info of different items in my store. However, as of now, everytime you click an item (even the same item) it will reload the data, which is unnecessary as the data is somewhat static. So I tried to fix the problem like so;
var loaded = {}; //save loaded items in dictionary, so it is not necessary to load them again.
function loaditem(item){
if(item.text() in loaded){
postdata = {
item: item.text()
};
$.ajax({
type: "POST",
url: "iteminfo/fetch.php",
data: postdata,
dataType: "json",
success: function(data) {
loaddata(data);
loaded[item.text()] = data; //item.text() is the name of the item in this case
},
error: function() {
console.log('Something went wrong');
}
});
} else {
loaddata(loaded[item.text()]);
}
So to explain the function: the function gets item, which is iniated by html like so: <li onclick="loaditem($(this))">item</li>. The function checks if the name of the item is in loaded (key checking) and if it isn't, it will load the data and save it into loaded.
Problem statement: however, when an item is clicked I get this error:
Uncaught TypeError: Cannot use 'in' operator to search for 'itemname' in undefined
So I searched the web, including StackOverflow, for an answer but I stumbled upon this answer which doens't even give a bloody answer (only an explanation) to the question! How can I access the global var 'loaded' from my function?

JQuery AJAX Call not returning Sucess function

I have a super simple JQuery ajax request below:
$.ajax("../ajax/data/items.json",
{ success: setContent, type: "GET", dataType: "json" });
function setContent(data, status, jqxhr) {
alert("Hello!");
}
The json loads on the page with a 200 response. The success function is set to setContent(). But the success function never runs and I cannot figure out why.
Questions:
Is my understanding of how the success function works incorrect? Why doesn't the function setContent() run for a 200 response on the Json?
Are the arguments for setContent() filled out behind the scenes by JQuery? Obviously I am not setting it anywhere in the code, but the video does not show adding arguments any place.
I am following Lynda.com's tutorial:
http://www.lynda.com/jQuery-tutorials/AJAX-made-simple/183382/368483-4.html
specifically the video AJAX made Simple.
The issue is most likely that you aren't getting back valid JSON. If you specify the data type as JSON and it returns something else, the success handler will not get called.
There is nothing wrong with the syntax:
As you can see, the console.log fires if you don't specify the dataType, as it doesn't care if it is JSON or not. If you do specify, nothing gets logged.
$.ajax(window.location.href,
{ success: setContent, type: "GET", dataType: "json" });
function setContent(data, status, jqxhr) {
console.log("It worked!");
}
You can copy that into dev tools on this site and see what happens when you remove the dataType parameter.

Update div after ajax database insert

so i have some comments pulled from a database and echoed into a div.
Im am entering new comments via a form and they are inserted into the database with ajax.
I want the comments in the div to update and show the new ones as soon as they are posted.
How can i refresh the div to show new content, without the page loading again?
javascript is like so:
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$comment.after('<div class="success">Update Added!</div>');
else
$comment.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
Thanks for any help.
I think you would like to use
http://api.jquery.com/prepend/ for making new comments on the top,
OR,
http://api.jquery.com/append for making new comments on the bottom.
right after using
$comment.after('<div class="success">Update Added!</div>');
Just append or prepend the valid structure that forms your comment box is okay for it.
just like for example:
$("#comment-holder").append("<div class='commentbox'><p class='commenthead'>" + response.newCommentHeadline + "</p><p class='commentcontent'>" + response.newCommentContent + "</p></div>");
Also worth looking into your response.databaseSuccess, you might want to compare it more strictly like using "==", because boolean not always work as you expect, since i am not sure if your responding document are in the correct format that it correctly interprets as a boolean.
you should extract your required data from response json and generate a Html for appending to your div with id of "comment" then as you apply your css it will get styled.
my suggestion is if you don't want to add extra info from your server to the comment, you only need a flag as success or fail and instead of sending data to server and retrieving it you can use your local data when successfully inserted to your database
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
$("#comment").after('<div><div class="from">'+response.from+'</div><div class="message">'+response.message+'</div></div>');
}
fail:function(){
$("#comment").after('<div class="error">Something went wrong!</div>');
}
});
}

Ajax success event not working

I have a registration form and am using $.ajax to submit it.
This is my AJAX request:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
In my submit1.php file I check for the existence of fields email address and username in the database.
I wish to display an error message if those value exist without a page refresh.
How can I add this to the success callback of my AJAX request?
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.
Although the problem is already solved i add this in the hope it will help others.
I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:
function callWebService(cartObject) {
$.ajax({
type: "POST",
url: "http://localhost/AspNetWebService.asmx/YourMethodName",
data: cartObject,
contentType: "application/x-www-form-urlencoded",
dataType: "html",
success: function () {
OnSuccess(cartObject.productID)
},
error: function () {
OnError(cartObject.productID)
},
complete: function () {
// Handle the complete event
alert("ajax completed " + cartObject.productID);
}
}); // end Ajax
return false;
}
If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.
Put an alert() in your success callback to make sure it's being called at all.
If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.
Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.
You must declare both Success AND Error callback. Adding
error: function(err) {...}
should fix the problem
I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.
In my case the reason was , that the closing tag did not match the opening tag.
<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<result>
<status>$status</status>
<OPENING_TAG>$message</CLOSING_TAG>
</result>";
?>
I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
The result was not being returned in JSON format
I was trying to convert an array to JSON format, but this array had non-utf characters
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.
I tried to return string from controller but why control returning to error block not in success of ajax
var sownum="aa";
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : "JSON",
url : 'updateSowDetails.html?sownum=' + sownum,
success : function() {
alert("Wrong username");
},
error : function(request, status, error) {
var val = request.responseText;
alert("error"+val);
}
});
I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved.
note using Lavalite framework.
before:
public function Activity($id)
{
$data=getData();
return
$this->response->title('title')
->layout('layout')
->data(compact('data'))
->view('view')
->output();
}
after code looks like:
try {
$attributes = $request->all();
//do something
return $this->response->message('')
->code(204)
->status('success')
->url('url'. $data->id)
->redirect();
} catch (Exception $e) {
return $this->response->message($e->getMessage())
->code(400)
->status('error')
->url('nothing Wrong')
->redirect()
}
this worked for me
I had the same problem i solved it in that way:
My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response.
Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working.
PS. Sorry if something is wrong but it is my first comment on this forum :)
in my case the error was this was in the server side and for that reason it was returning a html
wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");
Add 'error' callback (just like 'success') this way:
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
},
error: function(jqXhr, textStatus, errorMessage){
console.log("Error: ", errorMessage);
}
});
So, in my case I saw in console:
Error: SyntaxError: Unexpected end of JSON input
at parse (<anonymous>), ..., etc.
The success callback takes two arguments:
success: function (data, textStatus) { }
Also make sure that the submit1.php sets the proper content-type header: application/json

Categories