This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
Good day, everybody! I want to make multi lang landing page. There will be select with languages, when you select your lang, JS replace text with another lang from JSON file. But I have got problem with JSON and JS, when I trying to load JSON. I read a lot of guides but nothing help me.
What I have:
There is json file - lang.json. Here is some part of it:
{
"navigation-list" : {
"en" : ["About", "Contacts", "Cases"],
"ru" : ["О нас", "Контакты", "Случаи"],
},
"fb-like" : {
"en" : "Like",
"ru" : "Нравится",
},
"facebook-share" : {
"en" : "Share",
"ru" : "Поделиться",
},
"twitter-tweet" : {
"en" : "Tweet",
"ru" : "Твитнуть",
},
"twitter-follow" : {
"en" : "Follow on twitter",
"ru" : "Читать в twitter",
},
}
and I have main.js file where above JSON file should be imported as var. I used scripts from another guys:
Load local JSON file into variable
and
load json into variable
Here is code:
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'lang.json',
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
console.log(json);
But all the day I get in console null.
Also, I tried another ways, such as:
var lang={};
jQuery.getJSON("lang.json", function(data) {
lang.push(data);
});
console.log(lang);
Nothing help me. What do i do wrong?
Thanks in advance!
You cannot do it like this, the function you are calling is asynchronous in both case.
I will explain the second one.
var lang=[]; // It should be an array not {}
jQuery.getJSON("lang.json", function(data) {
lang.push(data); // This line is called second.
});
console.log(lang); // This line is executed first.
Here
jQuery.getJSON("lang.json", function(data) {
lang.push(data); // This line is called second.
});
The jquery will read your file lang.json but the other code will not wait for it to return. They will execute normally.
So, How you can read the data?
You can read data only after your callback is called.In your jQuery.getJSON along with the name lang.json you are also passing a function
function(data) {
lang.push(data);
}
This will be called when the file is read. The data parameter of the function will have the content of the file.
So, your code
console.log(lang); // This line is executed first.
when ran there is nothing in lang you need to wait till your callback is called then only your lang will be initialized.
One solution will be to call console.log(lang); from the callback itself.
var lang=[];
jQuery.getJSON("lang.json", function(data) {
lang.push(data);
console.log(lang[0]);
});
And if you have other code then you can create a function and call that from the callback.
var lang=[];
jQuery.getJSON("lang.json", function(data) {
lang.push(data);
_do();
});
function _do(){
console.log(lang[0]);
// Do all code dependent on the lang
}
Related
I'm following this guide to setup JsTree with lazy load using Ajax in my Laravel 5.5 app .
This is my controller: https://gist.github.com/aaronr0207/7fa0a38f40bfd2f728a15d655254f82d
My View:
https://gist.github.com/aaronr0207/f87720263e3d6026b04b00c08bae5cb2
My JsTree class is exactly the same I didn't make any change.
Actually I'm getting the following error on chrome's console:
d9973d3e-1476-4453-a013-9e9c8430bcba:1 Uncaught TypeError: Cannot read property 'children' of undefined
But when I dump the response to debug it (at the end of TreeViewController data method):
dd(response()->json($tree->build()));
It works...
My response looks like this (when I die-dump it):
Any idea? Thank you
EDIT1: If I return a simple json_encode($tree->build) there are no errors but it shows an empty tree... and the response looks like this:
EDIT2: got it! But now there are a new issue... All I did to solve it was change the url string with a callback:
$('#jstree').jstree({
'core': {
'data': {
'url': function (node) {
return '{!! route('tree.data') !!}' ;
},
'data': function (node) {
console.log(node);
return {'id': node.id};
}
}
}
});
But now when I fetch next level directories, if they have another directorie inside it fails without error:
Test1 content is the following:
If I delete test1/test2 folder, it works showing:
Same when I delete the txt file...What is happening now? Maybe this is a new question so I'll post my solution to the main problem and I'll accept it.
I suspect your named route is not working correctly. In your TreeController.php, change the route tree/route as follows:
Route::get('tree/route', 'TreeController#data')->name('tree.data');
got it! All I did to solve it was change the url string with a callback:
$('#jstree').jstree({
'core': {
'data': {
'url': function (node) {
return '{!! route('tree.data') !!}' ;
},
'data': function (node) {
console.log(node);
return {'id': node.id};
}
}
}
});
This could be caused by the escaping in the response. Can you dd($request->id) when the id is set?
I've been trying to make a request to a NodeJS API. For the client, I am using the Mithril framework. I used their first example to make the request and obtain data:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://localhost:3000/store/all"});
}
};
var Component = {
controller: function() {
var stores = Model.getAll();
alert(stores); // The alert box shows exactly this: function (){return arguments.length&&(a=arguments[0]),a}
alert(stores()); // Alert box: undefined
},
view: function(controller) {
...
}
};
After running this I noticed through Chrome Developer Tools that the API is responding correctly with the following:
[{"name":"Mike"},{"name":"Zeza"}]
I can't find a way to obtain this data into the controller. They mentioned that using this method, the var may hold undefined until the request is completed, so I followed the next example by adding:
var stores = m.prop([]);
Before the model and changing the request to:
return m.request({method: "GET", url: "http://localhost:3000/store/all"}).then(stores);
I might be doing something wrong because I get the same result.
The objective is to get the data from the response and send it to the view to iterate.
Explanation:
m.request is a function, m.request.then() too, that is why "store" value is:
"function (){return arguments.length&&(a=arguments[0]),a}"
"stores()" is undefined, because you do an async ajax request, so you cannot get the result immediately, need to wait a bit. If you try to run "stores()" after some delay, your data will be there. That is why you basically need promises("then" feature). Function that is passed as a parameter of "then(param)" is executed when response is ready.
Working sample:
You can start playing with this sample, and implement what you need:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://www.w3schools.com/angular/customers.php"});
}
};
var Component = {
controller: function() {
var records = Model.getAll();
return {
records: records
}
},
view: function(ctrl) {
return m("div", [
ctrl.records().records.map(function(record) {
return m("div", record.Name);
})
]);
}
};
m.mount(document.body, Component);
If you have more questions, feel free to ask here.
** JSON Data **
{
"data" : [{
"book" : "first book", -- > i want this via model.get('book');
"aurthor" : "xyz"
}
]
}
** Get json data using jquery Ajax. **
var jsonData = {};
$.ajax({
url : 'booklist.json',
async : false,
dataType : 'json',
success : function (json) {
jsonData = json.data;
}
});
** Model declaration here **
var MyModels = Backbone.Model.extend({
initialize : function () {},
defaults : {}
});
var modelinstance = new MyModels(jsonData);
modelinstance.get('book'); // it is giving undefined how can i get this value.
** Please help where i doing wrong.i am new in Backbone. **
If the data is always a single object wrapped up like that then you'd just add a parse method to your mode:
parse model.parse(response, options)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model.
Something like this:
parse: function(response) {
return response.data[0];
}
You can also trigger a parse call through the model constructor using the parse: true option:
constructor / initialize new Model([attributes], [options])
[...]
If {parse: true} is passed as an option, the attributes will first be converted by parse before being set on the model.
So if you're manually loading the data through a $.ajax call then you'd have something like this:
success: function (json) {
var m = new MyModel(json, { parse: true });
// Do something with m...
}
This question already exists:
jQuery .load() function (not loading files completely)
Closed 8 years ago.
I've been strugling with query for some time. I have a CMS that i want to use on my site, buy i cant use PHP includes so i decided to use jquery. I have made all the necesary includes and when i open the webpage it doesn't load all the files... Rarely does load() function load every file. Any ideas to solve the problem or alternatives? thanks.
<script type="text/javascript">
$(document).ready(function(){
// find element with ID of "target" and put file contents into it
$('#welcome-container').load('admin/data/blocks/Slider/Text.html');
$('#slides').load('admin/data/blocks/Slider/Imagini.html');
$('#acasa-continut').load('admin/data/blocks/Acasa/Continut.html');
$('#sidebar').load('admin/data/blocks/Sidebar/Continut.html');
$('#sidebar-v1').load('admin/data/blocks/Sidebar/Video-1.html');
$('#sidebar-v2').load('admin/data/blocks/Sidebar/Video-2.html');
$('#principii').load('admin/data/blocks/Despre/Principii.html');
$('#echipa').load('admin/data/blocks/Despre/Echipa.html');
$('#echipament').load('admin/data/blocks/Despre/Echipament.html');
$('#contact-t').load('admin/data/blocks/Contact/Contact.html');
});
</script>
I have checked with deloper tools and it gives ,randomly on every refresh, 500 Internal Server Error on different elements
Client-side code to request composite HTML and distribute it to the various containers will be something like this :
$(document).ready(function(){
$.ajax({
url: 'admin/data/blocks/all/page.html',
dataType: 'json',
success: function(data){
$.each(data, function(i, obj) {
$('#'+obj.target).html(obj.html);
});
}
});
});
This assumes admin/data/blocks/all/page.html to be a server-side resource that will deliver a json-encoded response of the following construction :
[
{ 'target':'welcome-container', 'html':'<div>whatever</div>' },
{ 'target':'slides', 'html':'<div>whatever</div>' },
{ 'target':'acasa-continut', 'html':'<div>whatever</div>' },
{ 'target':'sidebar', 'html':'<div>whatever</div>' },
{ 'target':'sidebar-v1', 'html':'<div>whatever</div>' },
{ 'target':'sidebar-v2', 'html':'<div>whatever</div>' },
{ 'target':'principii', 'html':'<div>whatever</div>' },
{ 'target':'echipa', 'html':'<div>whatever</div>' },
{ 'target':'echipament', 'html':'<div>whatever</div>' },
{ 'target':'contact-t', 'html':'<div>whatever</div>' },
]
I'm using jquery.couchdb.js to query my CouchDB database. The view I want to query has both map and reduce functions within. When sending the basic query as shown below:
$(document).ready(function() {
view_name = db_name+'/jobs_by_mod_stat'
options = {'group': 'true' , 'reduce': 'true' };
mod_stat = {};
$db.view(view_name , {
success: function(data) {
console.log(data)
for (i in data.rows) {
console.log(data.rows[i].value);
}
},
error: function(e) {
alert('Error loading from database: ' + e);
}
});
});
I see a sensible log for the data, indicating the query has been successful. However, changing the line:
$db.view(view_name , {
To
$db.view(view_name , options, {
I don't get a success outcome from the Ajax query, but an error message is not shown either. Firebug shows the query being sent, and the JSON data returned looks sensible:
{"rows":[
{"key":["template","completed"],"value":2},
{"key":["template","running"],"value":2},
{"key":["template","waiting"],"value":6}
]}
But the success function is not entered. Any ideas why I'm seeing this behaviour, I did wonder if it's a bug in jquery.couch.js (I have couchdb 1.1.0).
Cheers.
I've had a bit of trouble myself with the list function, until I went and looked through the source code of jquery.couch.js (the online documentation I found at http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/ seems to be outdated).
Basically, the parameters for view and list are different, the list having an extra parameter for the options, instead of having everything under the same parameter as with views.
View:
$.couch.db('yourdb').view('couchapp/' + viewName, {
keys: ['keys here'],
success: function (data) {
}
});
List:
$.couch.db('yourdb').list('couchapp/' + listName, viewName, {
keys: ['keys here']
}, {
success: function (data) {
}
});