I am going crazy with .getjson. I am trying to get data from a Wikipedia API using .getjson and it works fine. Let's say the Wikipedia API returns 10 selections, and before looping over each selection, I am trying to find the length of array in a for loop. The data is not available yet from the '.getjson'.
Here is my work in codepen. Look at console.log(sp.length); and sp.length in the for loop. They should give similar data, but one of them is undefined and other is working fine.
Here is my JS code:
$( document ).ready(function() {
var api_wiki="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch=cat&srwhat=text&callback=?";
var sp;
$.getJSON(api_wiki,function(data){
sp=data.query.search;
// console.log(sp.length);
}); //End of getJSON
for (var i=0;i<sp.length;i++){
}
});//End of get ready
Why does console.log give two different answers even though they both refer to the same variable? One is undefined and the other is working fine.
I edited the question so that it only reflect the problem facing.
You can't ask javascript to use data it doesn't have yet. You need to wait for the data to arrive. Try putting the for loop inside a function and calling the function in the onReady event of the getJSON:
$( document ).ready(function() {
var api_wiki="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch=cat&srwhat=text&callback=?";
var sp;
$.getJSON(api_wiki,function(data){
sp=data.query.search;
console.log(sp.length);
workWithTheData(sp);
}); //End of getJSON
function workWithTheData(sp){
for (var i=0;i<sp.length;i++){
console.log(sp[i]);
}
}
});//End of get ready
Related
I've been trying to execute an AJAX call inside an event handler function for about a day, trying lot of when(), then() and done() stuff and also to set async: false but I am still ending up with undefined errors. My code looks like this:
$('#id').on('itemMoved', function (event) {
console.log(event);
$.ajax({
type: "POST",
url: "create.php",
data: event
});
});
I need to pass the event object to create.php to do some server-side stuff. As console.log(event) is printing the object correctly, I guess the reason is the asynchronous behaviour of ajax - but have still no idea how to solve it.
Edit: First of all, sorry for not making it complete. Lack of knowledge makes it more difficult to decide what is relevant.
itemMoved is an event of jQuery UI Widget jxqkanban. It is triggered when a Kanbanitem is dragged and holds information about old and new column and itemdata (Documentation). I think AJAX is running before the objects content is completely resolved, causing
Uncaught TypeError: Cannot read property 'target' of undefined.
Thanks for your time.
Just been having a play in js fiddle link here.
https://jsfiddle.net/WillCodeForBeer/29kqpo58/1/
$("#click").click(function(event){
console.log(event)
data = {};
data.timestamp = event.timeStamp
$.post('/echo/js/?js=hello%20world!', { data : data } );
});
I'm not sure what error you are getting but when I tried to only send the event data I was getting a type error. After some reading, it turns out you cannot be sent the event object as
it contains HTML as it will reference the event target.
I would suggest something similar to the above code and extract the data you need out of the event object into another data object and post that.
NB. The post does not complete due to the url being a fake url. The triggering event is also different but the concept is the same.
let me know how you get on.
Here there is fiddle that maybe can be useful to you:
Fiddle
$('#id').on('click', function (event) {
$.post( "https://httpbin.org/post", event).
done(function( data ) {
console.log( "Data Loaded: " + data );
$( "#results" ).append( "Origin: "+ data.origin );
});
});
In Ajax, and in javascript, in general, is essential the concept of callback.
So in the example above the function inside done is executed only when the server responds.
Sorry if this type of question is already been answered.
I am trying to add a page using $("Div").load() inside $(document).ready().
Page is getting loaded but it is not showing anything inside its' variables.
Steps in my code:
Page starts loading
Value come from back-end code (spring java)
Loading a specific page when values are present and show them on page.
If values are null, do not load page.
Jquery version: "2.1.3"
Below is my code:
$(document).ready(
if(condition1){
var var1= data //some json data;
$('#divId').load('url/mypage.jsp');
if(condtition == true){
myFunctionToProcessData(var1);
}
}
)
I have tried ajax call, but its not working.
After completion, I can see my page is loaded and appended in division but not showing on UI and have empty variables.
Please help.
Thank you for your responses. I could not reveal my full code, so made a snippet to give an idea about what i wanted. Issue is fixed now.
Issue was: I wanted to append a JSP on certain condition inside $(document).ready() but the working of $(document).ready() is something like, it ensures executions of methods and conditions written inside it.
Problem was:
Method "myFunctionToProcessData" and "$('#divId').load('url/mypage.jsp');" was called simultaneously , and HTML was not complete at the same time when method called and due to this, my method did not find division to set values and do other validations.
To solve this I have used below approach:
Appended html/jsp page using .load function.
used an ajax method in which i am getting data.
execution steps:
1. Code appended HTML in some time (Using setTimeout function)
2. after execution of all lines in $(document).ready(), ajax function called
3. Now myFunctionToProcessData ca find divisions to set values and proper out put shown on the UI.
code:
$(document).ready(
if(condition1){
var var1= data //some json data;
setTimeout(function() {
$('#divId').load('url/mypage.jsp');
}, 10);
if(condtition == true){
$.ajax({
type : "GET",
contentType : "application/json",
data : "&sid=" + Math.random(),
url : "url", // change to full path of file on server
success : function (data) {
myFunctionToProcessData(var1);
});
}
}
)
This is just a workaround to make sure that myFunctionToProcessData executes only after jsp appended succesfully in it.
now myFunctionToProcessData is executing at the end.
I've just started to learn jquery&javascript, and in my project I've found this block of code, and I'm wondering what does it mean, some parts are confusing to me, all I've understand so far is that this is triggering on some control change event but how can I know which control and how does this work in fact?
<script type="text/javascript">
$(function () {
$("#MainGroupID").change(function () {
var val = $(this).val();
var subItems="";
$.getJSON("#Url.Action("GetSubgroupByMainGroup", "Article")", {id:val} ,function (data) {
$.each(data,function(index,item){
subItems+="<option value='"+item.Value+"'>"+item.Text+"</option>"
});
$("#SubGroupID").html(subItems)
});
});
});
</script>
Please some explanation line by line I'm trying to understand this stuffs how do they work with code behind etc etc :/
Maybe it's stupid question but .. :/
Thanks guys,
Cheers!
//$(function () {
this part is used to invoke the function when the DOM is ready.
$("#MainGroupID").change
//is a change event - like the value of the input has changed.
var val = $(this).val();
//You are picking up the value of the input
var subItems="";
// you are creating a placeholder variable to hold data
$.getJSON(
//this is a call to get json data.
$.each
//you are now looping through the data obtained from the json call
subItems+="<option value='"+item.Value+"'>"+item.Text+"</option>"
//you are now populating the variable you had set
$("#SubGroupID").html(subItems)
//this places the content of the obtained data and the structure from the placeholder into the div with the id SubGroupID
What i'm trying to do is what i thought would be quite easy, but it doesnt seem to be working. I want to get the href of an object and all the function is returning is undefined.
This is the page that i'm requesting and what i'm trying to retrieve is the href held in the element of the first seller (who's ClassName is ui-link-inherit)
var buy = $.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
alert($(data).find(".ui-link-inherit:eq(0)").attr('href'));
}
);
I thought it was a permissions issue at first but it still wont work even if you run that on the page.
Did you tried to just alert the data you get?
If there is no .ui-link-inherit ofc it wont work and since .ui-link-inherit seems to be a class of jqueryUI which adds the classes after the page is loaded via javascript, you wont get this class via GET
//EDIT: I dont get all this "you cant access the data cause ajax is asynchronus". He is using the get-fukction completely right. He can access data since data IS the returned stuff from the server. Did I miss something that you all get this that way?
You cannot return a value from that function, it is executed asynchronously. Instead just wait for the AJAX to finish and then do something with the result
// don't do this
// var buy = $.get(... etc...);
// the variable buy will never have any value
// do this instead
function getHREF(){
$.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
var buy = $(data).find(".ui-link-inherit:eq(0)").attr('href');
doSomething(buy);
}
);
)};
function doSomething(buy) {
// in here do whatever you want with the ajax data
}
$(document).ready(function () {
getHREF();
});
The site does not allow Cross-site HTTP requests. Read here: HTTP access control
I'm trying to get my jQuery to work in this flow:
Parse json using $getJson
Loop through returned JSON and create divs for each JSON item
Once done, repeat but instead with another json file and append the results to the existing results.
But as of now I can't call another function AFTER the first loop is done, because the function gets called before the page is populated. How can I finish the populating loop, and then call another function?
I appreciate any help you can give me. Still learning as you can tell.
function test() {
var i;
for(i=0;i<=10;i++) {
$("div#test").append("<div id='"+i+"'></div>");
}
when_loop_is_done();
}
function when_loop_is_done() {
var i;
for(i=0;i<=10;i++) {
$("div#test div#"+i).append("<span>foo</span>");
}
}
Essentially I'm grabbing JSON from a separate page on my server, then looping through and populating the content using variables from that JSON object. The issue is no matter what I do, the second function always gets called before jQuery populates the content. So if I were to call an alert after the loop is done the page would pop up the alert and then load in all of the appended html.
Store your results in a variable or property. Then, use $(document).ready(fn) to wait for the page to finish loading and populate the page or finish your work when it has finished loading.
Your code should look something like this:
$.getJSON('/remote.json', function (response) {
// do the first loop using the response json
})
.done(function () {
// do the second json request and loop through the results
});
Any code you call inside the done() method's callback function will wait until the previous method in the chain is complete. You should definitely review the API documentation for $.getJSON: https://api.jquery.com/jquery.getjson/