I'm trying to merge two objects I receive as JSON via Ajax, but I can not access the variable and declaring it global. What am I doing wrong?
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
post.done(function( data ) {
postdata = jQuery.parseJSON(data);
});
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
postwatch.done(function( data ) {
postwatchdata = jQuery.parseJSON(data);
});
var postmerge = $.extend(postdata,postwatchdata);
console.log(postmerge);
The answer of postdata = jQuery.parseJSON(data) should be:
{"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be:
{"respwatch":"needlogin"}.
But to access the console, instead of getting postdata and postwatchdata merged, I get an empty object.
Object {} product.js:61
Edit:
I want when post and postwatch done, use data in product function.
The answer of postdata = jQuery.parseJSON(data) should be: {"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be: {"respwatch":"needlogin"}.
function product(data){
var obj = jQuery.parseJSON(data);
if (obj.resplike=='like'){
var respuesta = 'No te gusta';
}
else if(obj.resplike=='dislike'){
var respuesta = 'Te gusta';....blabla
I want to get in obj: {"resplike":"needlogin", "respwatch":"needlogin"}
You cannot handle the result of an asynchronous call like that. All operations done on a async function call must be done within the callbacks of that async method. read more about this in answer
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
$.when(post, postwatch).then(function(arg1, arg2){
var postmerge = $.extend(arg1[0], arg2[0]);
console.log(postmerge);
})
Also since you need to wait for the responses from two different requests you can use $.when() which will back the success handlers once all the passed promises are resolved.
Related
i have file.txt
apple <--line 1
banana <--line 2
and this is my script
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n"); <--i want to split it by line
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord); <--add it to my homelists array
});
});
console.log(homelists); <-- returns array
console.log(homelists[0]); <--undefined
my problem is i cant get the inside value of homelists
how can i get homelists[0] or homelists[1]..(javascript or jquery(preferrable))
Javascript/Jquery ajax is an Async call meaning the code $.get and console.log on your example will be executed parallelly (immediate or the same times), so to parse the result of your file.txt, you need to do it inside the function (which will be executed after ajax called is done).
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n");
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord);
});
console.log(homelists);
console.log(homelists[0]);
});
I know this is too simple answer and may sound stupid to others but i have an idea!
why not store in the session the $.get data
url = 'file.txt';
$.get(url, function(data) {
localStorage['homelists'] = data;
});
then assign a variable to that session
homelists = localStorage['homelists'];
then make the session = null
localStorage['homelists'] = null
when you do console.log outside
console.log(homelists); <-returns string which you can manipulate to turn it into array
console.log(localStorage['homelists']); <-returns null
I dont know yet what could be the bad side/effect of this with my project.. any idea?
Since you are using jQuery, It would be better if you use AJAX. !
const ImportData = function(file){
let arrayData = undefined;
$.ajax({
url: file,
type: 'GET',
error: (err) => { throw new Error(err) },
success: ( data ) => {
arrayData = MakeArray( data );
//Do whatever you want here
console.log( arrayData );
}
});
}
const MakeArray = function(plaintext){
const array = [];
plaintext.split('\n').forEach( (line) => {
line = line.trim();
array.push( line );
} );
return array;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
const file = "https://www.w3.org/TR/PNG/iso_8859-1.txt";
document.addEventListener('DOMContentLoaded', function(){
ImportData( file );
});
</script>
I have an array that I would like to fill with responses from AJAX calls like so:
var dict = [];
function fillArray(){
$.post('getUsersOnline.php', function(phpReturnVal){
// ...
for(var i = 0; i < phpReturnVal.length; i++){
$.get("https://api.twitch.tv/kraken/streams" , function(data){
dict[data.key] = data;
});
});
}
function doStuff(){
// dict is empty or undefined here
}
How would I fill dict with objects so that I could retrieve them inside doStuff()? Currently, I am able to insert stuff into dict but when I try accessing dict outside the fillArray() function, I get an empty dict variable since I'm assuming the GET call is asynchronous and doesn't happen until after all the JS code has executed...
So, dict is an object that has no push method. You'd need dict=[]; If you had to have {}, then you'd need key:value pairs to populate it, such as:
dict[key] = value;
You are going to have to keep track of the number of calls that you are doing in that for loop and fire a callback function once they are all complete. I'm not totally confident about your current solution, with calling an indefinite amount of ajax requests, but I also don't fully understand the scope of your problem or the server that you're talking to.
So basically you will have to do something like this with what you have currently:
var dict = [],
requestsCompleted = 0;
function dictFilled() {
// do something with your dict variable;
}
function fillArray(){
$.post('getUsersOnline.php', function(phpReturnVal){
// ...
for(var i = 0; i < phpReturnVal.length; i++){
$.get("https://api.twitch.tv/kraken/streams" , function(data){
dict[data.key] = data;
requestsCompleted++;
if (requestsCompleted === phpReturnVal.length) {
dictFilled();
}
});
});
}
This haven't been tested, but basically you will have to define a function that will have access to the array that you are filling and call it once all you asynchronous requests finish successfully. For tasks like this though I recommend you take a look at jQuery's Deferred API. There is always a chance that one of those requests will fail and your application should know what to do if that happens.
I'm assuming the GET call is asynchronous and doesn't happen until
after all the JS code has executed...
Appear correct.
Try
var dict = [];
function fillArray() {
// return jQuery promise object
return $.post('getUsersOnline.php', function(phpReturnVal){
// ...
for(var i = 0; i < phpReturnVal.length; i++) {
// call same `url` `phpReturnVal.length` times here ?,
// returning same `data` response at each request ?,
// populating, overwriting `dict` with same `data.key` property ?
$.get("https://api.twitch.tv/kraken/streams" , function(data) {
dict[data.key] = data;
});
}; // note closing `}` at `for` loop
// return value
return dict
});
}
function doStuff(data) {
// `data`:`dict`, promise value returned from `fillArray`
console.log(data);
}
fillArray().then(doStuff, function error(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
});
var arr = ["a", "b", "c"];
var response = {
"a": 1,
"b": 2,
"c": 3
};
var obj = {};
var dict = [];
function fillArray() {
return $.when(arr).then(function(phpReturnVal) {
for (var i = 0; i < phpReturnVal.length; i++) {
// return same `response` here ?
$.when(response).then(function(data) {
dict[arr[i]] = data;
});
};
return dict
});
}
function doStuff(data) {
console.log(data)
}
fillArray().then(doStuff, function error(err) {
console.log(err)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
from controller Json is returned and in function i get an object which contains
{
"readyState":4,
"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{
"Success":0,
"Failed":0
},
"status":200,
"statusText":"OK"
}
How can I take Success and Failed values?
data.Successand JSON.parse(data) is not working
You dont need to parse that because that IS already an object:
var obj = {"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}","responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"};
var failed = obj.responseJSON.Failed;
var success = obj.responseJSON.Success;
var json_data = '{"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"}';
var obj = JSON.parse(json_data);
alert(obj.responseJSON.Success); // for success that in responseJSON
alert(obj.responseJSON.Failed);
Thanks :)
Im learning AngularJs.
And I find my self enjoying it, But im stuck with this code
my controller
$scope.getQuestionaires = function(){
var formdata = $scope.formdata;
var items = parseInt(formdata.items);
var num_letter = parseInt(formdata.num_letter);
var num_missing_letter = parseInt(formdata.num_missing_letter);
var send_data = {
api_type: 'select',
tb_name: 'tb_spelling',
tb_fields: false,
tb_where: false,
tb_others: "LIMIT "+items
};
return factory.getRecords(send_data);
}
my factory
factory.getRecords = function(data) {
return $http.post('models/model.php', {
params: data
}).then(function(response) {
records = response.data;
return records;
});
};
Situation : When I console.log($scope.getQuestionaires), It returns
function (b,j){var
g=e(),i=function(d){try{g.resolve((b||c)(d))}catch(e){a(e),g.reject(e)}},o=function(b){try{g.resolve((j||
d)(b))}catch(c){a(c),g.reject(c)}};f?f.push([i,o]):h.then(i,o);return
g.promise} controllers.js:307 function (a){function b(a,c){var
d=e();c?d.resolve(a):d.reject(a);return d.promise}function d(e,f){var
j=null;try{j=(a||c)()}catch(g){return b(g,!1)}return
j&&j.then?j.then(function(){return b(e,f)},function(a){return
b(a,!1)}):b(e,f)}return this.then(function(a){return
d(a,!0)},function(a){return d(a,!1)})} controllers.js:307
[Object, Object, Object, Object]
Question : My problem is that i only want the array of objects, how can i do that? I think theres a lot i got to improve about my code...I need help :)
Thx
====================================
Fixed
Thx to Chandermani's answer,
Got it!
My controller
$scope.createTest = function(){
$scope.getQuestionaires();
}
/*question getter*/
$scope.getQuestionaires = function(id,question){
/*send_data here*/
var records = factory.getRecords(send_data);
records.then(function(response){
$scope.questionaires = response.data;
});
}
My factory
factory.getRecords = function(data) {
return $http.post('models/model.php', {
params: data
});
};
The method getQuestionaires returns response for your $http post method which is a promise and not the actual data, since the call is async.
Change the method getRecords to
factory.getRecords = function(data) {
return $http.post('models/model.php', {
params: data
});
};
When you call the method getQuestionaires do something like
$scope.getQuestionaires().then(function(response){
//access response.data here
});
Try to understand the async nature of such request. If you ever call async methods within your own functions you can access the response by either returning the promise or provide a callback as a argument to the function.
The following is the code sample I have written. I would like to get the data from REST services and print it on the screen. I could get the response from REST in the JSON format. But, I could not find the way to use store it in the JSONStore and use it. Please help me to resolve this issue.
dojo.provide("index.IndexService");
dojo.require("dojo.parser");
dojo.require("dijit.Editor");
dojo.require("dijit.form.Button");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.data.JsonRestStore");
var xhrArgs = {
url: "http://localhost:8080/RestApp/service/customers",
handleAs: "json",
contentType : "application/json",
load: function(data){
alert(data);
},
error: function(error){
alert(error);
}
}
dojo.ready(function(){
// Create a button programmatically:
var button = new dijit.form.Button({
label: "View Transactions...",
onClick: function(){
// Do something:
dojo.byId("result1").innerHTML += "Functionality yet to be implemented! ";
}
}, "progButtonNode");
alert('hi');
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
alert(store);
store.get(1).when(function(object){
alert(object);
// use the object with the identity of 3
});
//var deferred = dojo.xhrGet(xhrArgs);
//compliantStore = new dojox.data.JsonRestStore({deferred});
alert(deferred);
});
Returned JSON value is
{"employees":{"customers":[{"city":null,"accountNo":null,"name":"Name
1","id":1},{"city":null,"accountNo":null,"name":"Name
2","id":2}],"count":2}}
How would I retrive the values?
JsonRestStore items are actually simple JavaScript objects, therefore you can always directly read properties from items. Like
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
myValue = recipeStore.getValue(item,"foo"); //stored in myValue
get = store.getValue;
set = store.setValue;
save = store.save;
// then fetch an item
var myGetValue = get(item,"foo");
var setMyValue = set(item,"foo","bar");
In synchronous mode, one can fetch without providing a callback, by directly accessing the results property from the request object that is returned from the fetch operation:
var queryResults = store.fetch({query:"?tastes='good'"}).results;
var firstItem = queryResults[0];
Did you meant something like that.. Hope it helps