AJAX to request another javascript or function from the server - javascript

As we know that AJAX is used to request a web-part in HTML format from the server. Is it possible to request a script containing functions using AJAX?

Here's an example how to use eval() to accomplish what you need:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
eval(xmlhttp.responseText);
// you can use whatever functionw as returned from the server from this line on :)
}
}
xmlhttp.open("GET","your-server-page-url",true);
xmlhttp.send();

Yes you can load a javascript via ajax
http://api.jquery.com/jQuery.getScript/
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
Also you could try something like this as mentioned in(how to run javascript in html loaded via ajax):
require("extra.js", function () {
functionDefinedInExtraJS();
});
//Sample require function:
function require(file, callback) {
var script = document.getElementsByTagName('script')[0],
newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
callback();
}
};
// others
newjs.onload = function () {
callback();
};
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
One other way would be to use eval() function and convert a string reply into working javascript code.

Is it possible to request a script containing functions using AJAX?
Yes, it is possible. And those functions could be executed on the client. For example with jQuery you even have a function that allows you to perform such request: $.getScript.

Related

multiple calls to jQuery.globalEval()

I have the following generic Ajax response writer which I recently added some logic to, in order to dynamically parse the results for script objects, and run them when I find them using jQuery.globalEval().
Here is the code:
//Generic Results Writter method for Ajax Calls
function writeAjaxResponse(targetId, response) {
document.getElementById(targetId).innerHTML = response;
try {
var dom = $j(response);
dom.find('script').each( function(){
$j.globalEval(this.text || this.textContent || this.innerHTML || '');
});
} catch (e) {
console.error("Error parsing for script reloads: "+e);
}
}
This solution works very nicely the first time its called. However writeAjaxResponse(targetId, response); is called each time a user loads some dynamic Ajax content. And unfortunately after the first time, the scripts are no longer loaded. To be clear, after the server side generated page is loaded, there are numerous links on the page which the users may click, which invoke this handler for the Ajax response.
No error occurs, and no console.error() is written.. The Ajax data loads as normal, its just that the scripts in the response are no longer loaded.
In debugging, $j.globalEval is still getting called and this.text still has the script content in it, and the data looks correct, but still no joy.
Any light someone could shed on this would be very much appreciated!
Adding main ajax call for GET for reference:
function doAjaxGet(targetId, getUrl, handler) {`
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
handler(targetId, xmlhttp.response);
}
catch (err) {
alert("Failed calling handler, detail: " + err + " Got responseText: " + xmlhttp.responseText);
}
}
}
xmlhttp.open("GET", getUrl, true);
xmlhttp.send(null);
}

Running jQuery scripts on DOM elements loaded with AJAX

I understand that jQuery will not run when the DOM content is being loaded via AJAX. But I'm confused as to the reason why. My understanding was that the DOM elements didn't exist at the time the jQuery was initiated therefore it won't find the correct IDs or classes.
But I have a situation where the jQuery is only called AFTER all the content has been loaded via AJAX. yet it still does not work.
Here is my code. I am trying to get the function decorateGains() to run after AJAX completes.
loadData('7-days'); // Runs the default AJAX for 7 days
function loadData(type){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById("home-table").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","actions/get-data-"+type+".php",true);
xmlhttp.send();
decorateGains();
}
You can see that I am including a call to the function decorateGains() right at the end of the loadData() function.
The decorateGains() function does run, as I can see my console message. However it does not do the task that it should.
function decorateGains() {
console.log('here');
$(".gains").each(function() {
var num = +($(this).text());
if (num > 0) {
console.log('here');
$(this).addClass("positive");
}
if (num < 0) {
console.log('here');
$(this).addClass("negative");
}
});
}
(The script searches for all elements with a class of .gains and adds a new class of positive or negative depending on the content of the element. Essentially it decorates the .gains element to be red or green depending on whether the number is negative or positive).
This is because the AJAX call is asynchronous. The request has not been completed (and therefore the new content has not been appended to the DOM) when you call your decorateGains() function. You need to place the call to the function inside the onreadystatechange handler, after setting the innerHTML:
loadData('7-days'); // Runs the default AJAX for 7 days
function loadData(type) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("home-table").innerHTML = xmlhttp.responseText;
decorateGains(); // <-- move this in here
}
}
xmlhttp.open("GET", "actions/get-data-" + type + ".php", true);
xmlhttp.send();
}

Called a jquery after javascript ajax call

I have this javascript code which returns an ajax request
function showUser(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("lister").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","popup.php?qq="+str,true);
xmlhttp.send();
}
I tried to execute a jquery that can't be done , unless ajax request returns , yet it's not working
$('#scrollbar2').tinyscrollbar();
So how should I execute that last jquery after the ajax load ?
Put it inside the callback after you set lister’s innerHTML:
document.getElementById("lister").innerHTML = xmlhttp.responseText;
$('#scrollbar2').tinyscrollbar();
But since you have jQuery, why not use its Ajax functionality?
$.ajax({
url: "popup.php",
data: { qq: str },
dataType: "text",
success: function(response) {
$('#lister').html(response);
$('#scrollbar2').tinyscrollbar();
}
});
Add the jQuery call inside your onreadystatechange callback. The reason for this is that ajax completes asynchronously (as per its name). Think of it like this:
onAjaxComplete = function () {
// this will run second
}
// this will run first
All work that depends on the result of the ajax call must be in the callback.
Additionally, since you are using jQuery anyway you might as well use their ajax API which is a lot simpler.
function showUser(str) {
$.get("popup.php", "qq=" + str).done(function (responseText) {
$("#lister").html(responseText);
$("#scrollbar2").tinyscrollbar();
});
}

Ajax Timed Event Redirect

Im trying to setup a redirect for a chat script. If the chat goes unanswered after x amount of time the page will redirect.
I posted a question here yesterday regarding the same thing, but at the time knowing little in regards to JS I was trying to mix php with js. I have changed tactics.
Here is what I got thus far:
function opCheck()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
opCheck();
// alert('working2');
}
}
opjoined = "newchattimer.php";
xmlhttp.open("GET",opjoined,true);
xmlhttp.send(null);
}
function opResult()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//alert('state = 4');
var op = xmlhttp.responseText;
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET",ajaxurl,true);
xmlhttp.send(null);
}
setTimeout(function() {
opCheck();
opResult();
//alert(op);
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
It creates the text file properly but ultimately no redirect. I used the chrome deveolpers tool and no errors. I also tried to alert(op); to see if the result is being grabbed, but I get no alert.
What is wrong with this code?
Thanks.
If you had taken the time to indent your code, you'd see that var op is declared inside the scope of the onreadystatechange function, which is both out of scope and asynchronous.
function opResult() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var op = xmlhttp.responseText; //declared here
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET", ajaxurl, true);
xmlhttp.send(null);
}
setTimeout(function () {
opCheck();
opResult();
// op is out of scope here
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
Since timeouts aren't generally the way to handle async functions, and doing ajax request when all you intend to do when it finishes is to redirect anyway is'nt really neccessary, you could just do a regular form submit, which will redirect all by itself, or move the redirecting inside the right scope!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if(xmlhttp.responseText == 'n') window.location.href = 'chatnoop.php';
}
}
You may find what you want here http://www.tizag.com/javascriptT/javascriptredirect.php but basically i don't think that window.location.replace("chatnoop.php"); is correct. You should consider using JQuery to manage all the Ajax stuff in addition, but it should work like you've done anyway

how can i do jquery's $.get in pure javascript? (without wanting to return anything)

I want the mobile version of my site to be as snappy as possible, however i still want some basic analytics.
I want to ping a php file (hit counter) after the mobile page has loaded to count the amount of hits from javascript enabled browsers.
Jquery's a bit overkill for 1 ajax function so i'm keen to learn how to do the following in pure javascript:
<script type="text/javascript">
Window.onload(function(){
$.get('mvc/assets/ajax/analytics/event_increment.php?id='+id');
})
</script>
Create a utility function that will return to you a browser-specific Ajax object:
function ajax(url, method, callback, params = null) {
var obj;
try {
obj = new XMLHttpRequest();
} catch(e){
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function() {
if(obj.readyState == 4) {
callback(obj);
}
}
obj.open(method, url, true);
obj.send(params);
return obj;
}
You could then call that function like this:
var ajax = ajax('someurl', 'get', function(obj) { alert(obj.responseText); })
Just specify your file as the src attribute for the script tag.
Something simplistic:
<div id="hidden"></div>
<script type="text/javascript">
window.onload = function(){
var div = document.getElementById("hidden");
div.innerHTML = "<img src='tracking.php' />";
};
</script>
#Mike is suggesting a great method. If you would like to get into AJAX, though, it's not that difficult.
Code c/o bobince
var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();
// FOR <IE8 Compatibility do this first:
if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
window.XMLHttpRequest= function() {
return new ActiveXObject('MSXML2.XMLHttp');
};
}
replace x.html with your php file
While it is possible to create an image tag with that url as the src if you want to do it via AJAX as jQuery does there you could do this:
<script type="text/javascript">
function report(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",'mvc/assets/ajax/analytics/event_increment.php?id='+id',true);
}
window.onload = report;
</script>
You can use an img tag and put that in the src, and have your script return a transparent image.
Or as someone else pointed out, have it be the src of a script tag.
EDIT
If you don't want it to load if a bot accesses the page, you could use an img tag still
<img src="transparent.gif" width="1" height="1" />
Then, use javascript to change the src of the image to your php script. Most bots won't execute the javascript and therefor will never access your php script.
You may want to obfuscate the javascript a little though, so they don't see a url in it and try and access it.
<script type="text/javascript">
Window.onload(function(){
var id = "", xmlhttp = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET","mvc/assets/ajax/analytics/event_increment.php?id=" + id,true);
xmlhttp.send();
}
})
</script>
there existed image preloaders in the early days of webpages, when internet connections were still slow, which created image objects to be used for rollover effects. this should still work and load the image:
<script type="text/javascript">
var img = new Image('http://url.to/your/image/or/script');
</script>
As 2019 you can use ES6 fetch a modern replacement for XMLHttpRequest.
const options = {
method: "POST",
data: {
title: "foo",
body: "bar",
userId: 1
},
credentials: "include",
headers: {}
};
fetch("https://jsonplaceholder.typicode.com/posts", options)
.then(response => {
return response.json();
})
.then(jsonObject => {
console.log(jsonObject);
document.write(`ID ${jsonObject.id} was created!`);
})
.catch(error => {
document.write(error);
});

Categories

Resources