I have this function handling ajax calls:
function ajaxPost (divNode, parameters, file) {
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) {
alert (xmlhttp.responseText);
divNode.appendChild (xmlhttp.responseText);
}
}
xmlhttp.open("POST", file, true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}
The alert about halfway down gives me the expected output from the given php file, but for some reason, I don't seem able to append it to the dom. I have checked the divNode is actually a div element & I'm successfully using appendChild else-where, so I'm at a loss to understand the problem here.
What is different about an Ajax call to disrupt normal javascript functions and how do I work around it?
The appendChild method takes an HTMLElementNode (or other DOM node object) as an argument, not a String
You need to build a DOM tree using createElement and createTextNode and then append that. This is a good solution combined with a server returning a neat data structure expressed in JSON.
Alternatively, you could look at innerHTML.
Change divNode.appendChild (xmlhttp.responseText);
to
jQuery:
$(divNode).appendChild (xmlhttp.responseText);
And change what you're passing in as divNode to something like '.classname' or '#idname'
Or Non jQuery:
document.getElementById(divNode).appen... divNode would need to be an ID of the element
Related
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 make an ajax commenting system where if a new comment is posted, the document title changes to (1) website title (like twitter)
my code is here
The xmlHTTPrequest
function loadXMLDoc7(url)
{
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",url,false);
xmlhttp.send(null);
document.getElementById('newcomments').innerHTML=xmlhttp.responseText;
}
The PHP
echo "<script type='text/javascript'>
function auto2comments()
{
var MyDiv1 = document.getElementById('uiuiui');";
echo "loadXMLDoc7(MyDiv1.innerHTML)";
echo "}";
echo "setInterval(\"auto2comments()\",15000);</script>";
}
The DIV uiuiui contains /newcommentingi.php?show=0&id=username
The problem is when the Newcomments DIV gets filled, it shows
ID =
Show = 0
why?
The XmlHttpRequest object is asynchronous, which means that when it has the data ready, it returns it in a method. It is best to create a function to act as an event handler so that when the server responds, it calls the event handler function.
I think the solution you need is similar to here: How to get the response of XMLHttpRequest?
I got a cgi-script the performs a search according to the query-string it gets submitted.
That works all fine.
But since the search can take some time and the user might start another search. I want the first search to get aborted before a second search is started, but if I insert a xmlhttp.abort() at the beginning of my AJAXRequest function the cgi-script doesn't get started at all.
Can anyone tell me how this could be performed?
Thanks in advance!
and here is the AJAX-code snippet
var xmlhttp;
function AJAXRequest()
{
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)
{
window.document.getElementById("resultlist").innerHTML=xmlhttp.responseText;
}
}
var queryString= "from=03-01-2006&to=04-30-2006&pattern=345";
xmlhttp.open("POST","../cgi-bin/search.exe?"+queryString);
xmlhttp.send();
}
Yea, XMLHttpRequest.abort() is a correct method to use for AJAX request aborting.
In my opinion your problem is more kind of design problem and not technical.
Therefore my suggestion is to review the flow of how the user interacts with your application.
For example, the classical solution is to show the progress bar or spinner and disable the "Search" button while your request is not completed and revert this state on success or error.
I found my problem.
I tried to abort a request object that has just been created. The object has to be global. At least that's the only way I see how to achieve this.
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.