I am sending chat message, and receiving them in particular div.. All read and write with ajax. Everything works fine in Chrome, but in firefox, it does not shows...
Here is my code :-
var xmlhttp = false;
function read_message() {
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatBox").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'http://<?php echo $domain; ?>/m.php?id='+<?php echo $id; ?>,true);
xmlhttp.setRequestHeader("Content-type","text/html");
xmlhttp.send();
}
$(document).ready(function(){
setInterval("read_message()", 800);
});
$domain is define in Header page and it is Same domain, where file is running... i.e,
if my chat page is in localhost than $domain is also localhost..
I am aware of same origin policy of ajax, but is this problem due to using http://.
I cannot leave http:// part as i am using url-rewriting and there my url is something like http://localhost/chat/user/anonymous so, if i use only m.php?id=1 than it tries to fetch page from
http://localhost/chat/user/m.php which obviously doesnot exist... it exist in http://localhost/m.php
if above mentioned point is error, is there any way that we can solve it, or any other better help would be great.
Thanks
When you fire two requests, if the second request fires before the first request resolves, xmlhttp.responseText in your onreadystatechange listener would point to the responseText of the second (unresolved) request when the listener for the first request fires. This is because you only use a single global xmlhttp variable that is shared for all requests.
If you define var xmlhttp inside your read_message, instead of outside of it, then each new function call will have its own private xmlhttp variable:
function read_message() {
var xmlhttp;
//...
}
Related
I have an AJAX code which takes input from the radio form.
When the server code satisfies a certain type of if() condition, it gets redirected to other page of my site for example, dashboard.php !
When it redirects, I still see the radio button form on the dashboard.php ! (which is not coded on that page...)
http://oi60.tinypic.com/30u7haq.jpg
For redirecting, I have used php function :
header('location:dashboard.php');
I need to somehow clear the response or disable the response when the code is redirected to the dashboard.php
AJAX Code:
function sendid(attack)
{
var att;
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("result").innerHTML=xmlhttp.responseText;
document.getElementById("r1").checked = false
document.getElementById("r2").checked = false
}
}
xmlhttp.open("POST","battleuser2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("att="+attack);
}
Hi I think you'll need to do your redirect after the ajax completes, not in the code that handles the ajax request...
try...
window.location.href = 'dashboard.php';
in your ajax success handler...
and remove the...
header('location:dashboard.php');
in your ajax handler
UPDATE:
Ajax handler (battleuser2.php)
if(true){
echo 'success';
}else{
echo 'fail';
}
exit;
Ajax complete:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.resonseText == 'success'){
window.location = 'dashboard.php?msg=You Won!';
}else{
window.location = 'dashboard.php?msg=You Lost!';
}
}
Dashboard.php..
if(isset($_GET['msg']))
echo $_GET['msg'];
Your ajax function is not loading a whole new page into the browser and thus the browser is not automatically processing the headers in the ajax response for a redirect. So, from your Ajax call, the server can't automatically cause the browser to go to a new page.
If you want that to happen, you will need to stop using an ajax call and just use a regular form post (where the server returns the response page which will be processed for a redirect).
Or, you can do the redirect manually in your own javascript that processes the result of the ajax call. Doing it yourself in your javascript code would look like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
window.location = 'dashboard.php';
}
So What I'm trying to do is, create an alert using java script. And if the person presses OK
it will send a variable to the handler and the handler will send an email. The following code is what I have, but I'm having trouble debugging it. As of right now I have this:
THE IF STATEMENT, CLICKING OKAY:
var pressed = confirm("Click okay to email users of video upload or Cancel to keep adding videos");
if (pressed == true)
{
var variable = 44;
emailParticipants(variable);
alert ("email sent");
}
FUNCTION THAT SENDS TO HANDLER:
function emailParticipants(sessionID)
{
var ID = sessionID;
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","http://www.website.ca/portal/folder/HandleEmail.php?sessID="+ID,true);
xmlhttp.send();
}
HANDLER:
$SessID = $_GET['ID'];
<?php
$toEmail = 'someone#hotmail.com';
$toName = "TEST TEST";
<script>alert ("works");</script>
.
..
....
The rest of the handler functing just sends the email. I can't catch where the mistake is.
Well, you are invoking the handler via AJAX. The alert() method is inside the page the handler returns ... but you aren't doing anything with that page. You make a request and forget about the response. The browser doesn't execute the response from an AJAX call, so the code with the alert never executes.
By the way, you ** never ** should send e-mails (or do any other change in the server but returning information) with a GET request. GET requests can be cached, or even prefetched, causing emails to be sent when not requested, or not be sent when requested. I'd change the request type to POST.
If you want your alert, you need to change your client code and add this:
xmlhttp.open("GET","http://www.website.ca/portal/folder/HandleEmail.php?sessID="+ID,true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('works!');
} else {
alert('Failed! ' + xmlhttp.statusText);
}
}
}
xmlhttp.send();
I think you are a bit lost about AJAX. You should read more
I have a Firefox addon, in one of my js files I have an object that I use in my script.
Now I need this object online as json, so I'm going to add this json file on the server. And every time I run script the first thing it will have to do is include that file.
How can I do this with javascript?
Something similar as PHP include something?
I can't use jQuery
Have a AJAX call to the url(server file that should provide the object as response) on top of your script.
See here for AJAX call, http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
Should the communication happen between domains, ie, if the file that holds JSON object hosted in abc.xom and script file that makes AJAX call hosted in XYZ.com then set Access-Control headers with response that would work with CORS enabled browsers http://enable-cors.org/client.html. For Non-CORS browser we should go with JSONP object/call.
Im trying to do this:
var locations = loadLocations();
function loadLocations() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
alert("Something went wrong!");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
return xmlhttp.responseText;
//console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://.../locations.json",true);
xmlhttp.send();
}
console.log(locations);
but firefox show me error debugger eval code on line xmlhttp.send();
when i do console.log(xmlhttp.responseText); inside the functions, it shows me everything, but when i return this, dont show anything
I have been playing around with Javascript and now I came to Ajax. I am trying to write very simple script that would get the file contents - print the txt file contents in the div with id=test. This is the script :
function loadXMLDoc(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('test').innerHTML = xmlhttp.responseText;
}
when I use it on this website :
<div id="test" name="test"> HELLo </div>
<button type="button" onclick="loadXMLDoc('test1.txt')">ClickMe1</button>
With this script HELLo is substituted by nothing - the script empties the container.
Maybe I am missing something trivial but do I need PHP installed ? I don't think so but... I am not sure what is happening in here. When I am debugging the xmlhttp is empty the whole time. Why ?
You'll need to check for readyState and the HTTP response status before replacing the text;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test").innerHTML=xmlhttp.responseText;
}
example on http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
Please let me know if it works.
For browsers other than IE
IE's active X object seems not to care much about the ready state, other browsers may not have the text loaded quickly enough at the time you run your function (hence why you are getting the blank instead of file contents). IE's active X seems to handle this automatically and ignores the ready state, so you have to break up the code differently as below. Normally you check the status of the request to see if it's been fully read or not before accessing the responseText.
Add onreadystatechange you cannot check the status attribute since there is no HTTP requests being made on a file system request. (The status will always be 0 for request not made via HTTP) The best I can offer is this:
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
xmlhttp.open( "GET", url );
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open( "GET", url );
xmlhttp.send(null);
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
}
For CHROME
If you are using CHROME you must start chrome up with the --allow-file-access-from-files switch. Otherwise, it will refuse file system ajax requests. (You will have to set this even if using a so-called "easier" library such as jQuery).
Running AJAX apps on File System In General
Not usually a good idea, a lot of caveats to this route. Typically local development is done with a web server installed to localhost on your development machine.
Today its old fashion to call ajax like xmlhttp = new XMLHttpRequest();
You have many other options for this.
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Firstly, you have to fight with Same Origin Policy.
A simple working code for a synchronous request is following:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.status == 200 && req.readyState == 4) {
...
}
req.open('GET', url, true);
req.send(null);
Note this is working for Firefox/Opera/Chrome. If IE, use:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
You need a server to listen up to requests. Your regular file system will not be able to respond to AJAX requests.
You don't need PHP, however you'll need apache or a similar web server.
Try with jQuery. Download the last version here and write this code snippet:
function loadXMLDoc(url) {
$("#test").load(url);
}
It's much simpler and less error prone
I'm trying to load specific content from a XML to a HTML div. I'm using a function with parameters to do this.
This my call to function:
loadDoc("news.xml","destak-article","article");
this should send a request for the xml file, get the content of «article» tag and put it on the «destak-article» div.
Here's my function body:
function loadDoc(url,id,tagname){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
But this doesn't seem to work.
On Chrome js console I get this error: Cannot call method 'getElementsByTagName' of null
On Firebug I get: xmlDoc.getElementsByTagName(tagname)[0] is undefined
Any help is much appreciated.
Did you verify the server response? Use some error checking in your code. For example:
if (xmlhttp.status == 200) {
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
else {
alert('error');
}
You need to register a handler function that will be called once the request is complete. You can see an example of how to do that here.
What's happening in your case is that you're trying to get the xmlDoc immediately after sending the request and the server hasn't had time to process the request and respond yet.