Reload url in javascript with ajax - javascript

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

Related

jQuery onClick pass a variable via GET to URL and load that URL

I know how to pass variables through AJAX calls via onClick to a PHP file and asynchronously loading the results on the initial page.
I now need to analogously pass a variable via onClick to a PHP file but I need to open a new window or redirect the whole page with the passed variable. The URL needs to contain the variable, so that the query/results can be "statically" sent to someone, like 'xyz.php?var=xyz'
I thought I could do something like this
$("#submit").click(function(event) {
var category_id = {};
category_id['linkgen'] = $("#linkgen").val();
$.ajax({
type: "GET",
url: "generatedlink.php",
dataType: "html",
data: category_id,
success: function(response){
window.open('generatedlink.php');
}
});
});
This only opens 'generatedlink.php'. I actually want what is passed via AJAX, i.e. 'generatedlink.php?linkgen=blabla' onClick in a new window/reloaded page! I'd very much appreciate your help.
just try: without ajax call
$("#submit").click(function(event) {
window.open('generatedlink.php?inkgen='+$("#linkgen").val());
});

Before firing AJAX event, manipulate DOM -- CSRF Error

I'm working with Django, trying to make a chained AJAX call -- that is, a call that, when returned, kicks off more AJAX calls. I've been over the various methods of dealing with CSRF tokens and AJAX that the Django documentation provides, to no avail.
I have working code that allows for this chained AJAX call to successfully go through:
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
headers: {'X-CSRFToken':csrftoken},
success: function(data, status){
$('#queue_div').append("<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>");
var div_id = 'queue'+counter;
data['div_id'] = div_id;
var token = $.cookie('csrftoken');
data['csrf'] = token;
$('#'+div_id).html(data['status']);
callbackAJAX(data);
} //end success function
}); //end ajax function
e.preventDefault();
But when you delay the form event from firing the AJAX event right away, either by using "beforeSend" (as below):
var data = {'group_name':'name', 'client':'MrClient'}
var counter = 0
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
headers: {'X-CSRFToken':csrftoken}
beforeSend:function(e){
$('#foo').append('<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>');
} .....
or by adding an event right before the $.ajax call (as below):
frm.submit(function(e){
$('#foo').append('<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>');
$.ajax({
type: frm.attr('method')....
You get a CSRF error.
I was successful in doing very, very simple functions such as the following:
var counter = 0;
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
sendBefore: function(e){
counter++;
}
But that's it. Anything more complicated gets rejected. I'm thoroughly confused as how to make heads or tails of what is actually happening OR what is acceptable to Django. & its CSRF protection.
The HTML you are trying to append is invalid. I believe that's why the form submission is not working. First you are trying to insert an element with ID foo into an element with the same ID ( foo ). Which is invalid HTML since IDs should never be repeated within the page.
Second and main problem is that you are appending <div id=foo></div> which should be <div id="foo"></div>

Recharge source javascript after loading ajax

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 ) { ... })
});

Can ajax call on return add new javascript function to the page?

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.

Return String Outside Ajax Request

I am pretty new to this, so go easy on me:
I am building an image gallery with a main index page which allows users to select different categories of projects, a sub-index page which allows users to select specific projects within their selected category, and then the gallery page for that project.
The code below is for the main index page. I am trying to pass the value of the src attribute of the first image of the first gallery page to the main index page to use as a thumbnail.
I have effectively been able to load the correct URL into the imageLoc variable, but I need to pass it outside of the Ajax request to pass it into my HTML document.
Simply put, I am trying to pass the value of the imageURL variable to the imageLoc variable.
Thanks for your help.
$('.galleryIndex a img').hide().each(function(){
var destination = $(this).parent('a').attr('href');
var imageLoc = $.ajax({
url: destination,
success: function(data){
var pageLoc = $(data).find('.galleryList a:first').attr('href');
$.ajax({
url: pageLoc,
success: function(data){
var imageURL = $(data).find('.galleryBox img:first').attr('src');
return imageURL
}
});
}
});
alert(imageLoc);
});
This will cause troubles do to the way the callback function is handled. It's a closure block that is called after the request has returned, so it runs apart from your main code in the function. If you want to alert the imageURL variable, alert it inside the callback function, or call another function to handle it. Since it is a callback function for an asynchronous server request, the part that alerts "imageLoc" will have run long before you ever get your async request back.
Edit: The only way to achieve what you're trying to do is to not make the ajax request asynchronously. If you set async:false, then you can call on the "responseText" property like this:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
But be warned...this will halt browser operation while the request is pending. It's usually best to block user interaction by other means if you don't want them to screw with the page while something is loading.
I was able to get what I wanted as follows:
$('.galleryIndex a img[id!="fp"]').hide().each(function(){
var destination = $(this).parent('a').attr('href');
$.ajax({
url: destination,
context: $(this),
success: function(data){
var pageLoc = $(data).find('.galleryList a:first').attr('href');
$.ajax({
url: pageLoc,
context: $(this),
success: function(data){
var imageURL = $(data).find('.galleryBox img:first').attr('src'); //returns the src for the thumbnails
$(this).attr('src', imageURL);
$(this).load(function(){
$(this).show();
});
}
});
}
});
});

Categories

Resources