The reason I am asking this is because in one of my pages I link a javascript script and then when I try to run a function in the javascript file, it doesn't work.
This is weird because when I copy the exact same code from the script file and put it between the tags, the function then works fine.
Here is how I linked it:
<script src="../scripts/login.js" type="text/javascript"></script>
Here is how it is referenced:
<td><button type="button" onclick="login()">log in </button></td>
Here is the javascript file in case you want to see it:
function login()
{
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)
{
username = encodeURICompenent(document.getElementById("username").value);
password = encodeURICompenent(document.getElementById("password").value);
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
If you attach an external JavaScript file to your document and it contains code that were not found inside any method written on function declaration syntax. those code would execute right after the browser parses the JavaScript file.
Ex.
function CallMe() {
console.log("I'm going to execute once callMe method is invoke");
}
console.log("I'm going to execute once browser parses the javascript file");
The login method on your case wont execute unless there is an event that triggers/invokes the click event of your button.
Related
I am currently creating a website where we take the data of our most visited articles of our website and list them on a specific page.
Now, the way I am collecting the data is by using PHP and I am using JS to generate the result on my page. The thing is that the coding is working but it only works if the page link ends with .html (i.e. www.website.com/article.html) but it my page link is addressed like this: www.website.com/article, the results don't show.
I tried extending the link of my js (i.e. ../result.js) but that doesn't do anything.
If you could please help me figure this out, I'd greatly appreciate it!
Thanks!
Here is a sample of the js code:
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function mostVisitedExt()
{
loadXMLDoc('mostvisited.txt',function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
var res = txt.split('*&^');
document.getElementById("mostVisitedExt").innerHTML =
"<ul class='jrecent'><div class='jname'><p class='body'>"+res[0]+"</p> </div><div class='jcontent'><a href=http://"+res[0].toLowerCase()+".website.com"+res[20]+" class='body-link' target='_blank'>"+res[10].substring(2, res[10].length-2)+"</a><p class='body'>" +
res[21] + "</p></div></ul>" +
The mostVisitedExt function is the PHP file where it is getting the data from.
I have been troubled on how to load the same div into the same page for days.
Been looking for answer in stackoverflow but not found one yet.
Simplified, this is my code so far,
<script>
function add_fields() {
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.open("POST", "add_more.php", false);
xmlhttp.send();
document.getElementById("add_more1").innerHTML = xmlhttp.responseText;
}
</script>
<html>
<body>
<input type="button" onclick="add_fields()" value="ADD"/>
<div id="add_more1"></div>
</body>
</html>
The problem is that when i clicked the button, it will only load add_more.php once. I want it to load everytime the button is clicked. How to do that?
Please help.
function add_fields() {
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"); //really no need for this anymore these days.
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) //success
{
document.getElementById("add_more1").innerHTML=this.responseText;
}
}
xmlhttp.open("POST","add_more.php",true); //set the sync to true, modern browsers will block a synchronous request.
xmlhttp.send();
}
This updated versions contains a readystate event that will fill your div every time the Ajax call is completed.
You were using a XMLHttpRequest with the asynchronous option set to false. This could block the user experience and modern browsers (like Firefox) will block this.
if you would like to add more content to the div, use
document.getElementById("add_more1").innerHTML += this.responseText;
+= adds content to the element instead of replacing it. It's a shorthand for:
document.getElementById("add_more1").innerHTML = document.getElementById("add_more1").innerHTML + this.responseText;
SIDENOTE: You are using a POST (in this case a GET would be better, since you're retrieving information only). If you want to send post data to the server you need to put the querystring (without the ?) as an argument in the send method.
To continue with this read up on asynchronous coding:
Easy to understand definition of "asynchronous event"? (very simple explanation).
How does Asynchronous Javascript Execution happen? and when not to use return statement? (more comprehensive).
I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>
I am trying to load a different xml file everytime a link is clicked, based on its href.
I have the following in head:
JAVASCRIPT
window.onload=function() {
loadXMLDoc("papers.xml"); // loads the default xml file so that page is not empty
}
function scanForXML(){
var extLinks=document.getElementById('results_list').getElementsByTagName('a');
for (i=0; i<extLinks.length; i++) {
extLinks[i].onclick=function getName()
{
var fileName=this.getAttribute('href');
loadXMLDoc(fileName);
return false;
}
}
}
HTML
<ol id="results_list">
<li> <a class="tooltip" href="paper2.xml"> Teaching with Tablet PC's </a></li>
<li> Tablet PC’s as Instructional Tools </li>
</ol>
The onclick event works, I get the href value but the new xmlFile does not get loaded.
Any ideas why?
ps: no jquery plz, cannot use that. trying to learn better basic javascript
The Javascript load code - by the way it does not work in chrome and opera - but works the default xml file gets loaded in safari
Code:
function loadXMLDoc(dname)
{
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",dname,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
Thanks!
K
That's because the request is asynchronous : there is no response when your loadXMLDoc function returns.
The usual solution is this :
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
// use xmlhttp.responseXML;
}
}
}
xmlhttp.open("GET",dname,false);
xmlhttp.send();
The main difference is that you don't use the return of the loadXMLDoc function but ask it to do something after it has fetched the XML.
Another solution would be to force a synchronous request using jquery's ajax function
EDIT : I mark it as duplicate as it's a frequent question but I hope this specific answer will help you.
I have use Ajax and jquery for get data from database and send data, but when we use ajax or jquery methods, web page source view ,we can see details like below;
Ajax
<script type="text/javascript">
function showUser()
function showUser()
{
var str = document.getElementById('txtusername').value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="<span style='color:#FFF;font-size:10px;'>Enter username</span>";
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","chkusername.php?q="+str,true);
xmlhttp.send();
}
</script>
In here you can see the get method and what are the sending values and also more things. I want hide these thing from source view, help me ..
You can't. Anything on the client side (HTML, CSS, JavaScript) is free for the user to see.
That's why anything security-related is on the server side, where it can be trusted (for the most part).
It's not a security risk if the user knows that to log in you go to /chkusername.php?q=username (or whatever). It is one, however, if you don't properly sanitise the input.