First Time Ajax request getting two url different elements - javascript

var memberURL;
var memberAva;
var memberName;
var members = data.find('.userdata');
for (var j = 0; j < members.length; j++) {
membername = $(members[j]).find('.username').text();
memberURL = $(members[j]).find('.username').attr('href');
}
memberAva = $('#advanced-profile-right img:eq[0]');
$.ajax({
url:"/viewonline",
type:"GET",
data: {memberURL, memberName}, //What should i do here?
success: function() {
$.ajax({
url: memberURL,
type:"GET",
data: memberAva
}).done(function() {
$('.user_info_on').append('<div class="on_name"><img src="' + memberAva + '"/></div>');
}
});
});
What I am trying to get from the first ajax request is the members URL and the Members name- then on success make another ajax request to the Members URL (each) and get the Members Avatar. Then on done post the data that is retrieved. Code is not working, and not sure what I should do?
I tried posting on two .get()s though I guess this is the only way? Anyways anyone have suggestions and tips for me?
The .get() that works-
$(function () {
$.get('/viewonline', function (data) {
data = $(data);
var members = data.find('.userdata');
for (var j = 0; j < members.length; j++) {
var membername = $(members[j]).find('.username').text();
var memberURL = $(members[j]).find('.username').attr('href');
});
$('.user_info_on').append('<div class="on_name"><img src=""/></div>'); //In between source of image would be memberAva from the other .get() request.
}
}, 'html');
});

Related

update a value BEFORE running a function containing ajax

On page load, the code below performs an api request and returns the result. I then have some code that on change of a selector updates one of the variables with the value of that selector and then re-requests the api using the function newsFeed();
My problem is the variable is not getting updated before the function has run.
How do you update a value before running a function containing ajax?
$(document).ready(function() {
var api = '//www.url.com'
var search = 'search?'
var orderBy = 'newest'
var url = api + search + orderBy
//API Call Setup
function newsFeed(data) {
$.ajax({
url: url,
success: function results(data) {
for (var i =0; i < data.response.total; i++) {
var content = '<li>' + data.response.results[i] + '</li>';
$('#news').append(content);
//end of for loop
};
}
});
}
newsFeed();
$("#selector").change(function(){
$('#news').empty(); //remove all child nodes
orderBy = $("#orderBy :selected").text();
newsFeed();
});
});
You're updating the orderBy variable, but then not updating the url with that. Move the declaration of url so it's in the same block as the AJAX call.
$(document).ready(function() {
var api = '//www.url.com';
var search = 'search?';
var orderBy = 'newest';
//API Call Setup
function newsFeed(data) {
var url = api + search + orderBy; // This line has been moved
$.ajax({
url: url,
success: function results(data) {
for (var i =0; i < data.response.total; i++) {
var content = '<li>' + data.response.results[i] + '</li>';
$('#news').append(content);
};
}
});
}
...
In your ajax call, you are requesting url: url
$.ajax({
url: url,
With url defined as
var url = api + search + orderBy
But var url doesn't get magically updated by changing one of the composing variable's value.
Once you've set url it's set (until you update it), so that would be the variable you'd need to update.
The quickest fix will be to just get rid of var url at all and use the ajax call like
$.ajax({
url: api + search + orderBy,
As baao said, your url variable inside newsFeed() doesn't get updated. I'd suggest passing variables as parameters to the newsFeed function.
$(document).ready(function() {
var api = '//www.url.com'
var search = 'search?'
//API Call Setup
function newsFeed(orderBy) {
// set url every time function is called
var url = api + search + orderBy
$.ajax({
url: url,
success: function results(data) {
for (var i =0; i < data.response.total; i++) {
var content = '<li>' + data.response.results[i] + '</li>';
$('#news').append(content);
//end of for loop
};
}
});
}
// First call with default orderBy value
newsFeed('newest');
$("#selector").change(function(){
$('#news').empty(); //remove all child nodes
orderBy = $("#orderBy :selected").text();
newsFeed(orderBy);
});
});
You need to arrange your code like this :
$(document).ready(function() {
var api = '//www.url.com'
var search = 'search?'
var orderBy = 'newest'
var url = api + search + orderBy
$("#selector").change(function(){
$('#news').empty(); //remove all child nodes
orderBy = $("#orderBy :selected").text();
newsFeed();
});
//API Call Setup
function newsFeed(data) {
$.ajax({
url: url,
success: function results(data) {
for (var i =0; i < data.response.total; i++) {
var content = '<li>' + data.response.results[i] + '</li>';
$('#news').append(content);
//end of for loop
};
}
});
}
newsFeed();
});

Cannot read property 'length' of undefined AJAX

I have searched throughout SO about this issue, but I'm not getting any results in my code.
I have a simple JSON parser here, which creates a table based on a JSON object returned by an endpoint. Here is what I have tried so far.
function getAJAXData(APIurl){
$.ajax({
url: APIurl,
type: "GET",
dataType: "json"
}).then(function(data){
alert(data);
});
}
function generateTable(tableId){
var objRecords = getAJAXData("http://jsonplaceholder.typicode.com/posts");
var cols = addTableHeaders(objRecords, tableId);
for(var i = 0; i < objRecords.length; i++){
var tRow = $('<tr/>');
for (var colIdx = 0; colIdx < cols.length ; colIdx++){
var cellVal = objRecords[i][cols[colIdx]];
cellVal = (cellVal == null) ? "" : cellVal;
tRow.append($('<td/>').html(cellVal));
}
$(tableId).append(tRow);
}
}
function addTableHeaders(myList, tableId){
var colSet = [];
var headers = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var hRow = myList[i];
for(var key in hRow){
if($.inArray(key, colSet) == -1){
colSet.push(key);
headers.append( $('<th/>').html(key) );
}
}
}
$(tableId).append(headers);
return colSet;
}
That one doesn't work but when I hard-code a list, it generates a table from the hard-coded list. Can someone please explain what I am doing wrong or missing in the code? Thanks .
These two lines are an issue:
var objRecords = getAJAXData("http://jsonplaceholder.typicode.com/posts");
var cols = addTableHeaders(objRecords, tableId);
First off, your getAJAXData function doesn't return anything, so objRecords will always be undefined.
Second, even if it did return something, it's an asyncronous call, so the data won't be ready right away.
What you need to do is to wrap up the relevant bits of your code into a function and call it on the success callback so it gets executed only after your AJAX data is ready.
You need to call addTableHeaders inside of ajax success
$.ajax({
url: APIurl,
type: "GET",
dataType: "json",
success: function(data){
//call it here
}
})
});

How can I get JSON from WebSQL

I have a little app, that uses WebSQL for data's storage.
I want to sync this data with web-server (PHP+MySQL)
My main problem that I have no idea how can I create a JSON from WebSQL to transfer it.
//view the result from DB on a web-page
$('body').html('<ul id="dataAllHere"></ul>')
mybase.init.getAll = function(){
var database = mybase.init.db;
database.transaction(function(tx){
tx.executeSql("SELECT * FROM table", [], function(tx,result){
for (var i=0; i < result.rows.length; i++) {
item = result.rows.item(i).item;
due_date = result.rows.item(i).due_date;
the_type = result.rows.item(i).the_type;
id = result.rows.item(i).ID;
showAll(item,due_date, the_type, id);
}
});
});
}
function showAll(item,due_date, the_type, id){
$('#dataAllHere').append('<li>'+item+' '+due_date+' '+the_type+' '+id+'</li>');
}
mybase.init.getAll();
I'm not really familiar with JSON and I'll be happy about any help and advice.
Basically you create an object/array and encode it to json, which looks the same, but string formatted. For your code:
var myJson = [];
for (var i=0; i < result.rows.length; i++) {
item = result.rows.item(i).item;
due_date = result.rows.item(i).due_date;
the_type = result.rows.item(i).the_type;
id = result.rows.item(i).ID;
showAll(item,due_date, the_type, id);
myJson.push({item: item, due_date: due_date, the_type: the_type, id: id});
}
$.ajax({
method: 'post',
data: myJson,
type: 'json',
url: 'target.php'
})
you can simplify the loop if you need to
just push every thing from the result to json.
for (var i=0; i < result.rows.length; i++) {
myJson.push(result.rows.item(i));
}

How can I list my twitter followers list in WinJS.UI.ListView

I want to list all my twitter followers in my WinJS.UI.ListView.
WinJS.xhr({
url: "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=" + twitterusername,
responseType: "json"
}).then(
function (xhr) {
var json = JSON.parse(xhr.responseText);
var a = [];
a = json.ids;
//
// now what next?
//
},
function (error) {
myListView.textContent = error;
}
);
I get all my twitter follores id by json.ids.
But next how to find their screen names and prifile pictures and main thing how to bind them with my ListView control. Becouse I had bind simple my static data into ListView but for this example i have no idea.
You have to make another call for each ids to api.twitter.com/1/users/show.json?user_id=json.ids[i].
After you receive all callbacks, you have to create an array with objects that have title, text and picture properties. After that simply bind it with you list.
The following code is an exemple (not tested, don't know if it's functional, but it should point you in the right direction)
var followersCallback = function(xhr){
var json = JSON.parse(xhr.responseText);
var promises = [];
// make promises for each user id (call to twitter to get picture/name/description)
for (var i = 0; i < json.ids.length; i++){
var promise = WinJS.xhr({
url: "https://api.twitter.com/1/users/show.json?user_id=" + json.ids[i],
responseType: "json"
});
promises.push(promise);
}
var dataArray = [];
// join those promises
WinJs.Promise.join(promises)
.then(function(args){
//when you get callback from all those promises
for (var j = 0; j < args.length; j++){
//not sure if parse is needed
args[j]=JSON.parse(args[j].responseText);
//populate your data array
var obj = {};
obj.title = args[j].name;
obj.picture = args[j].profile_image_url;
obj.text = args[j].description;
dataArray.push(obj);
}
//bind your data to the list
var dataList = new WinJS.Binding.List(dataArray);
});
};
WinJS.xhr({
url: "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=" + twitterusername,
responseType: "json"
}).then(
followersCallback,
function (error) {
myListView.textContent = error;
}
);

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");
}
});
}

Categories

Resources