I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).
Related
I have simple chat that uses ajax to get messages, heres the code:
function get_message_chat() {
$.ajaxSetup({
url: "chat.php",
global: true,
type: "GET",
data: "event=get&id=" + mid + "&t=" + (new Date).getTime()
});
$.ajax({
success: function(msg_j) {
if (msg_j.length > 2) {
var obj = JSON.parse(msg_j);
for (var i = 0; i < obj.length; i++) {
console.log(msg_j.length);
if (mid >= obj[i].id) {
continue;
}
mid = obj[i].id;
name = obj[i].name;
msg = obj[i].msg
$("#msg-box ul").append("<li><b><span class=\"username\" >" + name + "</span></b>:<span id=\"msgid_" + mid + "\" class=\"messsage\" style=\"color:black;\" > " + msg + "</span></li>");
if (msg.indexOf('#' + username) != -1) {
$("#msgid_" + mid).css('font-weight', 'bold');
}
}
$("#msg-box").scrollTop(2000);
}
}
});
setTimeout(get_message_chat, 2000);
}
mid = 0;
It grabs messages from php script "starts from mid ID". Then it shows messages to chat(appends to ul) and sets mid to new message id and then loop repeats. The problem is that it stucks fter mid = 9 for some reason. I still have more messages coming:
[{"id":"10","name":"user1","msg":"messages1234"},
{"id":"11","name":"user2","msg":"messages5678"}]
But they wont display. Everyting looks fine, but I can't understand why is that happening. Thank you for all comments.
This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I am creating a small domain availability checker. For that I will parse the desired domain into a form, and submit that to a PHP file with jQuery AJAX.
However while I am looping through the different TLD's it suddenly gets undefined and I am not able to use the "TLD" for further processing within the loop. As far as I can read, it as something to do with the loop happening first and the requests made after, so I somehow have to freeze the index of my array. But I don't know how to do that.
This is my code:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
};
return false;
});
The printed console.log's looks like this:
This is a classic JavaScript issue. In the success function (a closure), the i is being used. That callback runs in the future, once the AJAX call is done. By that point, the loop has finished, and i has been incremented to 4.
tlds[4] doesn't exist, and that's why you're getting undefined. The callbacks are all using the same i value.
To fix it, you need to create a new function to capture the value of i for each callback.
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
var createCallback = function(i){
return function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
};
}
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: createCallback(i)
});
};
return false;
});
By the time the ajax calls return, the loop has long since ended, and i has run past the end of tlds. Trying to print tlds[i] is bound to fail.
Break the lookup into a separate function, with local variables that will be valid on the ajax callback:
var checkup = function(datastring, domain, tld) {
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tld + " is " + data);
}
});
};
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
checkup(datastring, domain, tlds[i]);
};
You need to enclose the code in your loop in a closure as follows:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
(function() {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
})( i );
}
return false;
});
Let suppose i have a json file
and i can read this file in my script like this
$(document).ready(function () {
$.ajax({
type: "GET",
url: "Package.html",
dataType: "json",
success: function (data) {
var t = '';
for (var i = 0; i < data.yearData.length; i++) {
var mainStoryTitle = data.yearData[i].players;
for (var j = 0; j < mainStoryTitle.length; j++) {
var storyTitle = mainStoryTitle[j].name;
var topStoryContent = mainStoryTitle[j].description;
var storyImage = mainStoryTitle[j].image;
t = t + '<div class="content">';
t = t + '<article class="topcontent">';
t = t + '<header class="top" id="top1"><h2>' + storyTitle + '</h2></header>';
t = t + '<header class="bottom">';
t = t + '<h6><img src="' + storyImage + '" height=150 width=200>' + '</h6></header>';
t = t + '<content class="hide" id="content_' + j + '"><p>' + topStoryContent + '</p></content>';
t = t + '</article>';
t = t + '</div>';
}
}
$(".content").html(t);
},
error: function (e, ts, et) { alert(ts) }
})
});
and then i put this script in my html file.
So when i run this, it works properly but the problem is when i click on view source then inside it shows the path of json instead of exact data.
Hope you got the problem and please revert me asap.thanx
Instead of using alert, use console.log(ts) this will post the JSON file into your console. From there you can easily look around and see the JSON file by clicking the down arrow.
console.log(data); shows as:
> Object {Data: Array[2], ResponseMessage: "", Success: true}
console.log(JSON.stringify(data)); shows as:
{"Data":[{"ControllerID":2,"Description":"Aeon Power Monitor","DevType":1,"ID":1,"Name":"Power Monitor"},{"ControllerID":2,"Description":"Aeon Power Switch","DevType":2,"ID":2,"Name":"Switch"}],"ResponseMessage":"","Success":true}
Im beginner in AJAX & JS so please bear with me.
I use this AJAX for the pagination :
$(function () {
var keyword = window.localStorage.getItem("keyword");
//pagination
var limit = 3;
var page = 0;
var offset = 0;
$("#btnLoad").on('click', function () {
page++;
if (page != 0)
offset = (page - 1) * limit;
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/" + keyword + "/" + limit + "/" + offset, //This is the current doc
type: "GET",
error: function (jq, st, err) {
alert(st + " : " + err);
},
success: function (result) {
alert("offset=" + offset + " page =" + page);
//generate search result
$('#search').append('<p style="float:left;">Search for : ' + keyword + '</p>' + '<br/>' + '<p>Found ' + result.length + ' results</p>');
if (result.length == 0) {
//temp
alert("not found");
} else {
for (var i = 0; i < result.length; i++) {
//generate <li>
$('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p><p class="hidden"></p></li>');
}
var i = 0;
$(".box").each(function () {
var name, address, picture, id = "";
if (i < result.length) {
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
id = result[i].mallid;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
$(this).find(".hidden").html(id);
i++;
});
$(".box").click(function () {
//alert($('.hidden', this).html());
window.localStorage.setItem("id", $('.hidden', this).html());
$("#pagePort").load("pages/MallDetail.html", function () {});
});
}
}
});
}).trigger('click');
});
Please notice that i use the variables for pagination in the url:. I tried to alert the page and offset variable, and its working fine.
However, the AJAX only working for the first page (when page load). The rest is not working even though the page and offset variable's value is true.
Theres no warning/error in console. The data just not shown.
Any help is appreciated, Thanks :D
It is a bit hard to debug your code when the whole HTML is missing.
Could you put your code into JSFiddle, both HTML and JS.
I've been trying to get this right for quite some time, I'm trying to append the object from the first ajax call after the second ajax call. But the for loop seems to iterate the changing of the value to the last result before appending the information, having the last post appended every time.
var scribjson =
{
"user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
type: "POST",
url: "getScribbles.php",
data: scrib,
success: function(result)
{
var obj = jQuery.parseJSON(result);
for(var i = 0; i < obj.length; i+=1)
{
var userjson =
{
"user_id" : obj[i].user_id
};
userjs = JSON.stringify(userjson);
var user = {json:userjs};
localStorage.post = obj[i].post;
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
}
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
Since ajax calls It looks like the all success functions of the inner ajax call are being called after the loop has ended, so i will always be the last iterated value.
Try this:
(function(i)
{
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
})(i);
This will create a closure on i, which will give each ajax call its own copy of the current value.
Use an IIFE:
success: (function(i){return function(result) {
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),
etc. Currently your loop generated ajax success handlers contain a direct reference to the counter itself, which (by the time they are called) has reached its final value.