This is my website ( work in progress ) -> Link
I use this my code, written on the basis of another creator. -> Link
Ajax Code
$.ajax({
type: 'GET',
url: href,
cache: true,
}).done(function (data) {
......
// Run scripts
$data.filter('script').each(function(){
var scriptTag = document.createElement('script');
scriptTag.text = $(this).html();
document.body.appendChild(scriptTag);
});
});
The code allows you to load the page via ajax, then without refreshing the page. The problem arises when the page has to load javascript, they are not considered and therefore the script in the loaded page does not work.
If I can (if it is not edited) I'll link the site where I'm working and try to click in the first written EdoNetowork, then a link to an account in the topic and you'll see that the code is ignored.
How can I fix?
I think the problem is in updating the javascript page to load. But how can I recharge sources are loaded via javascript src?
You are using $data.filter('script') which is not returning anything, instead use find and in your function you are using $(this).html() but as script has no html inside it so it will not give you anything, instead access attr('src') and append it to your script tag
// your function
$data.filter('script').each(function(){
var scriptTag = document.createElement('script');
scriptTag.text = $(this).html(); // use $(this).attr('src')
// scriptTag.attr('src', $(this).attr('src')) // use it like this
document.body.appendChild(scriptTag);
});
you can also load javascript in your done callback in ajax call usinf jquery getScript()
$.ajax({
.. }).done(function () {
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) { ... })
});
Related
I'm trying to refresh an affiliate URL which is inside a piece of JavaScript with AJAX, but I can't get it to work.
Here's the code:
<script type="text/javascript">
(function() {
var mdWidgetUrl = "https://herecomestheurl";
var s = document.createElement("script"),
s1 = document.getElementsByTagName("script")[0];
s.type = "text/javascript";
s.async = true;
s.src = mdWidgetUrl;
s1.parentNode.insertBefore(s, s1);
})();
function fetchdata(){
$.ajax({
url: 's.src',
type: 'post',
success: function(data){
// Perform operation on return value
alert(data);
},
complete:function(data){
setTimeout(fetchdata,10000);
}
});
}
$(document).ready(function(){
setTimeout(fetchdata,10000);
});
</script>
What I'm trying to do is to AJAX reload the URL, which is known as "mdWidgetUrl", every 10 seconds without refreshing the whole page. This code doesn't work, because I don't know how to tag the s.src within the AJAX function.
Let's have a look to the different settings of your AJAX call:
url:
When you try:
url: 's.src',
you are not passing the content of the src property of the s object; you are literally passing the string "s.src". But even if you do:
url: s.src,
it won't work because s is out of scope. s was declared inside an IIFE ( (function() {... ) and it lives just inside it. You can not access it from outside.
Instead, after you create your s script, you can give it an id. Like this:
var s = document.createElement("script");
s.id = "mdWidgetScript";
Then, you can easily retrieve the value of the src attribute from the ajax call:
$.ajax({
url: $("#mdWidgetScript").attr('src'),
Note that using an id is not mandatory. You could find the script like you found s1, selecting the first element with a <script> tag:
url: document.getElementsByTagName("script")[0].getAttribute("src");
// or with jQuery
url: $("script:eq(0)").attr('src');
I just find using an id a cleaner and more bulletproof way.
type:
It is an alias for method. You are retrieving data from the server, not sending to. Switch POST to GET (or leave this setting out, since GET is the default). Read this question about the differences.
dataType:
You should set the dataType accordingly (check this question). If the URL points to a script, use dataType: "script",. Actually, you could use $.getScript() which is a shorthand method for this kind of AJAX call.
If after properly tuning your settings you still have troubles:
Check for errors in the console.
Ensure the data being send is well-formed
Read this other questions:
Why does jQuery insist my plain text is not “well-formed”?
jQuery.ajax success callback function not executed
I'm currently working on a website which should heavily rely on ajax. But I'm facing a problem which I cannot find a solution to online.
I'll now shamelessly post my (stripped) function to completely fetch a page.
function loadTemplate(name, replaceWholePage = true){
$.when( $.ajax({ url: "./templates/{0}/{0}.html".format(name), error: function() { console.error( "Could not load HTML file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.css".format(name), error: function() { console.error("Could not load CSS file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.js".format(name), error: function() { console.error("Could not load JS file of template '{0}'!".format(name)); }}) )
.then(function(html, css, js) {
var _css = "\n<style>\n" + css[0] + "\n</style>";
var _js = "\n<script>\n" + js[0] + "\n</script>";
if(replaceWholePage) {
$("#content").empty();
}
$("#content").append(html[0]);
$("#content").append(_css);
//$("#content").append(_js);
});
}
You see the line where it appends the js file is commented. But somehow the site still gets the js. When I comment that line out, my js code isn't actually twice in the document, but still gets called twice.
As Varinder stated, jQuery automatically recognised the fetched file as javascript and executed it. Setting the dataType to "text" in the call fixed it!
Thanks
I am trying to build a search page where the user inputs text into a search box and the page is generated based on the search. I am having timing issues because the blank search page is loading after the JS tries to edit the values on the page.
$.ajax({
type: 'GET',
url: '/index.php/content/generate_search',
data: {
search: input.val()
},
beforeSend: function() {
window.location.href = '/index.php/content/search';
},
success: function() {
$('.hero h1').text(input.val());
}
});
To check that the DOM is completely loaded, many steps have to be done taking all the browsers into consideration. (I cannot find the implementation in the jQuery source, but I will come back with a link).
The easiest and probably best way of doing it, since you're already using jQuery is by:
$( function() {
// your code here
} );
which is a shorthand for
$( document ).ready( function() {
// your code here
} );
EDIT
Ok, so as I promised, I came back with the implementation of document.ready. You can find it here, on GitHub. Here is a permanent link to the current version of the file.
Try this:
$(document).ready(function(){
//Your code
});
onload is used for executing code on pageload
window.onload = function() {
// your code
};
This code:
beforeSend: function() {
window.location.href = "/index.php/content/search";
},
… is causing the browser to leave the page and load a new one before it sends the Ajax request.
Consequently, the Ajax request gets cancelled. If it didn't, then there would be no JavaScript waiting to receive the response.
If you want to visit /index.php/content/search and then initiate an Ajax request, then the JavaScript to initiate the Ajax request has to be on /index.php/content/search. A page you've just left can't run JavaScript on the next page.
I have a page view that makes an ajax call and updates the contents of the page with renderPartial.
So page.php -> _pagePartial.php (ajax update)
in page.php I want to include the javascript files once, then have the DOM modifications apply after the ajax rendering happens. It doesn't make sense to have this JS file load on every AJAX refresh.
For example in page.php
$baseUrl = Yii::app()->baseUrl;
$basePath = Yii::app()->basePath;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl . '/js/jquery.ui.js'); // load one time!
then in pagePartial.php
// every ajax partial load
$('#sortable-list-left').sortable({
connectWith:'.productEntryCol',
placeholder: 'ui-state-highlight',
update: function(event, ui) {
var sortOrderLeft = getSortOrder('sortable-list-left');
var sortOrderRight = getSortOrder('sortable-list-right');
var projectId = '" . $project_id . "';
$.ajax({
data: { left: sortOrderLeft, right : sortOrderRight, id : projectId},
url: '/project/ajaxUpdateOrder',
type: 'POST',
success: function(response){
// process JSON response
var obj = jQuery.parseJSON(response);
}
});
}
});
The problem is after _pagePartial loads via AJAX, it can't use the .sortable() method.
What is the proper way to handle this ?
Thanks
The way I handle this is on the main view on the $.load or $.ajax or whatever it is, add your code on the success function.
So for example:
$.get('_pagePartial.php', null, function(html) {
$('#result').html(html);
$('#sortable-list-left').sortable({
//all your sortable code
});
});
Another option is to add your javascript on your ajax loaded page ('_pagePartial.php') into a function like so:
function firejs() {
$('#sortable-list-left').sortable({
//all your sortable code
});
}
Then on your successful ajax call on your main view ('page.php') simply add this:
$.get('_pagePartial.php', null, function(html) {
$('#result').html(html);
firejs();
});
You can bind to an object until it is added to the DOM and it isn't added to the DOM until the ajax call has finished successfully and the result is added to the DOM.
Also just an FYI yii has jqueryui built in you can simply say:
Yii::app()->clientScript->registerCoreScript('jquery.ui');
Yii::app()->clientScript->registerCoreScript('jquery');
For people like me who has the same issue, even with:
Yii::app()->clientscript->scriptMap['jquery.js'] = false;
in the renderPartial and still not work. I've found another solution, way more effective I think. The easiest solution is to set the 4th parameter of renderPartial.
RenderPartial-detail
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
It is about processOutput.If you put it to true, then Jquery will be loaded in your render Partial.
Hope this will help someone...
I have a jQuery ajax call that returns html of a table. Now I need to let user to do some javascript action on the table.
Can the return ajax response contain the javascript code or do I have to load the javascript code in the page on the first load of the page?
The user has the option of triggering the 'new' javascript. It doesn't have to triggered on ajax call.
To answer the actual question, the return response can contain the script. Simplest is to place it after the html, as the ready event has already fired in page it is being loaded into
You can use the success (or other event) callbacks provided with jQuery .ajax() to perform this JS action. Something like this:
$.ajax({
success: function(){
// Perform JS action
}
}
The jQuery API lists all such event callbacks available for AJAX calls. Check this for more info.
The returned ajax response can contain javascript code as a string. Then you can eval(response).
If you want to request a script with ajax that will be run when retrieved, then you can use jQuery's getScript() method to retrieve it and then execute it.
Per the jQuery doc, getScript() is a shorthand for:
$.ajax({
url: url,
dataType: "script",
success: success
});
Which shows that jQuery's ajax command will handle a returned script for you automatically if you set the data type appropriately.
You can make your request a variable and extend upon it after the set up.
// Make the request to the server
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "PageOrControllerOrWebApi/MethodName",
type: "POST",
data: { id : dataID },
dataType: "json"
});
// When the request is done process
// what you need done
request.done(function(msg) {
alert('You got this ' + msg);
});
// If the request failed you can
// see what the problem was and
// handle the situation accordingly
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});
you can do it using success callback i think this can be a way please try
$.ajax({
.....,
.....,
success:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#tableID").append( script );
});
i hope it should help.