So I recently asked a question concerning looping through data in a json file from an asynchronous AJAX call in jquery that uses callback functions (Looping through AJAX and callbacks in jquery) and I got a lot of good help, but now I wonder if I were to have 3 different json files (same structure and naming convention, but holding slightly different data) and their URLs in an array called myURL, would there be a way to loop through the AJAX call for all three URLs and output each of their respective results on a webpage? Below is my code:
<html>
<head>
<title>Weather Data for Emergency Models</title>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
<script Language="JavaScript">
//New Array for my URLs
var myURL = ["ticker1.json","ticker2.json","ticker3.json"];
function hmm(callback) {
$.ajax({
url : myURL[j], //<<<---Want to loop through this array
dataType: 'json',
success: function(response){
callback(response);
}
});
}
hmm(function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
document.write('<br>');
});
});
</script>
</body>
</html>
$.each(myURL,function(i,url){
hmm(url,function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
document.write('<br>');
});
});
});
And in your function -
function hmm(url,callback) {
$.ajax({
url : url,
dataType: 'json',
success: function(response){
callback(response);
}
});
}
Try this
for(var k=0,len=myURL.length; k<len; k++)
$.ajax({
url : myURL[k++], //<<<---Want to loop through this array
dataType: 'json',
success: function(response){
callback(response);
}
});
}
Related
My Django app sends through AJAX POST/GET communications arrays representing parts of my DB. As you can see on the picture, this is a typical array with all the objects. The objects represent a messages to integrate in a chat box. Just to clarify, the amount of objects might vary, so I need a loop function or smthg to display all the objects within the response array .
Therefore, I need to display these arrays, combining HTML and JS.
This is my exact AJAX Json response
HTML:
<div id="display"></div>
JS:
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/checkview",
success: function(response){
console.log(response);
$("#display").empty();
for (var models_to_return in response.message)
{
var temp="<div class='container darker'><b>"+response.messages[models_to_returney].user_id+"</b><p>"+response.messages[models_to_return].room+"</p><span class='time-left'>"+response.messages[models_to_return].datetime+"</span></div>";
$("#display").append(temp);
}
},
error: function(response){
//alert('An error occured')
}
});
},1000);
})
</script>
But nothing is displaying.
you can do like this
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/checkview",
success: function(response){
console.log(response);
$("#display").empty();
for (var model in response.models_to_return)
{
var temp="<div class='container darker'><b>"+model.user_id+"</b><p>"+model.room+"</p><span class='time-left'>"+model.datetime+"</span></div>";
$("#display").append(temp);
}
},
error: function(response){
//alert('An error occured')
}
});
},1000);
})
I'm using an ajax call to append a MVC partial view with some styles sheets and script files to my php page.
However it is not appending de <script> tags. I already checked my HTTP request on the network and it really brings those tags.
My code:
$.ajax({
type: 'POST',
url: 'http://localhost:63322/MyController/MyAction', //external url project
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
crossDomain: true,
processdata: true,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "*"
},
success: function(result){
$(".pageContainer").html(result);
},
error: function(er){ alert('Error'); }
});
On ajax success function I already tried:
to use $(".pageContainer").empty().append(result)
to separate the script tags and add to <head> like this:
var elems = $(result);
var scripts = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() == "script";
}catch(er){ return false; }
});
var remainElems = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() != "script";
}catch(er){ return false; }
});
$.each(scripts, function(){ $('head')[0].appendChild(this); });
$(".pageContainer").append(remainElems);
to give some time before appending with setTimeout(function(){ $(".pageContainer").html(result); }, 1000);
to change <script> tags to <link type="text/javascript" src="http://someurl.com" rel="tag"/> and it was appended but the code wasn't executed
But nothing works.
What is wrong? What I'm missing?
My PHP page uses jquery-1.8.3 and jquery-ui-1.9.2.custom. This is the problem?
NOTE:
My question is very different from that on: Executing inside retrieved by AJAX
If you read both you will see they are very different. I already readed what and noticed that.
Solved. I don't know why but seems jquery-1.8.3 don't performs the insertion of the <script> tags to the html code dynamically.
I changed
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
to
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
and now it works.
I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')
I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.
I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.