get value from $(document).ready - javascript

I am pulling temperature reading from my temp.php and displaying it on my index.php with the code below.
My problem is I cannot use the information for anything else
I would appreciate any suggestions.
<div id = "temperature"></div> // displays as expected
$(document).ready(function(){
setInterval(function(){
$("#temperature").load('temp.php')
}, 1000);
});
temp1 = document.getElementById('temperature').value; // this doesn't work
if (temp1 == 72) {do something}; //cannot get the value of "temperature"

You should get the response in the callback like the following
<script>
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>

Related

Writing fail case for ajax call in getJSON

I have following code of ajax call and I would like to write custom error on failed ajax call.In following piece of code block, where I can write the same:
$.getJSON("/ProductMatrix/CaptureCategoryTypeList/" + $("#categoryFilter > option:selected").attr("value"),
function (data) {
var items = "<option> Default </option>";
$.each(data,
function (i, captureCategoryType) {
items += "<option value=' " + captureCategoryType.Value + "'>" + captureCategoryType.Text + "</option>";
});
$("#categoryTypeFilter").html(items);
SherlockAdmin.Shared.closeProcessingWheel();
});
It's as simple as
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
console.log( "second complete" );
});
Code from http://api.jquery.com/jquery.getjson/

jquery.post and variable scope

I'm new to javascript and have the following problem.
I want to load some json from an api.php and succeed with the returned value to fill my GUI.
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) { json = data; });
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
});
So I wanna click a button, then it fetches via post some data ans save this to the variable data.
As it should be an object (json object?) I thought I just can use it as above...
But that doesn't work. Console say: can't find variable json.
Any hints?
jquery post as default works asynchronously which means that the line:
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
occur before the post request have returned the data.
this how it should be done:
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) {
$('#data1').empty().append( data[0].name + ' | ' + data[1].name );
});
});
You have your appending outside the post callback function. Try this:
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) {
json = data;
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
});
});

Adding options to select field using javascript from a json file

var json = $.getJSON("../category.json", function() {
alert(2);
})
.done(function() {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
var1.innerHTML = "<option value='" + key + "'>" + val + "</option>";
alert(var1);
})
.fail(function() {
alert( "error" );
});
I want to values from json file as options to my select field. But my code always shows alert error. Please tell me what is wrong with it ?
You're not setting your key and value parameters. In fact it doesn't look like you're getting your JSON results at all.
Change your done method to
.done(function( data ) { /* do stuff */ }
Now your JSON results will be stored in data.
Then you may need to loop through the results. See the example here
try this
var json = $.getJSON("../category.json", function(data) {
alert(2);
})
.done(function(data) {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
$.each( data, function( key, val ) {
var1.innerHTML += "<option value='" + key + "'>" + val + "</option>";
alert(var1);
});
alert(var1);
})
.fail(function() {
alert( "error" );
});
Your JSON is not valid: You cannot use a number as a JSON key
[
{
"NAME":"chair",
"0":"chair" <-- error
},
{
"NAME":"bed",
"0":"bed" <-- error
},
{
"NAME":"table",
"0":"tabl‌​e" <-- error
},
{
"NAME":"almira",
"0":"almira" <-- error
}
]
Try running your JSON through an online JSON parser and the error will come up.
Alternatively, change your error handler to include more information
.fail(function (jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText) }
});

Creating error handling in jQuery

I am trying to create an error message from jquery for my document.
I have populated a <select> menu with JSON data, they link to external HTML files to display weather for their Location, what I need is for an error message to appear if there is no HTML file for the option.
For example the locations are London, New York, Paris and Rome, all except Rome have an HTML file that has weather data in it and displays fine but when Rome is selected...Nothing happens! and when Rome is selected after another location has been selected it stays on the current data!
I am using jQuery to pull the data etc. its my gut feeling that it needs an if() statement but I'm not sure of the conditions of the statement!
My jQuery code is here...
$(document).ready(function () {
// The below function pulls in the data from the external JSON file
$.getJSON('json/destinations.json', function (data) {
// attaches it to a variable
var destinations = data.Destinations;
$(destinations).each(function (id, destination) {
$('#destinations').append('<option value="' + destination.destinationID + '">' + destination.destinationName + '</option>');
});
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function () {
$('#weatherForecasts').show("slow");
});
});
});
// Hide statements for our extra fields and also the weather forecast DIV
$('#weatherForecasts').hide();
$('#extraFields').hide();
$('.errorMessage').hide();
// Function that allows us to see the extraFields when a radio button is checked!
$("input[name='survey1']").change(function () {
$("#extraFields").show("slow");
});
$("input[name='survey1']:checked").change(); //trigger correct state onload
});
http://api.jquery.com/load/
at the bottom of the page there is an example for handling errors:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
So in your case
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function (response, status, xhr) {
if (status == 'error'){
// do error things
}else{
$('#weatherForecasts').show("slow");
}
});
});

How to encode URL being passed to div.load()?

I am using a URL rewrite and using
$('#somediv').load(query, function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry there was an error: ";
$("#somediv").html(msg + xhr.status + " " + xhr.statusText);
}
});
But the div.laod() wont work when my query has character like '?','&' and '='.
As in when I pass parameters as shown beloew, div rendering wont happen .
query ="http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html?date=2011-09-30&email=something#gmail.com&view=external"
But this works!
query ="http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html"
So How do I pass parameters in some encoded way? or any other solution for this is welcome, coz I am clueless..
After some more research, I have a doubt that it is only the # symbol which is creating the problem. Is it so? If yes, what is the possible solution fro that?
Thanks,
Adarsh
The second parameter in .load() is for passing query data. Here's the reference: http://api.jquery.com/load/.
Demo: http://jsfiddle.net/ThinkingStiff/EKHbQ/
HTML:
<div id="somediv"></div>
Script:
var uri = 'http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html',
data = {date:"2011-09-30",email:"something#gmail.com",view:"external"};
$( '#somediv' ).load( uri, data, function ( response, status, xhr ) {
if ( status == 'error' ) {
var msg = 'Sorry there was an error: ';
$( '#somediv' ).html( msg + xhr.status + ' ' + xhr.statusText );
};
});

Categories

Resources