ajax responsetext has extra data - javascript

I use ajax to check if there is a certain record in the database, using the variables 'zer' and 'modify' to search for the record containing those values (see the code below).
If the record is found in the database, I return "found" from the php ajax code to the javascript; otherwise I return "not found"
I also store the value of 'zer' and 'modify' into the SESSION before I return the "found" or "not found" from the php ajax code.
The response text looks like this when the record is found in the database:
array(2) {
["zer"]=>
string(2) "someVal"
["modify"]=>
string(1) "anotherVal"
}
found
I only want the "found" returned here and for some reason the responseText is returning the Session variables that I set up before the return.
Why is this, and how can I precisely control exactly what is returned from the Ajax call?
I tried using some buffer flushing php calls (see the code) to no effect. I've read a lot of Ajax posts but I cannot find one that explains how to have precise, exact control over what gets returned from my ajax, or whether storing my 'zer' and 'modify' values into the SESSION before I return the responseText is some kind of "no-no."
Here is the code (NOTE: the database lookup code works 100% and correctly finds the record if it is present -- the code below has been tested for both the 'found' and 'not found' situations and correctly locates the record if it is present).
EDIT: I use some output buffering PHP calls in an attempt to control any output buffering that may be happening, but this did not help. See these buffer calls below.
JAVASCRIPT
var zer = "someVal";
var modify = "anotherVal";
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var theResponseText;
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
theResponseText = xmlhttp.responseText;
alert("responseText is >>>" + theResponseText + "<<< that.");
if( theResponseText == 'notfound')
{
return;
}
else if( theResponseText == 'found')
{
alert("We found the record!.")
}
}
}
ajaxText = "handler.php?zer=" + zer + "&modify=" + modify;
xmlhttp.open("GET", ajaxText, true);
xmlhttp.send();
PHP CODE in handler.php
$zer = $_GET['zer'];
$modify = $_GET['modify'];
$theDB = connectToDb();
$query = "SELECT * FROM " . Dbases::$MyDB_TABLE
. " WHERE BINARY " . dbConstants::$ZERS
. " IN ('" . $zer . "')"
. " AND BINARY " . dbConstants::$MODIFYS
. " IN ('" . $modify . "')";
$result = mysql_query($query);
if($result)
{
$numrows = mysql_num_rows($result);
if($numrows > 0)
{
$bFound = true;
}
}
closeDB($theDB);
// now erase the php output buffering, start a new output buffer,
// echo the result, then flush the php output buffer so that the
// Ajax response text has *exactly* what I 'echo' here and nothing else.
// NOTE: this did *not* help.
if(! $bFound)
{
ob_flush();
while (#ob_end_flush());
//ob_end_flush();
//ob_end_clean();
//ob_end_flush();
ob_start();
//echo "notfound";
print "notfound";
ob_end_flush();
//ob_end_clean();
// clear out the session vars
$_SESSION['zer'] = "";
$_SESSION['modify'] = "";
return;
}
else
{
ob_end_clean();
ob_start();
//echo "found";
print "found";
ob_end_flush();
//ob_end_clean();
$_SESSION['zer'] = $zer;
$_SESSION['modify'] = $modify;
return;
}

I solved this. One of the team members, at some point, stuck a var_dump way up in the source file and I didn't catch it until just now. I commented out the var_dump() and voila, the responseText is as expected, and I eliminated all the php buffer function calls as well.

Related

How do I get value from SQL using AJAX

I know how to pass data from JS to PHP using AJAX, but have no idea how to select data to JS from db using AJAX+php.
I tried to find examples of it but nothing clear found.
Could anyone show me how can I get data from SQL? How I tried:
js function
getdata() {
// ?
var result // I want result to store here
var data = new FormData();
data.append('somekey', 'somevalue');
// AJAX CALL
var xhr = new XMLHttpRequest();
// query for getting some data from SQL
xhr.open('POST', "../php/get_answer.php", true);
xhr.onload = function(){
result = this.response // I presume that I can get result here
};
xhr.send(data);
console.log("RESULT GETTING JSON")
console.log(result)
}
get_answer.php
<?php
include("config.php");
$con = setConnection();
$id = $_COOKIE["id"];
$query = "SELECT results FROM `survey_results` WHERE user_id='$id'";
$n = mysqli_query($con, $query);
$results = 0;
while ($row = mysqli_fetch_assoc($n)) {
$results = $row['results'];
}
// return results ?
$con->close();
?>
In your php file, you can return your data as JSON string.
To do this, tell the client it's json by settings the response header to
header('Content-Type: application/json');
and return the results or data with
echo json_encode($data);
For the Javascript part, XMLHttpRequest is now an old way to make Ajax request but it's a good start to learn.
Fisrt, in your code you have to check if XMLHttpRequest is available in the navigator and try to use the old IE fashion way if not. To do this:
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
now you have your object so you have to set a listener witch listen for change in the state of XMLHttpRequest. If all seems ok the result go there:
xhr.onreadystatechange = function()
{
console.log("Wait server...");
if(xhr.readyState == 4) // 4 : request finished and response is ready
{
if(xhr.status == 200) // HTTP OK
{
console.log("Got data!");
result=xhr.responseText; // or result = JSON.parse(xhr.responseText) to have your data as js object
//It's here you have to modify your dom to show your data, change a variable, etc...
} ;
else // bad http response header like forbiden, not found, ...
{
console.log("Error: returned status code", xhr.status, xhr.statusText);
}
}
};
now you can set the URI and send your request:
xhr.open("GET", "../php/get_answer.php", true);
xhr.send(null)
;
If you want more informations about states and status, have a look at XMLHttpRequest Object Methods

ajax gets empty responseText once piping intermediate data to python at backend

The background is, frontend passed an id back to backend and backend uses the id to extract information from database. The extracted data need further processing at backend and then gets sent back to frontend.
Here is the front end code:
html:
<!DOCTYPE html>
<html>
<head>
<title>Test!</title>
<meta charset="utf-8">
<script src="loadPage.js">
</script>
</head>
<body onload = "loadPage()">
<div id="stack"><p>test part</p>
</div>
</body>
</html>
js:
function __getParameters() {
var parm = {};
var url = window.location.href;
var pairs = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i].split('=');
parm[pair[0]] = pair[1];
}
return parm;
}
function __loadData(star) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// var data = JSON.parse(xmlhttp.responseText);
console.log(xmlhttp.responseText);
if (xmlhttp.responseText == "") {
document.getElementById("stack").innerHTML = "f*ck";
} else {
document.getElementById("stack").innerHTML = xmlhttp.responseText;
}
}
}
var url = "getXML.pl";
url = url + "?STAR=" + star;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function loadPage() {
var parm = __getParameters();
// document.getElementById("stack").innerHTML = parm["STAR"];
if (parm == undefined) {
// wrong url error page
} else if (parm['STAR'] == undefined) {
// missing star error page
} else if (parm['user' == undefined]) {
// missing user id error page
} else {
var star = parm["STAR"];
var user = parm["user"];
__loadData(star);
}
}
The backend uses perl to extract data from database, and it will print the output to stdout. The output is a XML in string form. Then I must use an existed python script to process the extracted data.
However, the server seems not support python (But the server can run python if I directly run python scripts on it. The reason for my statement is that I wrote a python cgi and I got a 500 error, while the perl cgi is ok. I'm sure the python script is correct since it can run directly on the server. I have no access to error log and I cannot modify the config file of the server).
So I piped the output of the perl script to python, and run it using 'system()'. The python script will output a processed string to stdout.
Here is the backend scripts:
perl script:
#!/depot/perl-5.14.2/bin/perl
# extract posted data
local ($buffer, #pairs, $pair, $name, $value, %FORM);
$ENV{"REQUEST__METHOD"} =~ tr/a-z/A-Z/;
if ($ENV{"REQUEST_METHOD"} eq "POST") {
read(STDIN, $buffer, $ENV{"CONTENT_LENGTH"});
} else {
$buffer = $ENV{"QUERY_STRING"};
}
#pairs = split(/&/, $buffer);
foreach $pair (#pairs) {
($name, $value) = split(/=/, $buffer);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$star = $FORM{STAR};
print "Content-type:text/html\n\n";
my $cmd = "***/sq_star.pl --xml --star_id " . $star;
$cmd = $cmd . " | ***/python parseXML.py";
system($cmd);
the sq_star.pl (I just remove the path here and replace it with ***) near the end of perl script is just an existed script that will extract data from database. And parseXML.py is an existed script which does a lot to the input string.
The strange thing is, the responseText is always an empty string. I tried to run the perl script directly on the server, it can print expected results. And if I remove $cmd = $cmd . " | ***/python parseXML.py";, the responseText will be the data extracted from the database.
What I have tried for now:
1. I wrote a simple test python with just one line of print. Still empty response
2. I tried to store the output as $output =`$cmd`; and print $output; in the perl script, still empty.
3. I tried to store the original data in a txt and let the python read from the txt. Still empty
It seems that that data processed by python just cannot be sent back .....
-------------------update----------------
It seems to be the problem of the server. I guess the server is not set to support python so if I directly send requests to a python script on backend, there will be 500 error. But somehow my way, i.e., calling python in perl, gets around the error, but still the python just doesn't work... Just my guess
I found the problem. It is because the interpreter I specified cannot be found by the server. system(...) line actually doesn't run at all. The reason that I didn' t see any error is because system() hides the error for me. Actually the return value of system() is -1, which means something wrong. I should have checked the return value

how do I access the object the object i sent to the server file

//Sent an ajax http post request to a php file on the server, the post //request is a simple object.
var xhr = new XMLHttpRequest();
var person = {
"firstName" : "Adebowale",
"lastName" : "Johnson",
"ago" : 43
}
xhr.open("POST","phfile.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
var status = xhr.status;
if((status >= 200) && (status < 300) || (status === 304)) {
alert(xhr.responseText);
}
}
};
xhr.send(JSON.stringify(person));
//if I do alert(xhr.responseText);
//I get object{} from the browser.
//On the server, using php, how do I access the object, if I do echo or //print_r, I get the empty object --- object{} with none of the properties.
//As you can tell from the tone of my question, am still very new to all //these, am just trying to learn please.
//on my phfile.php, I set up the following php code...
<?php
print_r
//How do I access the object I sent to this file please
?>
I dont see the need for JSON.stringify(person) in your AJAX request, since all the keys of the Object are already in strings.
Since you are using POST method, you can directly access the object like
print_r ($_POST['person']);
You can read raw POST data using STDIN:
$post_data = fopen("php://input", "r");
$json = fgets($post_data);
$object = json_decode($json);
$firstName = $object->firstName;
$lastName = $object->lastName;
$age = $object->age;
You could simplify all of this by just passing the data as URL-encoded form fields:
xhr.send('firstName=' + encodeURIComponent(person.firstName) + '&lastName=' + encodeURIComponent(person.lastName) + '&ago=' + encodeURIComponent(person.ago);
Then you can just access them as $_POST['firstName'], etc. in PHP.

If statement always proving false when using the $_GET[] global variable set with AJAX

I started learning about AJAX very recently and this little problem seemed to have come out of no where. I wrote an html page that uses this code to create an AJAX connection and send a get request with an id.
function loadXML() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("text").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "textTesting.php?id='first'", true);
xmlhttp.send();
}
In my textTesting.php, just for the sake of testing, I compared incoming variable $_GET[id] with the string I expect to be true, first. But the comparison always seem to fail for some reason.
textTesting.php:
<?php
$output = "";
if(isset($_GET["id"])) {
$output = $_GET["id"];
if($output == 'first'){
$output .= " confirmed";
}
}
echo $output;
?>
Is there a concept of PHP or AJAX that I am missing? When writing this if statement I was expecting 'first confirmed' to become the output.
Please ask any further question if needed.
The value you are passing is 'first' but you are comparing it against first so it doesn't match.
In your query string the quotes are data. In your PHP, the quotes are string delimiters.
Either add quotes to the data in the PHP or remove them from the query string.

AJAX - JSON syntax error

I am working on a project for a client and they want to be able to update a list of costs dynamically depending on the registrants status as member/non-member or student. So I thought AJAX would have been the best way to do this but I am having trouble with my implementations. Every time I send my object I get a syntax error. I have placed the code below.
JavaScript
function checkMember(){
var member = document.getElementById("user_mem_id");
if(member.value == "" || member.value.trim() == ""){
document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
document.getElementById("testError").style.color = "red";
}else{
var json = { "data":[{"membership_id":member.value}]}
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
xmlHttp.open("POST","member_check.php",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("data=" + json);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("testError").innerHTML=xmlHttp.responseText;
console.log(xmlHttp.responseText);
json_last_error;
};
};
}
}
PHP
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data[membership_id];
}
The other issue is that when I try and access the membership "cell" of the data array I get illegal off set string. Thus I thought I had declared my original JSON object incorrectly but I appears (as I have viewed many examples on here and else where) that I have declared that correctly.
I think you need to use stringify in order to perform the post successfully.
var json = { "data":[{"membership_id":member.value}]};
json_data = JSON.stringify(json);
then use json_data in your ajax call.
There are quite a few things wrong with your code. As I stated in my first comment to you, you need to escape your json before you send it in the query string, as json converted to a string, without any special rules applied turns into [object Object], and that isn't valid json, nor is it parsed as such.
To do that, use JSON.stringify(json);. Example:
function checkMember(){
var member = document.getElementById("user_mem_id");
if(member.value == "" || member.value.trim() == ""){
document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
document.getElementById("testError").style.color = "red";
}else{
var json = { "data":[{"membership_id":member.value}]}
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
xmlHttp.open("POST","member_check.php",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("data=" + JSON.stringify(json));
//json turned into proper string
//I should also note, you should url-encode this string if it contains
//any special characters using encodeURIComponent()
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("testError").innerHTML=xmlHttp.responseText;
console.log(xmlHttp.responseText);
//json_last_error; //Commented this out, as it will
//echo an error, causing the script to halt, as it doesn't
//exist.
};
};
}
}
Secondly, you send an object whose key 'data' contains an array of objects.. not a simple object:
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data[membership_id]; // There are many things wrong here
// ^ ^ this is not a constant and likely does not exist.
// |- This is still your string, which doesn't work
}
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $res['data'][0]['membership_id'];
// ^ ^ ^ ^
// | |first item |-string
//The result|-string
}
Hopefully my comments will be self explanatory.. but in case they are not... $res is your decoded array, 'data' is the first position of that array, 0 is the first position of the array at that position, and 'membership_id' is the item you want to access. You access members as strings, indexes as integers.
The basic problem with your code is the ";" terminator when you are defining variable. Check your following line
json = { "data":[{"membership_id":member.value}]}
You haven't put a semicolon at the end. (however it might still work a few times but mostly its an error)
Rather you have written a lot of code too. I would suggest you to use jquery's $.ajax function to simplify your task.
Also in case if you only have membership id in your json data its more easy to create a json object like the one below
var json = {"membership_id" : member.value " } ;
Also you need to send your json data after quoting in string using JSON.stringify(json)

Categories