Working with Ajax... I cannot seem to figure out what is wrong here. The error occurs on the code: objUserID.innerHTML = username;. It thinks the variable username is null. username does have data in it because the following code confirms it: console.log("user: ["+username+"]"); Can anyone figure this out?
function actionBid(bidID,bidA,bidAction){
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject)
{
// ==== GET BID ====
if (bidAction == "getbid"){
var objUserID = document.getElementById("curBidUser"+bidID);
var res = XMLHttpRequestObject.responseText;
var username = res.substring(0,res.indexOf(','));
console.log("user: ["+username+"]");
objUserID.innerHTML = username;
}
}
}
It thinks the variable username is null
False. It is telling you that it cannot access the property innerHTML of null. In other words, that objUserID is null and that you cannot access a property of it.
Put another way, your element does not exist.
If you are having this problem, it might be because you have placed your script tag at the top of the body tag before everything else. You want to place your script tag at the bottom of the body tag.
Actually it was an loading issue check with the follow code.
setTimeout(function(){
xYzFunction();
}, 3000 )
It means that the element or the object is not found. It doesn't exist.
Here is a fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/cF6Bh/
You can see, that the code works. But the element's not present for the JavaScript to work on.
Make sure that the element is present. Either you need to make sure the characters are OK or something like that.
document.getElementById("objectId").innerHTML = "Text";
So the remedy to this would be, to change the ID param that you're passing onto the method.
actually this error can be also caused by calling like this document.getElementById("#content-content").innerHTML=output;
instead of like this
document.getElementById("content-content").innerHTML=output;
Ok, I know this has been asked before (as I have viewed it myself) and it seems to work for everyone else except for me. Im terribly new to javascript, as I try not to use it cause its a nightmare to debug. But, here is my issue. I have a script that im working on for ajax to add an image to a gallery. The image is just an id that references another table in the database, and same for the gallery. Just two id's. Anyways, when I click on a link, I want it to run this script to add it to the database. But, its not working, and of course, javascript is horrible at letting you know where it fails. Here is the code for the script.
function addToGallery(img)
{
var e = document.getElementById("galleries2");
var gal = e.options(e.selectedIndex).value;
window.alert("Gallery Id: "+gal+" Image Id: "+img);
if (img=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","addtogallery.php?img="+img+"gal="+gal,true);
xmlhttp.send();
}
Ok, so the above doesnt work. I added the alert message to try to troubleshoot as much as I could. If I put the alert box above the var's, and only ask it to reference the img variable, it works. Now, if I put it below and try to do what I did there, it just stops. No message box, no ajax, nothing. So, im betting it has something to do with the
var gal = e.options(e.selectedIndex).value;
I have also tried it with the [] instead of the () and nothing there either...
Any help would be appreciated.
UPDATE
Ok, so I have got past the problem with the select, now im trying to pass values with the xhtmlrequest.open method. I can pass 1 get value it seems, but not two. Here is the line of code in question
xmlhttp.open("GET","addtogallery.php?image="+img+"&gid="+gal,true);
Now, I know that img and gal are set because of an alert box that pops whenever this script is run to tell me that they are set. But when it gets to the php page its only putting out the img variable, and the gal variable is still not set. Anyone have this issue before?
You definitely need square brackets, but also try changing your variable "e" to something else like "el". The function responds to a click as I understand, so it might be reserved for an event.
Try:
var galleries = document.getElementById("galleries2");
var gal = galleries.options[galleries.selectedIndex].value;
I think what you want to do is:
var gal = e.options[e.selectedIndex].value;
Hope this helps.
You need square brackets instead of parens.
var gal = e.options[e.selectedIndex].value;
Your JavaScript environment should be giving you a nice TypeError saying something like "HTMLOptionsCollection is not a function"
I am trying to write some javascript which asks a user, when they leave the page, if they want to fill out a survey (however annoying this may be!). I thought my solution was found by an answer on this site. This is the code I currently have that does not seem to be working:
<script language="javascript">
function comfirmsurv() {
var ConfirmStatus = confirm("We would love to receive your feedback on your experience of this page. Would you like to complete our short survey?");
if (ConfirmStatus == true) {
window.open("#");
}
else
{window.close();}
}
}
window.onUnload=confirmsurv()
</script>
<body>
Test
</body>
Any help is greatly appreciated.
You are assigning the result of calling the function, not the function itself:
window.onunload = confirmsurv; // Note no ()
A few other issues:
Javascript is case sensitive, the property you are after is "onunload", not "onUnload".
The name of the function is "comfirmsurv" but you are assigning "confirmsurv"
window.close() : you can only close windows you open, not others.
There is an extra }.
The language attribute for script elements has been deprecated for over a decade, the type attribute is required, use type="text/javascript"
The unload property is incorrectly stated as onUnload instead of onunload. Also, the code have too many errors here and there.
The browser's console log provides a log that you can use to find the cause of error.
Here's the fixed script.
<SCRIPT>
function confirmsurv() {
var ConfirmStatus = confirm("We would love to receive your feedback on your experience of this page. Would you like to complete our short survey?");
if (ConfirmStatus == true) {
window.open("#");
} else {
window.close();
}
}
window.onunload=confirmsurv;
</SCRIPT>
I'm new to this website and not sure how it works and whether anybody would reply to my question or not, but worth a try, so will post my question here! :)
Basically I've a HTML page which contains some within different parts of the page and here is my code:
<html>
<head>
<title>Welcome to My 1st JavaScript Page</title>
</head>
<body>
<script type="text/javascript">
//
var parameter = document.location.search.replace("?", "").replace("=", "");
// IF NO PARAMETER
if (!document.location.search || !parameter) {
document.write("No parameter is defined. Please either set ?pictures, ?videos or ?music");
// IF PARAMETER
} else {
// IF GAMES
if (parameter == "pictures") {
// FOR EXAMPLE INCLUDE THE PICTURES.HTML
// IF VIDEOS
} else if (parameter == "videos") {
// FOR EXAMPLE INCLUDE THE VIDEOS.HTML
// IF MUSIC
} else if (parameter == "music") {
// FOR EXAMPLE INCLUDE THE MUSIC.HTML
}
}
</script>
</body>
</html>
This page would load different things according to the URL parameter that I've set, so when different URL parameters is called, I want to load different external HTML pages within the same page, and don't want to use iframe and such!
Is this possible or not? Please have a look at my code above!
In PHP we use:
<?php
include ("./includes/music.html");
?>
But I don't know how to do this in JavaScript! Could somebody please help me with this!
Thanks :)
You'll need Ajax, something like this:
function include(page) {
var rq = null;
if(window.XMLHttpRequest) {
rq = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try { rq = new ActiveXObject("Msxml2.XMLHTTP"); } catch(o) { try { rq = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }
}
if(rq) {
try {
rq.open("GET", page, false);
rq.send(null);
document.body.innerHTML = rq.responseText;
} catch(ex) {
// Provide a fallback here, probably a redirect
}
} else {
// Provide a fallback here, probably a redirect
}
}
Try using a templating engine to load templates with data.
There are many templating engines like EJS, mustache, jQuery-tmpl.
The general idea is to request some a template file from the server based on your URL and use the templating engine to render it. You can also request JSON data to populate your template with.
If you're okay with learning a new library, the simplest way is to use jQuery and its load method.
There are some other cross-platform ways of using XmlHttpRequest objects to get an HTML page, but jQuery's is by far the simplest.
I have a system where I send an Ajax command, which returns a script block with a function in it. After this data is correctly inserted in the DIV, I want to be able to call this function to perform the required actions.
Is this possible?
I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".
OK, if you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:
1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a <script> block within an existing <div> element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must eval() your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.
Even if quite dummy, this code explains the idea:
<html>
<body>
<div id="div1">
</div>
<div id="div2">
<input type="button" value="Go!" onclick="go()" />
</div>
<script type="text/javascript">
var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
var e = document.getElementById('div1');
e.innerHTML = newsc;
eval(document.getElementById('sc1').innerHTML);
</script>
</body>
</html>
I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)
Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.
Finally, if I misunderstood your question, and you're talking about contextual invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach described by krosenvold, as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations.
Note: eval() can be easily misused, let say that the request is intercepted by a third party and sends you not trusted code. Then with eval() you would be running this not trusted code. Refer here for the dangers of eval().
Inside the returned HTML/Ajax/JavaScript file, you will have a JavaScript tag. Give it an ID, like runscript. It's uncommon to add an id to these tags, but it's needed to reference it specifically.
<script type="text/javascript" id="runscript">
alert("running from main");
</script>
In the main window, then call the eval function by evaluating only that NEW block of JavaScript code (in this case, it's called runscript):
eval(document.getElementById("runscript").innerHTML);
And it works, at least in Internet Explorer 9 and Google Chrome.
It is fully possible, and there are even some fairly legitimate use cases for this. Using the Prototype framework it's done as follows.
new Ajax.Updater('items', '/items.url', {
parameters: { evalJS: true}
});
See documentation of the Ajax updater. The options are in the common options set. As usual, there are some caveats about where "this" points to, so read the fine print.
The JavaScript code will be evaluated upon load. If the content contains function myFunc(),
you could really just say myFunc() afterwards. Maybe as follows.
if (window["myFunc"])
myFunc()
This checks if the function exists. Maybe someone has a better cross-browser way of doing that which works in Internet Explorer 6.
That seems a rather weird design for your code - it generally makes more sense to have your functions called directly from a .js file, and then only retrieve data with the Ajax call.
However, I believe it should work by calling eval() on the response - provided it is syntactically correct JavaScript code.
With jQuery I would do it using getScript
Just remember if you create a function the way below through ajax...
function foo()
{
console.log('foo');
}
...and execute it via eval, you'll probably get a context problem.
Take this as your callback function:
function callback(result)
{
responseDiv = document.getElementById('responseDiv');
responseDiv.innerHTML = result;
scripts = responseDiv.getElementsByTagName('script');
eval(scripts[0]);
}
You'll be declaring a function inside a function, so this new function will be accessible only on that scope.
If you want to create a global function in this scenario, you could declare it this way:
window.foo = function ()
{
console.log('foo');
};
But, I also think you shouldn't be doing this...
Sorry for any mistake here...
I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.
This is the example code provided by the jQuery API documentation:
function test()
{
jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true
This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.
A checklist for doing such a thing:
the returned Ajax response is eval(ed).
the functions are declared in form func_name = function() {...}
Better still, use frameworks which handles it like in Prototype. You have Ajax.updater.
PHP side code
Name of file class.sendCode.php
<?php
class sendCode{
function __construct($dateini,$datefin) {
echo $this->printCode($dateini,$datefin);
}
function printCode($dateini,$datefin){
$code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute,
//only javascript or Jquery code , dont incluce <script> tags
return $code ;
}
}
new sendCode($_POST['dateini'],$_POST['datefin']);
Now from your Html page you must trigger the ajax function to send the data.
.... <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>
Now at our local script.js we will define the ajax
function triggerAjax() {
$.ajax({
type: "POST",
url: 'class.sendCode.php',
dataType: "HTML",
data : {
dateini : $('#startdate').val(),
datefin : $('#enddate').val()},
success: function(data){
$.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class. That is our javascript code to be executed
}
});
}
This code work as well, instead eval the html i'm going to append the script to the head
function RunJS(objID) {
//alert(http_request.responseText);
var c="";
var ob = document.getElementById(objID).getElementsByTagName("script");
for (var i=0; i < ob.length - 1; i++) {
if (ob[i + 1].text != null)
c+=ob[i + 1].text;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.text = c;
document.getElementsByTagName("head")[0].appendChild(s);
}
My usual ajax calling function:
function xhr_new(targetId, url, busyMsg, finishCB)
{
var xhr;
if(busyMsg !== undefined)
document.getElementById(targetId).innerHTML = busyMsg;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch(e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch(e2)
{
try { xhr = new XMLHttpRequest(); }
catch(e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
var target = document.getElementById(targetId)
target.innerHTML = xhr.responseText;
var scriptElements = target.getElementsByTagName("script");
var i;
for(i = 0; i < scriptElements.length; i++)
eval(scriptElements[i].innerHTML);
if(finishCB !== undefined)
finishCB();
}
else
document.getElementById(targetId).innerHTML = 'Error code: ' + xhr.status;
}
};
xhr.open('GET', url, true);
xhr.send(null);
// return xhr;
}
Some explanation:
targetId is an (usually div) element ID where the ajax call result text will goes.
url is the ajax call url.
busyMsg will be the temporary text in the target element.
finishCB will be called when the ajax transaction finished successfully.
As you see in the xhr.onreadystatechange = function() {...} all of the <script> elements will be collected from the ajax response and will be run one by one. It appears to work very well for me. The two last parameter is optional.
I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.
This does not sound like a good idea.
You should abstract out the function to include in the rest of your JavaScript code from the data returned by Ajax methods.
For what it's worth, though, (and I don't understand why you're inserting a script block in a div?) even inline script methods written in a script block will be accessible.
I tried all the techniques offered here but finally the way that worked was simply to put the JavaScript function inside the page / file where it is supposed to happen and call it from the response part of the Ajax simply as a function:
...
}, function(data) {
afterOrder();
}
This Worked on the first attempt, so I decided to share.
I solved this today by putting my JavaScript at the bottom of the response HTML.
I had an AJAX request that returned a bunch of HTML that was displayed in an overlay. I needed to attach a click event to a button in the returned response HTML/overlay. On a normal page, I would wrap my JavaScript in a "window.onload" or "$(document).ready" so that it would attach the event handler to the DOM object after the DOM for the new overlay had been rendered, but because this was an AJAX response and not a new page load, that event never happened, the browser never executed my JavaScript, my event handler never got attached to the DOM element, and my new piece of functionality didn't work. Again, I solved my "executing JavaScript in an AJAX response problem" by not using "$(document).ready" in the head of the document, but by placing my JavaScript at the end of the document and having it run after the HTML/DOM had been rendered.
If your AJAX script takes more than a couple milliseconds to run, eval() will always run ahead and evaluate the empty response element before AJAX populates it with the script you're trying to execute.
Rather than mucking around with timing and eval(), here is a pretty simple workaround that should work in most situations and is probably a bit more secure. Using eval() is generally frowned upon because the characters being evaluated as code can easily be manipulated client-side.
Concept
Include your javascript function in the main page. Write it so that any dynamic elements can be accepted as arguments.
In your AJAX file, call the function by using an official DOM event (onclick, onfocus, onblur, onload, etc.) Depending on what other elements are in your response, you can get pretty clever about making it feel seamless. Pass your dynamic elements in as arguments.
When your response element gets populated and the event takes place, the function runs.
Example
In this example, I want to attach a dynamic autocomplete list from the jquery-ui library to an AJAX element AFTER the element has been added to the page. Easy, right?
start.php
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<!-- these libraries are for the autocomplete() function -->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-lightness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
<!--
// this is the ajax call
function editDemoText(ElementID,initialValue) {
try { ajaxRequest = new XMLHttpRequest();
} catch (e) {
try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}}}
ajaxRequest.onreadystatechange = function() {
if ( ajaxRequest.readyState == 4 ) {
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?ElementID="+ElementID+"&initialValue="+initialValue;
ajaxRequest.open("GET", "ajaxRequest.php"+queryString, true);
ajaxRequest.send(null);
}
// this is the function we wanted to call in AJAX,
// but we put it here instead with an argument (ElementID)
function AttachAutocomplete(ElementID) {
// this list is static, but can easily be pulled in from
// a database using PHP. That would look something like this:
/*
* $list = "";
* $r = mysqli_query($mysqli_link, "SELECT element FROM table");
* while ( $row = mysqli_fetch_array($r) ) {
* $list .= "\".str_replace('"','\"',$row['element'])."\",";
* }
* $list = rtrim($list,",");
*/
var availableIDs = ["Demo1","Demo2","Demo3","Demo4"];
$("#"+ElementID).autocomplete({ source: availableIDs });
}
//-->
</script>
</head>
<body>
<!-- this is where the AJAX response sneaks in after DOM is loaded -->
<!-- we're using an onclick event to trigger the initial AJAX call -->
<div id="responseDiv">I am editable!</div>
</body>
</html>
ajaxRequest.php
<?php
// for this application, onfocus works well because we wouldn't really
// need the autocomplete populated until the user begins typing
echo "<input type=\"text\" id=\"".$_GET['ElementID']."\" onfocus=\"AttachAutocomplete('".$_GET['ElementID']."');\" value=\"".$_GET['initialValue']."\" />\n";
?>
I needed to get something to do this, I find that this has worked for a long time for me, just posting this here as one of many solutions, I like to have solutions without jQuery and the following function may help you, you can pass the full html with script tags in and it will parse and execute.
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
if (scripts[i] != '')
{
try { //IE
execScript(scripts[i]);
}
catch(ex) //Firefox
{
window.eval(scripts[i]);
}
}
}
catch(e) {
// do what you want here when a script fails
if (e instanceof SyntaxError) console.log (e.message+' - '+scripts[i]);
}
}
// Return the cleaned source
return source;
}
Federico Zancan's answer is correct but you don't have to give your script an ID and eval all your script. Just eval your function name and it can be called.
To achieve this in our project, we wrote a proxy function to call the function returned inside the Ajax response.
function FunctionProxy(functionName){
var func = eval(functionName);
func();
}