I have problem with my code:
Now I want to send request Ajax to 2 page, is it ok ? if ok, can show me how to do. Thanks.
Example:
function change_select_employee(){
var p="";
p="&month="+document.getElementById('F02S').value;
document.getElementById('select_employee').innerHTML = "";
new Ajax.Request('a.php', { method:'get', onSuccess:onLoad_select ,parameters:p});
}
I want send this ajax to 2 file, a.php, b.php, how do I do it ?
As both comments suggest you can go both ways about this, either run the Ajax.Request twice or use an array to hold your target urls.
function change_select_employee(){
var p = "&month="+document.getElementById('F02S').value;
document.getElementById('select_employee').innerHTML = "";
new Ajax.Request('a.php', { method:'get', onSuccess:onLoad_select ,parameters:p});
new Ajax.Request('b.php', { method:'get', onSuccess:onLoad_select ,parameters:p});
}
or
function change_select_employee(){
destinations = ["a.php","b.php"];
var p = "&month="+document.getElementById('F02S').value;
destinations.forEach(function(dest) {
new Ajax.Request(dest, { method:'get', onSuccess:onLoad_select ,parameters:p});
});
document.getElementById('select_employee').innerHTML = "";
}
You can even define the target url array outside the main function and pass it as an argument to change_select_employee($destinations)
Create a function ( makeAjaxRequestTo(page) ) that sends an AJAX request to a given page, and then simply call it with a few pages, like this:
var pages = [ "/page1/somewhere.php", "/page2/somewhere.php" ];
var page;
for (var i in pages){
page = pages[i];
makeAjaxRequestTo(page); // Your own code goes here to send an AJAX request to page x
}
Related
I am new here but I have a problem and need your help, so in my code I called a JSON file.
var data = {};
var spectator;
var tmp = [];
var IDcatcher =[];
var summonerID = [];
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
});
so this gives me the ID from the JSON which is stored in summonerID variable now I want to use this variable to complete the URL to get the 2nd JSON so.
var spectatorUrl = "link" + summonerID;
Now get the 2nd JSON
var Charcatcher =[];
var CharID = [];
$.getJSON(spectatorUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (Charcatcher in tmp) {}
});
CharID = tmp[Charcatcher].id;
});
My problem is the 2nd JSON doesn't run, it doesn't get anything and returns nothing (obviously).
Help?
I can't run 2 JSONs at different times? If so how can I do it or change it?
As I mentioned, due to the asynchronous nature of JavaScript, if you have an AJAX request with a callback and some code following the request, JS will fire off the AJAX request and will continue with the rest of the code. It won't wait for the result of the AJAX request to return.
Here's a simple demo -
function first() {
setTimeout(() => {
console.log("1");
}, 2000);
console.log("2");
};
first();
Look at the order of the console.log statements in the code, and then check the actual order in the console.
To solve your original problem, you can nest a $.getJSON() inside the first one, this will ensure that summonerID is available when you fire off the second AJAX request.
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
// second AJAX request
var spectatorUrl = "link" + summonerID;
$.getJSON(spectatorUrl, function(data) {
// logic
});
});
I need to display the images on my site from a JSON request.
I have the JSON:
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1
And I have the format I need to put the photo URL in:
https://www.flickr.com/services/api/misc.urls.html
But I don't know how I would loop through that, I found some examples similar, but I am still having trouble seeing what I need.
I am using JavaScript/jQuery to pull the info.
I figure I would have this in a loop.
CurrentPhotoUrl = 'https://farm'+CurrentPhotoFarm+'.staticflickr.com/'+CurrentPhotoServer+'/'+CurrentPhotoId+'_'+CurrentPhotoSecret+'_n.jpg'
But each of those variables would need to be populated with an value from the element. I would need to loop through all 5 elements that are in the JSON.
Any help on how to create this loop would be greatly appreciated.
Try this code
var n = JSON.parse(x) //x is the json returned from the url.
var _s = n.photos.photo;
for(var z = 0 ; z < n.photos.photo.length ; z++)
{
var CurrentPhotoUrl = 'https://farm'+_s[z]['farm']+'.staticflickr.com/'+_s[z]['server']+'/'+_s[z]['id']+'_'+_s[z]['secret']+'_n.jpg'
console.log(CurrentPhotoUrl);
}
Edit ( With actual JQUERY AJAX call )
var n ='';
$.ajax({url: "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1", success: function(result){
console.log(result);
n = result;
var _s = n.photos.photo;
for(var z = 0 ; z < n.photos.photo.length ; z++)
{
var CurrentPhotoUrl = 'https://farm'+_s[z]['farm']+'.staticflickr.com/'+_s[z]['server']+'/'+_s[z]['id']+'_'+_s[z]['secret']+'_n.jpg'
console.log(CurrentPhotoUrl);
}
}});
Output:
https://farm8.staticflickr.com/7198/6847644027_ed69abc879_n.jpg
https://farm3.staticflickr.com/2517/3905485164_84cb437a29_n.jpg
https://farm1.staticflickr.com/292/32625991395_58d1f16cea_n.jpg
https://farm9.staticflickr.com/8181/7909857670_a64e1dd2b2_n.jpg
https://farm9.staticflickr.com/8143/7682898986_ec78701508_n.jpg
This answer assumes your json data will not change. So inside a .js file, set your json to a variable.
var json = <paste json here>;
// the photos are inside an array, so use forEach to iterate through them
json.photos.photo.forEach((photoObj) => {
// the photo will render via an img dom node
var img = document.createElement('img');
var farmId = photoObj.farm;
// you can fill out the rest of the variables ${} in the url
// using the farm-id as an example
img.src = `https://farm${farmId}.staticflickr.com/${serverId}/${id}_${secret}.jpg`
// add the image to the dom
document.body.appendChild(img);
}
Inside your html file that contains a basic html template, load this javascript file via a script tag, or just paste it inside a script tag.
If you want to get the json from the web page and assuming you have the jquery script loaded...
$.ajax({
type: 'GET',
url: <flicker_url_for_json>,
success: (response) => {
// iterate through json here
},
error: (error) => {
console.log(error);
}
});
I'm not sure if this is the best solution but its is something someone suggested and it worked.
const requestURL = 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1'
$.ajax(requestURL)
.done(function (data) {
data.photos.photo.forEach(function (currentPhoto) {
console.log('https://farm'+currentPhoto.farm+'.staticflickr.com/'+currentPhoto.server+'/'+currentPhoto.id+'_'+currentPhoto.secret+'_n.jpg')
})
})
Varun's solution worked for me as well. I don't know which one is better but I thought I would post this as well since it looks like they were done fairly differently.
I want to update a JSON object though my app using the PUT method. I am attempting to partially simulate the operation of a form submission. This call is synchronous, as after the PUT, a 200 should be returned. However, when I try the code below, sendAJAX does not include the object's content, the PUT request has content-length: 0. A submission through the form has all of the correct settings - content-type, x-requested-with, etc. I'm not quite sure why the code below doesn't function as I'm expecting. I've also tried setting var 'data' as a string of json formatted parameters. That also results in a PUT request of content-length: 0.
What am I doing wrong here?
casper.then(function() {
this.evaluate(function() {
var element = document.querySelectorAll("h6");
for (var i = 0; i < element.length; i++) {
if (element[i].innerHTML == "Special Tag") {
var appid = element[i].parentNode.parentNode.getAttribute("app-id");
var wsurl = "https://appurl.net"+appid;
var data = new Object();
data.user_id = "xxxxx-xxxx-xxxx-xxxx-xxxx";
data.name = "Name";
data.description = "blahr blahr blahr";
data.amount = "-9000000";
data.start = 1409900400000;
data.finish = 1412492400000;
data.seq = 0;
data.locked = false;
data.paused = false;
data.contributed_amount = 0;
data.created = 1409920472782;
data.modified = 1426538857339;
data.color = "#E37368";
data.archived = false;
data.target_amount = null;
data.uuid = "xxxx-xxxxx-xxxxx-xxxxxx";
data.aprox_daily_contribution = 0;
return JSON.parse(__utils__.sendAJAX(wsurl, "PUT", data, false, { contentType: "application/json"}));
CasperJS' sendAJAX() function does not support PUT requests as seen in the code:
xhr.send(method === "POST" ? dataString : null);
Or more precisely, it only supports a payload for POST requests. You will have to build the XHR yourself or change the CasperJS code accordingly.
I don't think you need to simulate the form submission. If you're testing the web app, then it is better to actually submit the form and then check if it resulted in a correct page rather than parsing the response, because you will need to effectively implement the logic twice: in the page JavaScript and in your test script.
I a trying to make an ajax call with the URL http://exampleurl.com/site/api/v1/brand/page/1/size/100. I need the page number to change (page/1 in example) based on the response I get from this ajax call. Here is what I currently have
$.when(
$.get("http://exampleurl.com/site/api/v1/brand/page/1/size/100", function(result) {
brands.total = result.totalElements;
brands.pages = result.totalPages;
brands.page = result.pageNumber;
brands.first = result.firstPage;
brands.last = result.lastPage;
})
).then(function() { ... other data });
I would like to $.get("http://exampleurl.com/site/api/v1/brand/page/"+ i +"/size/100"... but I need the loop to be based off of the brands.pages. I have tried putting another ajax call in this get function, however I am unable to set a variable such as brands.data in the second call and retrieve it in the then function. Any help??
Here's an idea:
function fetch(page) {
var url = "http://exampleurl.com/site/api/v1/brand/page/" + page + "/size/100"
$.get(url, function(result) {
// do something
if (page < result.pages) {
fetch(page + 1)
}
}
}
What we're doing is fetching the data, processing, then checking if we're done, if not, we call the same function recursively.
I have a mystic problem with sending parametrs from one page to another.
In one of ExtJs methods i send parameter by POST to another page:
autoLoad : {
url : url_servlet+'form.jsp',
params: str,
scripts: true
}
But i dont know how to get this parametr in JavaScript. Okey i says, and sent parameter in url:
url : url_servlet+'form.jsp?ss=333'
And in another page:
function param(Name){
var Params = location.search.substring(1).split("&");
var variable = "";
for (var i = 0; i < Params.length; i++){
if(Params[i].split("=")[0] == Name){
if (Params[i].split("=").length > 1)
variable = Params[i].split("=")[1];
return variable;
}
}
return "";
}
var s =param('ss');
alert(s);
And see empty alert.
in firebug i try:
window.location.search
and get " ".
Whats wrong? I read several examples and everywere see code like this.
What's likely going on here is that ExtJS loads an entire page from a remote location into the current page.
When this happens, the code that gets run as a result of the load, will execute in the current page (which probably doesn't have the ss=xyz parameter at all).
However, your form.jsp should have access to the query string and can inject that into the page it returns to ExtJS.
Another option is to somehow pass that data from JavaScript once the page is loaded, but I don't know enough about ExtJS to tell you how that could be done.
Can you please try below function ?
function param(Name){
var Params = location.search.substring(1).split("&");
var variable = "";
for (var i = 0; i < Params.length; i++){
if(Params[i].split("=")[0] == Name){
variable = Params[i].split("=")[1];
return variable;
}
}
if(variable=="") return variable;
}
var s =param('ss');
alert(s);
You cannot get POST parameters from javascript. POST parameters are to the server and javascript is on the client side..
If its a GET then you could use parseUri library
var value = uri.queryKey['param'];