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>' },
]
Related
I am editing someone else project and they have used a lot of DOM which I'm not familiar with.
First select box
<select name="task_projectid" id="task_projectid"
data-assigned-dropdown="assigned"
data-ajax--url="/feed/projects?ref=general"></select>
When user select project I'm using following to update the data-ajax--url in task_itemid
$(document).on('change', '#task_projectid', function() {
$('#task_itemid').attr('data-ajax--url', '/feed/items?ref=' + this.value);
});
here is task_itemid box
<select name="task_itemid" id="task_itemid"
data-assigned-dropdown="assigned"
data-ajax--url="/feed/items?ref=">
</select>
It's working and url on task_itemid changed to
/feed/items?ref=4
But the Ajax call still going to
/feed/items?ref=
Please help.
I found this
$(".js-select2-basic-search-modal").select2({
theme: "bootstrap",
width: null,
containerCssClass: ':all:',
minimumInputLength: 1,
minimumResultsForSearch: 1,
ajax: {
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.value,
id: item.id
}
})
};
}
}
});
See the documentation:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes, which will override any options set when initializing Select2 and any defaults.
You're changing the attribute, but by that time Select2 has already been initialised and read the old value.
I think you can use the dynamic urls feature to read the value when the Ajax request is triggered.
ajax: {
url: () => $('#task_itemid').attr('data-ajax--url'),
I haven't tested this, and it might override the logic for adding a query string to the URL, in which case you'll need to make that function add the data from params.term too.
Lately i have discovered chrome coverage report that I find very useful.
https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage
The weakness of this tools is that it is single page scoped. But in version chrome 73 there is an option to generate json file for page that can be stored for further processing.
I would like to collect json data for multiple pages, than merge it and visualize in the context of single file (in my case stylesheet).
It would be great if I could receive json file directly through chrome (Extenstion?) API. So far i have found only this example: https://gist.github.com/krisselden/2487706bcbf37da26d4a89d0f74df768. But it seems to work only for browser remote mode.
Do you know is there any way to get coverage json report over chrome API?
Best regards
It Man.
Heres what i got so far (snippets only):
Got extension template form https://extensionizr.com
Inside background.js script have placed this raw method:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request.command);
if (request.command === "getCoverage") {
chrome.tabs.query(
{currentWindow: true, active : true},
function(tabArray){
var activeTab = tabArray[0];
console.log("tabid: " + activeTab.id)
chrome.debugger.attach( { tabId: activeTab.id }, "1.2", function() {
console.log("attached");
chrome.debugger.sendCommand( { tabId: activeTab.id }, "Profiler.enable", undefined, function(result) {
console.log("ProfilerStarted:" ,result);
chrome.debugger.sendCommand( { tabId: activeTab.id }, "Profiler.startPreciseCoverage", { callCount: true }, function(result) {
console.log("coverageStarted:" ,result);
setTimeout(function() {
chrome.debugger.sendCommand( { tabId: activeTab.id }, "Profiler.takePreciseCoverage", undefined, function(response) {
console.log(response.result);
});
}, 4000)
});
});
});
}
);
}
});
Inside browser_action.js:
document.getElementById("getCoverageSnapshot").addEventListener("click", function() {
chrome.extension.sendMessage({
command: "getCoverage"
});
});
And in browse_action.html:
<!doctype html>
<style type="text/css">
</style>
<button id="getCoverageSnapshot">Get Snapshot</button>
<script type="text/javascript" src="/src/browser_action/browser_action.js"></script>
When button clicked Profiler.takePreciseCoverage result can be recieved inside background.js.
Still looking the way to receive css coverage data...
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
}
I have an array of script objects as such:
_externalLibraries = [{name: 'knockout', url: '...'}, { name: 'knockoutValidation', url: '....'}];
I then Tried to write the following:
loadLibraries: function() {
if (_externalLibraries.length === 0) {
return;
}
_externalLibraries.forEach(function(lib){
// Check if the libraries has been registered as "loaded."
var librarysAlreadyLoaded = _loadedLibraries.filter(function(libAlreadyLoaded){
return libAlreadyLoaded.name === lib.name;
});
// If it hasn't been loaded. Load it. This allows for mul;tiple widgets to be on the page.
// Or this file (for what ever reason) to be called multiple times.
console.log(librarysAlreadyLoaded);
if (librarysAlreadyLoaded.length === 0) {
$.getScript(lib.url, function(){
_loadedLibraries.push({name: lib.name});
});
}
});
},
Basically what I am trying to do is say load the library in this array, if it hasn't already been loaded. If it hasn't then load it and add the name to an array of "loaded libraries".
The problem, at least with knockout and knockout validation is that "ko is undefined." How ever after the page loads, I can then type ko in the console and see that it is in fact loaded.
What can I change or add to the code to make it say "Ok I need to wait until each script in this array is loaded." And then do what ever else I want to do.
You can utilize $.when() , Function.prototype.apply()
var _externalLibraries = [{
name: "knockout",
url: "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"
}, {
name: "knockoutValidation",
url: "https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"
}];
var loadedLibraries = [];
$.when.apply($, $.map(_externalLibraries, function(lib) {
return $.getScript(lib.url, function() {
loadedLibraries.push(lib.name)
})
}))
.then(function() {
console.log(loadedLibraries, ko, ko.validation)
}, function err(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Using a backbone collection I am trying to fetch JSON from a page. However browsing to this page does give me a JSON, using the collection.fetch does not.
Looking in Firebug I see a:
"GET http://survey/api/list_surveys 200 OK 4ms"
This text however is in red and the Response tab is empty.
The Model:
var SurveyList = Backbone.Model.extend({
defaults: {
"sid": "",
"title": '',
"surveyUrl": ""
},
initialize: function() {
console.log('MODEL AANGESPROKEN');
}
});
The collection:
var Surveys = Backbone.Collection.extend({
model: BGGZ.SurveyList,
url: 'http://survey/api/list_surveys'
});
The JSON:
[{
"sid":"12345",
"surveyls_title":"test 1",
"survey_url":"http://survey/index.php?newtest=Y&sid=12345"
},
{
"sid":"54321",
"surveyls_title":"Test 2",
"survey_url":"http://survey/index.php?newtest=Y&sid=54321"
}]
Does anyone has a solution?
I already tried a parse in the collection, but this didn't help.
Might this has something to do with json with padding?
If so How can I resolve this?
So I found the solution here.
As this is a remote server I am getting the json from I can use JSONP.
In the collection.fetch() Backbone uses jQuery's $.ajax() method to get the data.
So you can place your $.ajax settings in the fetch:
myCollection = new Surveys();
myCollection.fetch({
dataType: "jsonp",
success: function(data) {
console.log(data);
},
error: function() {
console.log('error');
}
});
Now this will not work if your API doesn't expect a JSONP.
JSONP will give a callback parameter to your API. So did your API call first looked like this:
http://survey/api/list_surveys
with JSONP it will now look like this:
http://survey/api/list_surveys?callback=jQuery12654876544
Your API should not return the standard JSON, because jQuery / backbone is expecting the data in a callback function.
if the JSON first looked like this:
{
"sid":"12345",
"surveyls_title":"test 1",
"survey_url":"http://survey/index.php?newtest=Y&sid=12345"
}
you must now add the API to this callback function:
jQuery12654876544({
"sid":"12345",
"surveyls_title":"test 1",
"survey_url":"http://survey/index.php?newtest=Y&sid=12345"
})
Now you're done.