I'm having difficulty juggling values in jQuery, as most of jQuery is done in an external script, and I'm not sure when I'm in functions and not in functions, so it's hard to tell when global vars are set and not set.
This one in particular is puzzling me, and I'm absolutely stumped, logically to me it should work, but there seems to be something capping it at some point, and disregarding the values I'm trying to store.
I've concluded this, as the error I'm having is that inside the second getJSON call, I'm getting a 'val' undefined issue, but Javascript console isn't showing any javascript errors, just getting an undefined log when I log to the console and also print the object in an alert.
Just need a fresh set of eyes, feel like this is probably something simple, but I've been looking at the code so long that I can't seem to fathom it.
Any help is greatly appreciated.
var post_ids = new Array();
var i = 0;
var val;
$.getJSON("/client-ajax/last-ten-posts.php", function(data){
$.each(data, function(k, val) {
post_ids.push(val.id);
});
});
$.getJSON("/client-ajax/last-ten-posts.php?post-id=" + post_ids[0], function(val){
alert(val.title+"");
$("#postContainer").empty();
$("#postContainer").append("<p class='title'>" + val.title + "</p><div class='post-icon'></div><pre>" + val.content + "</pre><p class='footnote'>Posted by " + val.firstname + " " + val.surname + " at <time datetime='2014-06-10'>08:52</time> GMT+00 on the <time>10-06-2014</time></p>");
});
UPDATE:
I edited the code slightly in light of #N0ir's answer, but to no success. The done method ensure that actions are taken once the async process is complete, but although this is the case, val is still undefined. The code I've tried is below for examination and dissemination.
$.getJSON("/client-ajax/last-ten-posts.php", function(data){
$.each(data, function(k, val) {
post_ids.push(val.id);
});
}).done(function(){
$.getJSON("/client-ajax/last-ten-posts.php?post-id=" + post_ids[0], function(val){
alert(val.title+"");
$("#postContainer").empty();
$("#postContainer").append("<p class='title'>" + val.title + "</p><div class='post-icon'></div><pre>" + val.content + "</pre><p class='footnote'>Posted by " + val.firstname + " " + val.surname + " at <time datetime='2014-06-10'>08:52</time> GMT+00 on the <time>10-06-2014</time></p>");
});
});
UPDATE - Network Return on call for JSON:
GET http://*****************.com/client-ajax/last-ten-posts.php [HTTP/1.1 200 OK 154ms]
GET http://*****************.com/img/home.jpg [HTTP/1.1 304 Not Modified 152ms]
GET http://*****************.com/img/about.png [HTTP/1.1 304 Not Modified 142ms]
GET http://*****************.com/img/about-repeat.jpg [HTTP/1.1 304 Not Modified 147ms]
GET http://*****************.com/img/blog.jpg [HTTP/1.1 304 Not Modified 146ms]
GET http://*****************.com/img/portfolio.jpg [HTTP/1.1 304 Not Modified 210ms]
GET http://*****************.com/img/contact.jpg [HTTP/1.1 304 Not Modified 209ms]
GET http://*****************.com/client-ajax/last-ten-posts.php [HTTP/1.1 200 OK 207ms]
You wanna do somethign like this:
var post_ids = new Array();
var i = 0;
var val;
$.getJSON("/client-ajax/last-ten-posts.php", function(data){
$.each(data, function(k, val) {
post_ids.push(val.id);
});
$.getJSON("/client-ajax/last-ten-posts.php?post-id=" + post_ids[0], function(result){
alert(result.title+"");
$("#postContainer").empty();
$("#postContainer").append("<p class='title'>" + result.title + "</p><div class='post-icon'></div><pre>" + result.content + "</pre><p class='footnote'>Posted by " + result.firstname + " " + result.surname + " at <time datetime='2014-06-10'>08:52</time> GMT+00 on the <time>10-06-2014</time></p>");
});
});
So that the second getJSON call happens after the first one is finished.
So I found the issue, turns out fetchAll() in php's PDO returns an array, so when creating the JSON from the array, the JSON needs to be accessed through the first element of the array, like so:
val[0].content
rather than:
val.content
Related
I'm having an issue with something similar to this and have followed the suggestions but the date is not returning correctly or at all. I think the issue is with the response i.e. the data I'm trying to retrieve.
$(document).ready(function() {
$.getJSON ( "<MYURL>", function(response) {
var location = response["properties"]["name"];
var temp_c = response.temperature;
$(".conditions").html("Current temperature in " + location + " is: " + temp_c + "C");
console.log(response);
});
});
This is the format it is being returned in if I run the link direct from the browser
{"type":"FeatureCollection","crs":{"type":"name",
"properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},
"features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-7.62806,42.32008]},
"properties":{"id":"63797","name":"Xunqueira de Espadanedo",
"municipality":"XUNQUEIRA DE ESPADANEDO",
"province":"Ourense","type":"locality",
"days":[{"timePeriod":{"begin":{"timeInstant":"2016-08-09T20:08:30+02"},"end":
I've been racking my brains all day on this and dont seem to be getting anywhere so any assistance would be appreciated in pointing me int he right direction
I have this javascript code that is meant to run inside the google chrome console. It constantly checks a json formatted response. If anywhere in the response BestPrice equals max_price then it will purchase it using some API. The problem I am having is about 10 seconds after running it I get 'ERR_INSUFFICIENT_RESOURCES'.
I suppose it is from too many requests? I need it to loop through as fast as possible, so if it can't be instant, is there a certain request limit?
Code:
function snipebot(page, max_page, max_price){
$.getJSON('http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&LegendExpanded=true&Category=2&PageNumber=' + page, function(data){
$.each(data, function(index, item){
if (item['BestPrice'] <= max_price){
$.get('http://www.roblox.com/Item.aspx?id=' + item['AssetId'], function(data){
var purchaseData = $($(data).find(".PurchaseButton")[0]).data();
if (purchaseData['expectedPrice'] <= item['BestPrice']){
$.post('/API/Item.ashx?rqtype=purchase&productID=' + purchaseData['productId'] + '&expectedCurrency=1&expectedPrice=' + purchaseData['expectedPrice'] + '&expectedSellerId=' + purchaseData['expectedSellerId'] + '&userAssetID=' + purchaseData['userassetId'], function(){
console.log('[' + item['BestPrice'] + '] #' + new Date().toTimeString())
});
} else {
console.log("Detected purchase.");
}
});
};
setTimeout(function(){
snipebot(page + 1 > max_page ? 1 : page + 1, max_page, max_price);
},100);
console.log("!checked");
});
});
};
snipebot(1, 4, 50);
When you call snipebot, it makes a request, and looking at the URL you're using, it gets an array back. Then for each item in the array, you are spawning another snipebot call. Each of those calls would in turn spawn more snipebot calls and so on. So, yeah, the ERR_INSUFFICIENT_RESOURCES error isn't really surprising.
I have a contact form that encrypts the form message:
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<form name="form_contact" method="post" action="/cgi/formmail.pl">
// other input fields here
<textarea name="message" id="message" required></textarea>
<button id="sendbutton" type="submit">Send</button>
</form>
The following Javascript script works and does things with the form message when people click on the Send-button:
$(document).ready(function() {
$("button[id$='sendbutton']").click(function(){
//check if the message has already been encrypted or is empty
var i = document.form_contact.message.value.indexOf('-----BEGIN PGP MESSAGE-----');
if((i >= 0) || (document.form_contact.message.value === ''))
{
document.form_contact.submit(); return;
}
else
{
document.form_contact.message.value='\n\n'+ document.form_contact.message.value + "\n\n\n\n\n\n\n\n" + "--------------------------" + "\n"
if (typeof(navigator.language) != undefined && typeof(navigator.language) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.language);}
else if (typeof(navigator.browserLanguage) != undefined && typeof(navigator.browserLanguage) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.browserLanguage); }
// and here's where the geoip service data should be appended to the form message
addGEOIPdata();
//finally the resulting message text is encrypted
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
}
});
});
function addGEOIPdata(){
$.get('http://ipinfo.io', function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp');
};
Well, it works except: it does not add the response from the Geoip service ipinfo.io to the form message before encrypting it.
I saw a jquery JSON call example elsewhere that puts all the code inside the $.get('http://ipinfo.io', function(response){...})
but that's not what I want.
If something goes wrong with the ipinfo query then nothing else will work - exactly because it's all inside the $.get('http://ipinfo.io', function(response){...}).
In other words: how can I make my button.click and my $.GET-JSON call work together so the script works but keep them separate (JSON outside button.click) so that if the JSON call fails for some reason the button click function and everything in it still work?
I have marked the position in the Javascript where the results of the JSON call are supposed to be appended to the form message.
Thank you for your help.
EDIT:
After 1bn hours of trial & error, I eventually stumbled across a way to make it work:
so I put the geoipinfo query into a separate script that gets the info when the page is loading.
$.getJSON("https://freegeoip.net/json/", function (location) {
var results = "\n\n" + "IP: "+ location.ip + "\n" + "Location: " + location.city + ", " + location.region_name + ", " + location.country_name;
window.$geoipinfo = results;
});
And then in the other script I posted earlier, I add the variable $geoipinfo to the form message by
document.form_contact.message.value=document.form_contact.message.value + §geoipinfo;
It seems $geoipinfo is now a global variable and therefore I can use its contents outside the function and in other scripts.
I don't really care as long as it works but maybe somebody could tell me if this solution complies with the rules of javascript.
The jQuery API: http://api.jquery.com/jQuery.get/
specifies that you can put a handler in .always() and it will be called whether the get succeeds or fails.
$.get('http://ipinfo.io', , function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp').always(function(){
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
});
I seem to have a memory leak in IE9. It works just fine in Chrome. The memory leak is on the client machine. I left this page open for days in chrome and no leak.
Using jquery 1.9.0, signalr rc2
This page uses signalr and refreshes it's contents every 5 seconds with what comes from the server.
I have four tabs/divs that do this.
proxy.on('newRequests', function (data, updatetime) {
newrequestupdatetime.text('Last updated: ' + updatetime);
numberofnewrequests.text('Number of cases found: ' + data.length);
numberofnewrequeststab.text('(' + data.length + ')');
var h = '';
$.each(data, function (i, val) { h += '<li>' + val.Ref + ' ' + val.Type + '</li>'; });
newrequests.html(h);
});
newrequests is an ul on the page which I initialized like this
var newrequests = $('#newrequests');
in
$(function () {});
Not really sure what is the cause.
I can make it a lot worse by doing this.
newrequests.empty();
$.each(data, function (i, val) { newrequests.append('<li>' + val.Ref + ' ' + val.Type + '</li>'); });
I'm guessing that it has something to do with the last line of code, that puts the new html inside the ul tag.
Try changing the line into this (old code):
document.getElementById('newrequests').innerHTML = h;
See also: jQuery - Internet Explorer memory leaks
I'm trying to get the last 50 tweets using a certain hash tag, on a mobile device using PhoneGap (0.9.6) and jQuery (1.6.1). Here's my code:
function getTweets(hash, numOfResults) {
var uri = "http://search.twitter.com/search.json?q=" + escape(hash) + "&callback=?&rpp=" + numOfResults;
console.log("uri: " + uri);
$.getJSON(uri, function(data) {
var items = [];
if(data.results.length > 0) {
console.log("got " + data.results.length + " results");
$.each(data.results, function(key, val) {
var item = "<li>";
item += "<img width='48px' height='48px' src='" + val.profile_image_url + "' />";
item += "<div class='tweet'><span class='author'>" + val.from_user + "</span>";
item += "<span class='tweettext'>" + val.text + "</span>";
item += "</div>";
item += "</li>";
items.push(item);
});
}
else {
console.log("no results found for " + hash);
items.push("<li>No Tweets about " + hash + " yet</li>");
}
$("#tweetresults").html($('<ul />', {html: items.join('')}));
});
}
This code works great in a browser, and for a while worked in the iPhone simulator. Now it's not working on either the iPhone or Android simulator. I do not see any of the console logs and it still works in a browser.
What am I doing wrong? If it's not possible to call getJson() on a mobile device using PhoneGap, what is my alternative (hopefully without resorting to native code - that would beat the purpose).
Bonus: how can I debug this on a mobile simulator? In a browser I use the dev tools or Firebug, but in the simulators, as mentioned, I don't even get the log messages.
As always, thanks for your time,
Guy
Update:
As #Greg intuited, the function wasn't called at all. Here's what I found and how I bypassed it:
I have this <a> element in the HTML Get tweets
Then I have this code in the $(document).ready() function:
$("#getTweets").click(function() {
var hash = "#bla";
getTweets(hash, 50);
});
That didn't call the function. But once I changed the code to:
function gt() {
var hash = "#bla";
getTweets(hash, 50);
}
and my HTML to:
Get Tweets
it now works and calls Twitter as intended. I have no idea what's screwed up with that particular click() binding, but I ran into similar issues with PhoneGap before. Any ideas are appreciated.
Considering that (a) there isn't much that could go wrong with the first line of your function and (b) the second line is a log command, then it would seem that the function isn't being called at all. You'll have to investigate the other code in your app.
Or are you saying that you don't have a way to read logged messages on your mobile devices?