Basically what I'm trying to do is have a search bar. The user should input the state and city. Once I get the state and city, update the html with the result. The problem is once i enter an invalid state or city, it gives me an error in the console. What i want is an alert telling the user that they have made a mistake in entering the city or state. I tried using a try and catch/ ajax error function but it doesn't seem to work. Need some help thanks !
$(document).ready(function() {
setTimeout(function(){
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search= $('#search');
var searchsubmit= $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
try {
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}catch(err){
alert(err.message);
}
});
});
I think that adding the error callback should work, here is a jsbin:
https://jsbin.com/ciwosoqeye/edit?html,js,output
var searchresult = '';
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/" +
searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
},
error: function(jqxhr, errorString, ex) {
alert(ex);
}
});
as defined in the doc
Without knowing what error message you are getting or what parsed_json looks like with a bad request, this is only a guess but parsed_json probably doesn't have a location property and/or a city property when bad data is passed in. I'm guessing that is causing the error. If this is the case, you can check for the existence of parsed_json.location and parsed_json.location.city before trying to access them and display the error if they don't exist.
$(document).ready(function() {
setTimeout(function() {
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search = $('#search');
var searchsubmit = $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
if (parsed_json.location && parsed_json.location.city) {
var location = parsed_json.location.city;
var temp_f = parsed_json.current_observation.temp_f;
alert("Current temperature in " + location + " is: " + temp_f);
} else {
alert(err.message);
}
}
});
});
});
Setting a break-point at the beginning of the success callback and inspecting parsed_data would help in debugging this sort of thing.
Related
First, I think my title isn't very clear and very representative of what I want to achieve, but I couldn't make it clearer ...
Ok so I have a Leaderboard, created from this ajax call:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var tb = document.getElementById('Leaderboard');
while(tb.rows.length > 1) {
tb.deleteRow(1);
};
var keys = Object.keys(data);
for( key of keys) {
var username = data[key].username;
var score = data[key].score;
var row = $('<tr id = "row' + tb.rows.length + '"><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
if(tb.rows.length > 11){
tb.deleteRow(tb.rows.length -1);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
So as you can see in the Leaderboard, when clicking on a username, it opens a new page with the result of a GET request (/leaderboard/:username). My question is how can I skin this page, or even better load an html file in this page, but while keeping accessible the result of the GET request to use it inside?
That may not be clear, and that's maybe a reason why my title is not really fitting ... But anyway if you have some ideas i'll take them !!
Thanks
I have a GET ajax call as follows :
var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification
if (dataInfo == "row") {
changeUrl += "&id=" + id
}
changeUrl += "&executedConfigId=" + executedConfigId + "&currUser=" + currentUser + "&productName=" + productName + "&eventName=" + eventName + "&alertDetails=" + JSON.stringify(alertArray);
//if the selected signal is not null then we show the product names
$.ajax({
url: changeUrl,
type: "GET",
success: function (data) {
for (var index = 0; index < checkedRowList.length; index++) {
var row = checkedRowList[index]
signal.list_utils.change_priority(row, targetValue);
}
$('#change-priority-modal').modal('hide');
if (applicationName == "Signal Management") {
signal.list_utils.set_value(parent_row, 'dueIn', id, signal.list_utils.get_due_in, applicationName);
$(parentField).html(targetValue);
}
location.reload();
},
error: function (exception) {
console.log(exception);
}
});
The value of changeUrl as I get in my browser's developer console is :
http://localhost:8080/signal/singleCaseAlert/changePriority?newValue=Medium&justification=test%20justification%20first.&id=6816&executedConfigId=6704&currUser=15&productName=Wonder%20Product&eventName=1.Pyrexia&alertDetails=[{%22alertId%22:%226816%22,%22event%22:%221.Pyrexia%22,%22currentUser%22:%2215%22}]
But I get a 400 bad request status and a http header parse error in the backend. Can someone help me resolve this?
On your JSON.stringify(alertArray) you'll need to also encodeURI();
encodeURI(JSON.stringify(alertArray));
A better solution would be send your JSON in the body of a POST request if thats feasible within your design
I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>
Hi I have this code in my controller:
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
return Json(new {CalculatedBMI = CalculateModel.BMICalc.ToString(), CalculatedBMIMeaning = CalculateModel.BMIMeaning.ToString() }, JsonRequestBehavior.AllowGet);
}
I would like to display CalculatedModel.BMICalc and CalculatedModel.BMIMeaning on the page using this JavaScript:
$('#good').click(function () {
var request = new BMICalculation();
$.ajax({
url: "CalculateAndSaveToDB",
dataType: 'json',
contentType: "application/json",
type: "POST",
data: JSON.stringify(request),
success: function (response) {
var div = $('#ajaxDiv');
div.html("<br/> " + "<b>" + "Your BMI Calculations: " + "</b>");
printBMI(div, response);
},
});
});
function printBMI(div, data) {
div.append("<br/>" + "You are " + response.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + response.CalculatedBMIMeaning + ".");
};
Nothing happens however when I do the button click. The correct data from form goes correctly into DB. My Chrome debugger says however that CalculateAndSaveToDB isn't found 404 error. Please help.
Try to return false at the end of your click function.
$('#good').click(function () {
//Your code
return false;
});
Also I can see an error in your printBMI function. There is not reference to the variable "response". It should be "data"
function printBMI(div, data) {
div.append("<br/>" + "You are " + data.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + data.CalculatedBMIMeaning + ".");
};
There might be several problems:
Your routing is not correct and the post-action cannot be invoked. I dont see any information about routing, so this might be a problem.
You do not return false, as suggested by PraveeReddy. If you dont do so, the browser follows the link of your button.
Just a hint: In such simple scenarios it can be easier to use $.load: http://api.jquery.com/load/
Can any of you see why the div (#welcome) is not being updated in the below code?
function show_logged_in(success)
{
var is_logged_in = success;
var dataString = {"reg":invalid, "login":invalid,"is_logged_in":is_logged_in};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data:dataString,
dataType:'JSON',
success: function(username) {
alert("User is shown");
user = username;
change_div();
},
error: function() {
alert("ERROR in show_logged_in")
}
});
function change_div(){
$('#welcome').style.display = 'block';
$('#welcome').innerHTML = "Welcome" + user + "to SIK";
}
}
The response from the ajax called is simply grabbing the username from the session variable. and it is returning correctly.
And when it returns i would like the div to show up and say welcome.
But for some reason the div is not being updated.
Here is the html:
<div id="welcome" style="display:none; postion:absolute; top:0; float:right;">...</div>
You can't do
$('#welcome').style.display = 'block';
$('#welcome').innerHTML = "Welcome" + user + "to SIK";
with jquery. This is because with $('#welcome') you are grabbing the jQuery object, not the DOM element.
To do this with jQuery:
$('#welcome').html('Welcome' + user + 'to SIK').show(); // Brought up in comments
$('#welcome').show(); // Old
$('#welcome').html('Welcome' + user + 'to SIK'); // Old
Or if you really want to grab the DOM Element:
$('#welcome')[0].style.display = 'block';
$('#welcome')[0].innerHTML = "Welcome" + user + "to SIK";
#Jeff Shaver is right but Pass user as argument change_div(user);
then
function change_div(user){
$('#welcome').show();
$('#welcome').html('Welcome' + user + 'to SIK');
}
try this friend..
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data:dataString,
dataType:'JSON',
success: function(username) {
alert("User is shown");
user = username;
change_div(user);
},
error: function() {
alert("ERROR in show_logged_in")
}
});
function change_div(user){
$('#welcome').css("display","inline");
$('#welcome').append("Welcome" + user + "to SIK");
}
The display property does not exist.
$('#welcome').style.display = 'block';
Use this instead:
$('#welcome').css({"display":"block"});
I'd stick to pure JS with this code.
var welcome = document.getElementById('welcome');
function change_div(){
welcome.innerHTML = "Welcome" + user + "to SIK";
welcome.style.display = 'block';
}