Creating divs in AJAX loop - javascript

I am getting data from the server side using AJAX, I am now trying to populate data from from a list of objects into divs, the problem I am having is that I can not create the div while inside of the foreach loop.
$(document).ready(function () {
var divs = "";
var url = "../Graphs/CreateChart";
$.ajax({
type: 'POST',
url: url,
success: function (data) {
for (var i in data) {
var x = data[i];
for (var j in x) {
var val;
if (x.hasOwnProperty(j)) {
val = x[j].SpName;
if (x[j].SpName != "undefined") {
$('#a').appendTo('#content');
createBarChart("#a", "USP_Charts_BarChart1");
}
}
}
}
}, dataType: "json",
cache: false
});
});
</script>
I am trying to populate where it says "#a" with val and also then I need to populate the div I write with the val for the id, but when I try to put the document.write inside of the loop, I get a blank screen, any ideas why it would do this?

you're trying to append a created variable to your content? Try making the markup a string FIRST then appending it.
To test it try it without data.
$("<h2>HI</h2>").appendTo("#content");
If that works, then make a string that is the markup you want, with the data you need.
$("<a data='"+data.variable+"'></a>").appendTo("#content");
append and appendTo are VERY similar, but you need to use a string, not just an identifier, if the object doesn't exist yet.

Related

Get data from localStorage with ajax

I have an array that consists of some links, this array is stored in localStorage. I have a page where I want to display all of them. So when I append any item to my array, it has to be added to the page using ajax.
I have a function that just creates this table using data from local storage:
function get_table(links) {
let result = ["<table class='table text-center'>"];
let number = recent.length;
result.push("<thead><tr><th scope='col'>Page Number</th><th scope='col'>Link</th></tr></thead>")
result.push("<tbody>")
for(let link of links) {
result.push(`<tr><td>${number}</td><td>${link}</td></tr>`);
number--;
}
result.push("</tbody></table>");
return result.join('\n');
}
But I don't know where to apply ajax. I tried doing so:
$.ajax({
type: "POST",
url: "http://127.0.0.1:8000",
data: {recent: localStorage.getItem('RecentPages')},
dataType: 'json',
success: function(data)
{
$('.container').append(get_table(data));
},
});
But it doesn't work. How can I achieve my goal?
There's an approach to add your new data to the table without re write it. I was looking for a callback or event to get when Array.push happen but there isn't.
function ArrayEvent(array){
this.Array = array;
this.push = function(data){
//push the data in the array
this.Array.push(data);
//store it in the local storage
localStorage.setItem("links", JSON.stringify(this.Array));
//add to the end of the table
$("table.table > tbody").append(`<tr><td>${data.number}</td><td>${data.link}</td></tr>`);
};
}
If you don't like it, you could also try with Proxy:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Use JSON output from Flickr to display images from search

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.

Ajax Prototype To Jquery Conversion For Innerhtml Updates

I am attempted to use jquery instead of prototype for the first time. I have a form, when you change the country on my dropdown I would like to then call another script that will bring up the appropriate list of states/provinces. In prototype I would have just used:
function getstates(form) {
document.getElementById("stateresult").innerHTML="<img src='images/ajaxshippingload.gif' border='0'> Processing...";
var checkingurl="shopgetstates.asp";
var pars = 'country=' + form.country.value + '';
var url = checkingurl + '?' + pars;
var target = 'stateresult';
var myAjax = new Ajax.Updater(target, checkingurl, {method: 'post',parameters: pars});
}
I am attempting to convert this into query with little success. I have come up with:
function getstates() {
$.ajax({type:'POST', url: 'shopgetstates.asp', data:$('#ListingForm').serialize(), success: function(response) {
$('#ListingForm').find('.stateresult').html(response);
}});
return false;
}
But I think this is overkill considering I only need to grab the selected value of 1 dropdown. Is there any easier way to accomplish what I am looking to do?

Use a FOR loop within an AJAX call

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:
I never used the for loop in JS, but seems familiar anyway.
The way the loop is made, obviously wont work:
for (i=0;i<required.length;i++) {
var required[i] = $('#'+required[i]).attr('value');
This will create the variables i want, how to use them?
HOPEFULLY, you guys can help me!!! Thank you very much!
required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];
function ajaxrequest() {
for (i = 0; i < required.length; i++) {
var required[i] = $('#' + required[i]).attr('value');
var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: dataString,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.
jQuery:
required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];
function ajaxrequest() {
var params = {}; // initialize object
//loop through input array
for (var i=0; i < required.length; i++) {
// set the key/property (input element) for your object
var ele = required[i];
// add the property to the object and set the value
params[ele] = $('#' + ele).val();
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: params,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}
Demo: http://jsfiddle.net/kPR69/
What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;
var obj = {};
$('.save').each(function () {
var key = $(this).attr('id');
var val = $(this).val();
if (typeof (val) == "undefined")
val = "''"
obj[key] = val;
}
Then send obj as the data property of your AJAX call....
There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.
I would suggest using pre-written library, a few I included below.
http://jquery.malsup.com/form/#validation
https://github.com/posabsolute/jQuery-Validation-Engine
Otherwise the follow would get you close. You may need to covert the array into a string.
var required = ['nome','sobrenome'];
function ajaxrequest() {
var values;
for (i = 0; i < required.length; i++) {
var values[i] = $('#' + required[i]).attr('value');
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: values,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}

JavaScript auto-incrementing a variable in jQuery and AJAX

I have JavaScript using jQuery and AJAX which creates a dynamic array, which has some values used for AJAX request as below;
<script type="text/javascript">
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
var i = 0;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "testdata", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
i++;
}
</script>
The script is suppose to submit values in the array in array[i] for each AJAX request. I made a variable var i which auto increments.. But the script is not working.. The script works well if array[i] is replaced by array[0] or array[1] etc..
How can I solve the syntax error?
Every time you call updateBackground() i = 0 (again). May be you must initialize i outside of the function.
What happens if i > array.length? And I would rename the variable.
You don't have an iterator. Your variable i gets set to 0 every time the function runs. The increment at the end is useless.
Maybe you need something like this?
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
for( var i = 0; i < array.length; i++ ) {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "<?php echo $dir; ?>", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
}
}
Each time you call updateBackground() function, the i variable is being reinitialized. It's just a local variable and as soon as the function finishes it's being destroyed by GC. You could do something like this:
var UpdateBackground = {
array: [..],
counter: 0,
doUpdate: function(cellId, titleId) {
// AJAX request
this.counter++;
}
};
UpdateBackground.doUpdate(1, 1);
UpdateBackground.doUpdate(1, 1);
I think that you should send the whole array maybe as a commaseparated string and instead and make just one ajax request, because http-requests are expensive and change the server side code accordingly. And fetch the cellids as an array.
If you think that you have a long list or a table it can be like a lot of requests. Do the stuff in client code and do the stuff in server code and keep the number of http-requests as few as possible.
And use the join method on the array.
var arr = [ 'y', 'y' ];
arr.join(',');
// outputs y, y
I fixed it... Thank you so much #Jed, #Pointy, #Crozin, and #Lord Vader for helping me to figure it out.... :)
I just take var i = 0; outside the loop.... above var array like;
var i = 0;
var array = Array("y","y","x","y","y","x");

Categories

Resources