Javascript AJAX responseText problem in IE - javascript

I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:
(AJAX)
function getMessages(messengerid, repeat)
{
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("messages").innerHTML=xmlhttp.responseText;
document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
}
}
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
(PHP/MySql)
<?php
$key = "abcIUETH85i236t246jerst3487Jh";
if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {
include_once("../config.php");
include_once("../class/system.class.php");
$sys = new system($template_name);
if(!$sys->connect($db)) {
exit();
}
$messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
$messenger = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");
$user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
$user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");
$displaynames[$user1[0]['id']] = $user1[0]['displayname'];
$displaynames[$user2[0]['id']] = $user2[0]['displayname'];
foreach($messages AS $key => $message) {
if(is_numeric($key)) {
?>
<div class="message">
<b><?=$displaynames[$message['account_id']];?> (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
<?=nl2br($message['message_content']);?>
</div>
<?php
}
}
}
?>
Any help would be much appreciated!
Thanks in advance.
Best Regards,
Skyfe.

Your response is being cached. One way to fix this is to append a unique parameter in your request URL, such as the current timestamp.

Its a common problem with IE it caches the result.Add some dummy random parameter to your ajax call e.g current timestamp

i dont know about php but in jsp you can add the following code to your jsp page
response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
i know the post is old , i just replied for future viewers :D ;)

Related

How to send data through ajax function in JavaScript

i am trying to create an ajax favorite button in php similar to instagram and twitter.
my code seems to be fine and i am doing everything correctly and tried to get it working this way:
php code:
$user_id = $_SESSION['active_user_id'];
extract($_POST);
extract($_GET);
if(isset($_GET['message']))
{
$id=$_GET['message'];
$q=$db->prepare("SELECT msgid,date,text
FROM messages
WHERE to_id=? and msgid=?");
$q->bindValue(1,$user_id);
$q->bindValue(2,$id);
$q->execute();
$row2=$q->fetch();
$d=$row2['date'];
$fav_questionq=$db->prepare("SELECT *
FROM messages
LEFT JOIN users
ON messages.to_id=users.id
WHERE users.id=? AND messages.msgid=?
");
$fav_questionq->bindValue(1,$user_id);
$fav_questionq->bindValue(2,$id);
$fav_questionq->execute();
$frow=$fav_questionq->fetch();
$fquestion= $frow['text'];
$result = $db->prepare("SELECT * FROM fav_messages
WHERE username=? AND message=?");
$result-bindValue(1,$user_id);
$result-bindValue(2,$id);
$result->execute();
if($result->rowCount()== 1 )
{
$deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
$deletequery->bindValue(1,$id);
$deletequery->execute();
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
else
{
$insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
$insertquery->bindValue(1,$user_id);
$insertquery->bindValue(2,$id);
$insertquery->bindValue(3,$fquestion);
$insertquery->bindValue(4,$d);
$insertquery-execute();
}
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
javascript code:
<script>
function GetXmlHttpObject() {
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
}
return xmlHttp;
}
function ajaxfav(){
var xmlHttp=GetXmlHttpObject();
var url="favorite.php?message="+document.msgidform.fav_message.value;
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
alert("Message is favorited");
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
</script>
HTML form and link code:
<form name="msgidform" method="post">
<input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>></p>
</form>
<a class="msg-icon" href="" onclick="ajaxfav();"><img
src="images/linedfav.png" id='img'></img></a>
but i kept getting an error in the console that reads:
"Uncaught TypeError: Cannot read property 'value' of undefined
at ajaxfav" but i've fixed it and now it immediately goes to the alert message, but nothing is inserted into the database, meaning that the data was not sent to the php file.
can someone advise me on what i can do?
network tab of the ajax call
please i would appreciate any help or suggestion. the php file is called but does not insert anything into the database.
You can use
document.msgidform.elements['fav_message'].value
in your ajaxfav() function to get name field value.

xmlhttp.open does not seem to do anything in MVC structure

I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} else {
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("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.

AJAX: Why does $_REQUEST on server side not contain the variable passed from JS in URL by GET method?

I have three divs saved in an array as simple_html_dom objects. I needed to change a CSS property of two of them on the click of a button. That's easy, but then I also need to make that change in the CSS property (in the simple_html_dom object stored in the aforementioned array) in the PHP script on the server side.
So I figured from my web search I needed AJAX for this. So I read up this tutorial, and I am following this example, and doing something like:
On the client side:
function xyz(var divIdOne, var divIdTwo) {
document.getElementById(params.divIdOne).style.display = "none";
document.getElementById(params.divIdTwo).style.display = "block";
document.getElementById(params.divIdTwo).style.border = "5px solid red";
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();}
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
On server side:
foreach($_REQUEST as $requestkey => $requestvalue) {
echo $requestkey.': '.$requestvalue;
}
if (array_key_exists('pass_back', $_REQUEST)) {
foreach ($array_of_divs as $div) {
if ($div->id=$divIdOne) {
$div->style='display:none';
} else if ($div->id=$divIdTwo) {
$div->style='display:block';
}
}
} else {echo 'FALSE!';}
The first foreach loop prints other variables but does not print pass_back. The next if block does not execute at all. The else block executes. This means that $_REQUEST clearly does not contain pass_back. Can anyone pinpoint why, or what I did wrong?
I fail to see the error. How do you check that you're not sending the data properly? I suggest using this piece of code in order to check what your server is receiving from your request:
function xyz() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);// Let's see what the server is echoing
}
}
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
Please, let us know the output.
I would recommend that you use jquery and firebug, and first get rid of the following problem: why is passback variable not received.
Create the file: test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<title>Html page</title>
</head>
<body>
<script>
(function($){
$.post("myfile.php", {
passback: "pooo"
}, function(d){
console.log(d);
});
})(jQuery);
// or if you cannot use jquery
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) {
// do something with the response, if you need it...
// document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("passback=pooo");
// src: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
</script>
</body>
</html>
Then create the file: myfile.php
<?php
if(isset($_REQUEST['passback'])){
echo "ok";
}
else{
echo "oops";
}
Next, download firefox, and download the firebug extension (or you can use chrome's console alternatively). The goal here is to see what is being passed through the network.
Launch test.php in a browser, open the firebug console (or chrome's console),
and debug until you see the "ok" message.

Ajax watch database for changes and execute code

My goal is to more or less send out requests to a php file, giving it parameters like so;
<!DOCTYPE html>
<html>
<head>
<script>
function onsubmit()
{
var id = $_SESSION['user']['id'];
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)
{
window.WhateverVariable = xmlhttp.responseText;
}
}
xmlhttp.open("GET","clientrequest.php?id="+id,true);
xmlhttp.send();
}
</script>
</head>
<body>
</body>
</html>
and keep sending out requests untill my php script returns x value, which will be passed into the window.WhateverVariable, and when the WhateverVariable is equal to 'x' I wish to execute some code;
however, I can achieve this, but when the code is executed, the request is still going meaning the response text will be 'x' and will continuously destroy then re-execute the code, any way to get past this?
if ( the_mini_game_is_not_open() )
{
// send the regular ajax request
} else {
// send the ajax request but with the message that the mini game is open through parameters maybe like ?open=1
}
And on server side deal with this like:
if ( isset ( $_GET['open'] ) && $_GET['open'] === 1 )
{
// pause it or whatever...
} else {
// show the regular results
}
This was what I understood. Sorry if that's not what you want

ajax php call not returning anything

I want php to return a value to ajax. I'm following W3 schools example but no joy.
Here is the javascript/ajax code:
function createReport() {
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("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)
createReport();
and later in the body section of the html I have:
<div id="report">Report will be placed here...</div>
If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:
<?php
echo 'return this to ajax';
?>
My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?
I personally do not think the w3cschools a good place to learn ( see http://www.w3fools.com/ ).
It may be that the problem occurs because of the order that you set the ajax, you did:
XMLHttpRequest/onreadystatechange/open/send
is preferable (if you do not follow this order may occur several flaws in older browsers):
XMLHttpRequest/open/onreadystatechange/send
Note: do not worry, the "open(...)" does not start listeners.
Listeners only work after the "send(...)"
Another reason may be that you did not create "error handling" of XMLHttpRequest.status, it serves to verify faults in the server response.
Try this:
<script>
function XHR(){
if(window.XMLHttpRequest){//outers browsers
return new XMLHttpRequest();
} else if(window.ActiveXObject){//IE
try{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(ee) {//IE
try{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(ee) {}
}
}
return false;
}
function createReport(){
var xhr = XHR();// call ajax object
if(xhr){
xhr.open("GET", "test.php", true);//setting request (should always come first)
xhr.onreadystatechange = function(){//setting callback
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("report").innerHTML=xhr.responseText;
} else {//if the state is different from 200, is why there was a server error (eg. 404)
alert("Server return this error: " + String(xhr.status));
}
}
};
xhr.send(null);//send request, should be the last to be executed.
} else {
alert("Your browser no has support to Ajax");
}
}
</script>
<div id="report">Report will be placed here...</div>
<script>
createReport();//prefer to call the function after its div#report
</script>
To prevent cache, replace:
xhr.open("GET", "test.php", true);
by
xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);
At first glance I don't see anything wrong on your js code, so I bet it will probably be a problem locating test.php in your folder structure.
With firebug check the call your javascript AJAX it's doing, and check if the file test.php is being correctly assesed.
I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).
Possible factors:
Missing <script></script> tags
Make sure you have JS enabled.
Make sure your browser supports it.
You may have forgotten to change the button's call to the proper function.
Working and tested code using FF 26.0 and IE version 7
Pulled from W3 Schools Website (example) and slightly modified to prove this works.
Result when clicking on the Change Content button:
return this to ajax - as per your PHP code.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP used: (test.php)
<?php
echo 'return this to ajax';
?>
Other possible factors:
If on a local machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly.
If on a hosted service, make sure PHP is available for you to use.
Files are not in the same folder as executed from.
try{
request = new XMLHttpRequest();
}catch(trymicrosoft){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request = false;
}
}
}
if(!request)
{
alert("Error initializing XMLHttpRequest!");
}
function Create_Ajax_Query(LinkToFile,Parametrs)
{
window.document.body.style.cursor='progress';
request = new XMLHttpRequest();
var url = LinkToFile;
var params = Parametrs;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = newinfo;
request.send(params);
}
function newinfo()
{
if(request.readyState==4 && request.status == 200){
window.document.body.style.cursor='default';
alert(request.responseText);
}
}
Hope its useful!
The code looks correct. it runs just fine on a local environment.
I would advise to look at the "Network" tab in the developer tools to detect any errors may occurs on the server side. You can also use console.log() to follow the javascript actual flow:
function createReport() {
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() {
console.log(xmlhttp); //to show the entire object after statechage.
console.log(xmlhttp.readyState); //to show specific parameter.
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}

Categories

Resources