AJAX xmlhttp.responseText - javascript

I've been racking my brain for a few hours and can't figure out why a string comparison won't work. In the following code, I do a xmlhttp call and get a response text. The PHP file that I get a call IS returning the proper response string "NOAD", and NOAD is being displayed when appropriate in my testing. However, when the call is returned NOAD I want to identify it, however for some reason within the call below xmlhttp.responseText == comparisonText its NOT properly comparing the two. Why does xmlhttp.responseText printout NOAD but I can't use it within the comparator?
function loadXMLAdImage1Doc(currentScenarioTime)
{
var returnText = "Not Here";
var comparisonText = "NOAD";
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)
{
if (xmlhttp.responseText == comparisonText)
{
document.getElementById("AJAXTEST").innerHTML =returnText;
} else {
document.getElementById("AJAXTEST").innerHTML =xmlhttp.responseText;
}
}
}

Okay, thanks Luth for pointing me in the right direction. I solved my problem, but I'm not sure what the problem is within xmlhttp.responseText or user error that caused it.
The return text from my PHP file was placing an unseen character BEFORE the returned string (in testing, I would have figured it was an invisible character after prior to the results but go figure). Theoretically, this shouldn't be happening...my PHP is returning a straightforward string:
..do some MYSQL queries..
$AdLink = mysql_result($result, 0);
if ($AdLink == "") {
echo "NOAD";
} else
{
echo $AdLink;
}
So the PHP file SHOULD be sending a 4 character return screen to the xmlhttp.responseText call named "NOAD". But what was found in measuring the string length was that it was sending a 5 character string back with some invisible character BEFORE "NOAD" that wasn't showing up on the screen - therefore screwing up the comparator. I used the following code to remove the character and it worked perfectly...
returnText = xmlhttp.responseText;
var returnlength = returnText.length;
returnText = returnText.substring(1, returnlength);
I have no idea WHAT the character is, whether its a problem with my PHP code or the xmlhttp.responseText call, but something to be aware of if you're dealing with the call.

Related

Php not receiving post from JavaScript

I have implemented the same setup elsewhere in my site and can't figure out why it's not working this time.
When a user clicks the accept button, it calls a JavaScript function acceptOrder(orderID) which passes the orderID onto a php page to update a record in the db.
orderID is assigned ok in the JavaScript but it doesn't reach the php. Var_dump on POST shows nothing, nor does $_POST('orderID'). I've even tried just sending an integer to the php in case there was a problem with the var but it made no difference.
Js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft. }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}
Php
<?php
require_once("config1412/class.shop.php");
session_start();
$shop = new SHOP();
echo var_dump($_POST);
//$orderID = $_POST['orderID'];
//echo "orderId var = ".$orderID."<br/>post ".$_POST['orderID'];
//$shop->acceptOrder($orderID);
?>
Needless to say I've searched about and don't see any solutions elsewhere.
Many thanks
As i can see, you didn't set variable name for orderID, change line of code:
xmlhttp.send(orderID);
to:
xmlhttp.send("orderID="+orderID);
If it's only SQL error of missing orderID, and all other passess okay, it's solution for you. As you said in comments "I just get a sql error because the variable orderID is empty".
You're missing only naming post send data, that's why it's empty.
Please replace this line
xmlhttp=new ActiveXObject("Microsoft. }
with following this line
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
You should write this in your js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}
I would recommend you to use jQuery for ajax calls. It's much easier to setup and straightforward. Especially, and specialy because it is very easy setup for a beginner. And for people who want to install ajax the easy way. I use it every single time I want to do ajax in my code. Here is a link:
http://api.jquery.com/jquery.ajax/
Just put the tag to include jQuery and then one javascript command to call the ajax.

AJAX mysql command not immediately executed?

So I have some code, which checks for whether a one time use discount code exists, and if so, it applies it and then marks it as used in the database. The problem is, it ends up being useable more than once if you spam click it, and then some time maybe 15-20 seconds later it stops being useable.
The relevant javascript component:
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) {
discountAmount += parseFloat(xmlhttp.responseText);
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
This is processed over in the php file, and when a match is found we echo that amount and then delete the entry
$mysqli->query("DELETE FROM discounts_available WHERE `index`=$index");
The php file is indeed doing what its supposed to. When you click apply code, it is immediately deleted from the database. The problem is, even with the code no longer in the db, you can still apply the code over and over for some amount of time before the js file finally realises there is no entry in the db. Why is this?
You should first check if it exists in DB then only you should proceed with request, it should be very first statement.
If it does not exists you can send response saying code already applied.
You most likely need to lock the table ASAP so no other instances can modify the table concurrently.
http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html
I did not get your problem, exactly I am assuming lost of things, so..
//this is triggered on some click, right?
//TODO:- check if button is disabled? you can have some js variable or check button attribute disbled
//TODO:-if its not disaled->{so first disable the button when it is clicked } else do nothing
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) {
discountAmount += parseFloat(xmlhttp.responseText);
// if succefull keep button disabled
// else renable it, so that it can be clicked again.
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
thers's no syntax problem here in your code its logical,
ajax call is asynchronous call, it does not happen in sequence
1) You clicked
2) Request Sent
3) Request Processed
4) JS is informed : your modifyCartOrder function executed
what I am trying to say here is that, there is no 3 immediately after 2, 3 will take time to start, js has no control over it, whenever php is done it will reply there's no guarantee. so you can repeat 1 again and again, and 2 will keep repeating... and so 3 will...
I hope I understood your problem, and you understood what I am trying to say :)
Problem is : You are sending asynchronous ajax calls from following code :
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
Solution : as defined , for opening an ajax call , method is :
xmlhttp.open(method,url,async)
So, You have to modify above line as:
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,false);

Show Save-As window from JSP

I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + 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)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.

Javascript Unexpected token ILLEGAL

I have a PHP script (fetchData.php) that fetches some data and outputs it to a page.
<?php
require 'config.php';
require 'jsonapiSDK.php';
$api = new JSONAPI($ip_address, $jsonapi_port, $username, $password, $salt);
$response = $api->call('BWMFunction');
echo(addslashes($response["success"].";"));
?>
You can see the output here: http://justicecraft.net/worldmap/fetchData.php
I have another page that uses an XMLHttpRquest to get the response from fetchData.php
Here's the JavaScript for it. It's supposed to take the response, and eval() it (to create an array called BWMFunction) then pass that array to another function I have. The Illegal token error occurs when I try to eval() the response.
function fetchData() {
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) {
res = xmlhttp.responseText;
alert(res);
eval(res);
generate(BWMFunction);
}
}
xmlhttp.open("GET", "fetchData.php", true);
xmlhttp.send();
}
This is my first time on StackOverflow, so any help would be appreciated. I have googled around for quite a while now, but none of the answers helped me.
You have invalid javascript returned from fetchData.php which is why the eval method crashes. Instead of \" in the output you should have simple ". I know strictly nothing about PHP but I am ready to bet some bucks that its the addslashes function which is causing the damage. So maybe you could try something along the lines of:
echo($response["success"].";");

IE issue with DOM manipulation

I have a AJAX form and I use this line on receiving a response:
document.getElementById("output").innerHTML = xmlhttp.responseText;
Output is a div and in IE I'm getting an Unknown JavaScript Error.
Would it be the content that's being passed from the AJAX that's causing this error or is there something syntactically wrong with that line?
EDIT:
if(valid==true){
//AJAX
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("output").innerHTML = xmlhttp.responseText;
id = document.getElementById("parentID").value;
}
}
var parameters = "shedloadofvariables"+shedloadofVariables;
xmlhttp.open("POST", "register.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}
else{
alert("Please Fill in All Fields");
}
Cheers
Output is a div and in IE I'm getting an Unknown JavaScript Error.
"Unknown runtime error" commonly occurs when setting invalid HTML via the innerHTML property. Not all invalid HTML will cause this problem — the common case is trying to stuff a block element into an element that doesn't allow block elements, like a <div> inside a <p>. Only IE spits out this error message, other browsers will do their best to recover from your crappy HTML.
First thing to do is validate the HTML with the W3C validator. For more information, take a look at http://blog.rakeshpai.me/2007/02/ies-unknown-runtime-error-when-using.html.
You could try using jquery $('#output').html(xmlhttp.responseText);
I still don't understand the problem fully (Andy E's answer certainly helps though).
I found a work-around for this issue:
var t = document.createElement('div');
t.innerHTML = xmlhttp.responseText;
document.getElementById("output").appendChild(t);
Flawless.
Don't know why, but I'm not about to question it, because it works!

Categories

Resources