Send Flag from PHP to JavaScript - javascript

I want to initialize a flag in a condition in PHP and send it to be read by JavaScript.
At the moment, I have this code :
PHP
if ($totalResults > MAX_RESULT_ALL_PAGES) {
$queryUrl = AMAZON_SEARCH_URL .
$searchMonthUrlParam .
$searchYearUrlParam .
$searchTypeUrlParam .
urlencode( $keyword ) .
'&page=' . $pageNum;
} else {
$queryUrl = AMAZON_TOTAL_BOOKS_COUNT .
$searchMonthUrlParam .
$searchYearUrlParam .
$searchTypeUrlParam .
urlencode($keyword) .
"&page=" . $pageNum;
$flagQuery = TRUE;
echo $flagQuery;
}
JavaScript
<script>
function getFlagValue() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 && xmlHttp.status==200) {
alert(xmlHttp.responseText);
}
};
xmlHttp.open("GET","getAmazonResult.php",true);
xmlHttp.send();
}
var flagQuery = new Boolean();
flagQuery = getFlagValue();
alert(flagQuery);
</script>
I can't seem to retrieve the Flag in JavaScript.

I found out why my Flag displays Undefined.
It is simply that to make a alert (flagQuery) a boolean does not function.
I combine my code with that of Jan Turon, and this is achieved
function getFlagValue() {
var xmlHttp = new HmlHttpRequest();
xmlHttp.onload = function() {
if (xmlHttp.status==200) yourCustomHandler(xmlHttp.responseText);
};
xmlHttp.open("GET","getAmazonResult.php",true);
xmlHttp.send();
}
function yourCustomHandler(response) {
flagQuery = response;
alert(flagQuery);
}
flagQuery = getFlagValue();
if (flagQuery = true) {
alert ("Flag = TRUE");
}
else {
alert ("Flag = FALSE");
}
And now I see if the flag is true or false

Just uncomment the echo $flagQuery from your PHP code and change it to
echo $flagQuery ? 1 : 0;
since false echoes nothing.
A stands for asynchronous in AJAX. Therefore in your javascript you need to set the flag var in onreadystatechange event:
function getFlagValue() {
var xmlHttp = new HmlHttpRequest();
xmlHttp.onload = function() {
if (xmlHttp.status==200) yourCustomHandler(xmlHttp.responseText);
};
xmlHttp.open("GET","getAmazonResult.php",true);
xmlHttp.send();
}
function yourCustomHandler(response) {
flagQuery = response;
alert(flagQuery);
}
Your code will also work if you make it synchronous by setting false as the third parameter in:
xmlHttp.open("GET","getAmazonResult.php",false)
and if you actualy return the responseText from the getValue() function, but I don't recommend it since the net communication may fail and you javascript then freezes.
BTW: you don't need to bother with ActiveXObject legacy code, see here. Also have a look at XHR2: I updated your JS code for XHR2 standard in my answer), as you see, it is much shorter.
Oh, and there is a minor mistake in your PHP, you need to echo the flagQuery everytime:
if ($totalResults > MAX_RESULT_ALL_PAGES) {
$queryUrl = ...
$flagQuery = FALSE;
} else {
$queryUrl = ...
$flagQuery = TRUE;
}
echo $flagQuery ? 1 : 0; // outside of the if-else block

Related

XMLHttpRequest with php will not work

I've been trying to get this solved for 2 weeks now and still have no success.
JavaScript:
var quotenum = 0;
var xmlhttp = null;
var rt = "";
function ChangeQuote() {
quotenum++;
xmlhttp = null;
//alert("quotenum= "+quotenum);
if (quotenum === 0) {
document.getElementById("quote").innerHTML = "";
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 === XMLHttpRequest.DONE && xmlhttp.status === 200) {
rt = xmlhttp.responseText;
//alert("quote= "+rt);
alert("request number= " + xmlhttp.length);
document.getElementById("quote").innerHTML = rt;
}
};
xmlhttp.open("Get", "getquote.php?q=" + quotenum, false);
//xmlhttp.open("GET", "getquote.php?XDEBUG_SESSION_START=netbeans-xdebug&q=" + quotenum, false);
xmlhttp.send();
//var thediv = document.getElementById("quote");
return false;
}
PHP:
error_reporting(E_ERROR | E_PARSE);
$q="";
$q = intval($_GET['q']);
$link=mysqli_connect("localhost","root","sequence","babylon");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="SELECT quotetext FROM quote where quotenum='".$q."'";
$show=mysqli_query($link,$query) or die ("Error");
while($row=mysqli_fetch_array($show)){
echo $row["quotetext"];
}
Can anyone see anything wrong with this?
Using WAMP I can see the correct result when I run the PHP file in a browser.
I also try to use Jquery instead.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var quotenum = 0;
// var xmlhttp = null;
// var rt = "";
function ChangeQuote() {
quotenum++;
$.ajax({
url: "getquote.php?q="+quotenum,
method: "get",
data: {
q: quotenum
}
}).done(function (data) {
alert(data);
document.getElementById("quote").innerHTML = data.quotetext;
});
return false;
}
</script>
The only noticable error I see is you inlining your js with the script tag that has a src attribute.
HTML 4.01 Specification:
The script may be defined within the
contents of the SCRIPT element or in
an external file. If the src attribute
is not set, user agents must interpret
the contents of the element as the
script. If the src has a URI value,
user agents must ignore the element's
contents and retrieve the script via
the URI.

Detect arrays with ajax

I have a document on PHP retrieving the postal codes via form and it gives back an array. If the postal code is used on more than one citie, it creates a multidimensional array, otherwise it stores everything just in one.
I have three scenarios:
If the postal code doesn't exist it gives an array with 2 values "Doesn't exist" and output it on the form.
If the postal code exists it gives you an array with the city and the state and output them on the form.
If the postal code exists and is used on more than one citie it stores every result on an array and all of them into a another array (Array => Array [0] => Array([city]=>city1 [state]=>state1) Array [1] => Array([city]=>city2 [state]=>state2)... and then outputs a popup.
I managed to do everything but I still have some problems. Here's my code:
Script PHP
include_once('../../../connect.html');
//perform lookup
$title = ($_GET['postal_code']);
$statement = $connection->prepare ("SELECT city, state FROM cities, states WHERE cities.state_id = states.state_id AND cities.postal_code = ?");
$statement->execute(array($title));
$statement->setFetchMode(PDO::FETCH_ASSOC);
$items = array();
while ($r = $statement->fetch()) {
//$arrayName = array($r = $statement->fetch());
$items[] = $r;
}
if (count($items) == '1'){
$newArray = $items[0];
echo $newArray['city'].",".$newArray['state'];
}elseif (count($items) == '0'){
echo "Doesn't exist".","."Doesn't exist";
}else{
$varios = array($items);
print_r($varios);
}
AJAX code
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var zipValue = document.getElementById("postal_code").value;
if(zipValue)
{
var url = "get_cities.php";
var param = "?postal_code=" + escape(zipValue);
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
if( ajax.responseText.length ) {
if (ajax.responseText[2]) {
centerPopup();
loadPopup();
}
citystatearr = ajax.responseText.split(",");
city.value = citystatearr[0];
state.value = citystatearr[1];
}else{
}
}
}
Problems are:
It calls the function centerPopup and loadPopup everytime, regardless the result (it should be called only when the PHP script gives back a multidimensional array.
I don't know how to detect via AJAX when the script is sending the normal array or the multidimensional array.
It's basically those two problems but solving one, the other one is solved.
Any help is appreciated!!
ajax.responseText is a string, in JavaScript string[n] return the nth letter of the string.
You must encode your data in PHP then decode it in JavaScript, the best way to do it is with JSON. Both PHP and JavaScript provide support for JSON (json_encode/json_decode and JSON.stringify/JSON.parse) so it's easier!
So this is the code in JS:
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var zipValue = document.getElementById("postal_code").value;
if(zipValue)
{
var url = "get_cities.php";
var param = "?postal_code=" + escape(zipValue);
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
if( ajax.responseText.length ) {
try {
var data = JSON.parse(ajax.responseText); // = $items
}
catch(e) {
//json parse error
}
if (data[2]) {
centerPopup();
loadPopup();
}
citystatearr = ajax.responseText.split(",");
// ^^^^^^ I think you'll need to change this
city.value = citystatearr[0];
state.value = citystatearr[1];
}else{
}
}
}
And PHP :
include_once('../../../connect.html');
//perform lookup
$title = ($_GET['postal_code']);
$statement = $connection->prepare ("SELECT city, state FROM cities, states WHERE cities.state_id = states.state_id AND cities.postal_code = ?");
$statement->execute(array($title));
$statement->setFetchMode(PDO::FETCH_ASSOC);
$items = array();
while ($r = $statement->fetch()) {
//$arrayName = array($r = $statement->fetch());
$items[] = $r;
}
if (count($items) == '1'){
$newArray = $items[0];
echo $newArray['city'].",".$newArray['state'];
}elseif (count($items) == '0'){
echo "Doesn't exist".","."Doesn't exist";
}else{
$varios = array($items);
die(json_encode($varios));
}

window.location not firing after ajax event

I'm not sure if this is related to an ajax call or not. I'm very new to Ajax, and so I suspect it is the cause.
I run the following javascript:
function GetXmlHttpObject() {
"use strict";
var objXMLHttp = null;
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
objXMLHttp = new window.ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp;
}
function delete_director(i) {
"use strict";
var r, url;
r = window.confirm("Are you sure you want to disable this director");
url = "ajax.php?task=director&event=delete&UserId=" + i;
if (r === true) {
mdata = new GetXmlHttpObject();
if (mdata === null) {
alert("Browser does not support HTTP Request");
return;
}
mdata.open("GET", url, true);
mdata.send(null);
}
}
And that calls into the following php function:
function deletedirector()
{
$UserId=mysql_real_escape_string($_GET['UserId']);
$query = "update tbl_users set IsDisabled='1' where UserId=".$UserId;
$result = mysql_query($query) OR die('Cannot perform query!');
if ($result) {
error_log("a");
?><script type="text/javascript">window.location='index.php?task=director&success=Director Successfully Deleted.'</script><?
} else {
error_log("b");
?><script type="text/javascript">window.location='index.php?task=director&error=Director Deletion Failed.'</script><?
}
}
The db shows that the director was deleted, and "a" prints in the error log, but the window.location never fires.
The user experience is that the browser prompts for confirmation, and after that - nothing. A javascript console shows now error.
Any ideas?
You already return new object (of XMLHttpRequest API) with function, so you don't need new here
...
if (r === true) {
mdata = GetXmlHttpObject();
...
and try to use onreadystatechange like this
mdata.onreadystatechange = function(){
if (mdata.readyState === 4) {
alert("some text");
} else {
alert(mdata.status);
}
};

xmlhttprequest: "password" from txt-file

I'm new to javascript/ajax and a bit stuck right now.
The assignment is to use only javascript/ajax.
I'm supposed to make a login-form, and when typing in the right password it will display a "secret message". Currently this message is an alert-box.
This is in the script for validating the form input:
var riktigPassord = 'password';
var passord = window.document.passordSkjema.passord.value;
if (passord == riktigPassord ) {
alert("Dette er en hemmelig beskjed");
window.document.passordSkjema.passord.focus();
return true;
}
else {
alert("Innlogging mislyktes. Passord er feil!");
window.document.passordSkjema.passord.focus();
return false;
}
}//slutt på funksjonen her
And this is the code for the form:
<form name="passordSkjema" action="#" method="post"
onSubmit="return validerPassord();">
Passord: <input type="text" name="passord"><br>
<input type="submit" name="knapp">
</form>
I'm supposed to get the password from a txt-file. (still using only javascript)
and in my case, the txt-filename is "password.txt".
I've never done this before, but I think I know how to make a XHR-object... xD
// New XMLHttpRequest-object
function newXHRobjekt() {
try {
XHRobjekt = new XMLHttpRequest(); // Firefox, Opera, ...
} catch(err1) {
try {
XHRobjekt = new ActiveXObject("Microsoft.XMLHTTP"); // Noen IE
} catch(err2) {
try {
XHRobjekt = new ActiveXObject("Msxml2.XMLHTTP"); // Noen IE
} catch(err3) {
XHRobjekt = false;
}
}
}
return XHRobjekt;
}
So.. My question is. How do I use a XHR-object to get use the functions above to check the password-input against password.txt. the file only contains the password (for instance only "12345"). and also I would like to know how to get the "secret message" from another txt-file.
I'm aware that this isn't secure at all, but it's a part of understanding javascript/Ajax, in my classes.
Thanks!
add the following code to the onload event of the body.
var passwordLoaded = false;
var password = "";
var secretMessageLoaded = false;
var secretMessage = "";
var xhr = newXHRobjekt();
xhr.open("GET", "password.txt");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
password = xhr.responseText;
passwordLoaded = true;
}
}
xhr.send(null);
xhr = newXHRobjekt();
xhr.open("GET", "secret_message.txt");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
secretMessage = xhr.responseText;
secretMessageLoaded = true;
}
}
xhr.send(null);
If both passwordLoaded and secretMessageLoaded are set to true you can use the variables password and secretMessage.
Like many of the Javascript APIs XHR object too have an async interface. So you will need to define callback functions to handle the responses:
xmlhttp.open("POST", "http://example.com",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send('my request data');
Search for example on the net. I found a post, a bit old but seem to have good examples.

javascript wont load, no clear error

I have the following code, which will not work. The javascript gives no errors and appears to load fine. but clicking on a link will do nothing. An example of a link is:
Link 1<li>Link 2</li>
and the code:
var xmlHttp
var layername
var url
function update(layer, url) {
var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
//etc
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function updateByPk(layer, pk) {
url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random();
update(layer, url);
}
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write(<?php echo htmlspecialchars(json_encode($row2["ARTICLE_DESC"]), ENT_QUOTES); ?>);
child1.document.close();
}
It may probably be due to the double-quote characters surrounding 'Ed Hardy'. Does this work:
Link 1<li>Link 2</li>
From the wonderful JSLint
You are missing semicolons after these
var xmlHttp
var layername
var url
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
//etc
}
(e) is used 2x, change the second to 'ex'.
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
Try using single quotes for EVERYTHING in JS, and use double quotes for EVERYTING in PHP.
Get Firebug to see if there are any other syntax errors.
Additionally, this line:
child1.document.write(<?php echo htmlspecialchars(json_encode($row2["ARTICLE_DESC"]), ENT_QUOTES); ?>);
Should probably include quotes around the PHP reference, so JavaScript knows what you want it to write:
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
Note that I changed the double-quotes surrounding ARTICLE_DESC to single-quotes as well.

Categories