hi i have some ajax coding in which the if condition is not at all working, whenever the program executes else statement only works even the program satisfies the if statement.
<script type="text/javascript">
function CheckDetails()
{
var http = false;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
var rid = document.new_booking.ph_number.value;
http.onreadystatechange = function() {
if (http.readyState == 4) {
var str_d = http.responseText;
if (str_d == "no") {
document.getElementById('cus_name').focus();
} else {
var str_details = http.responseText;
var arr_details = str_details.split("~");
document.new_booking.cus_name.value = arr_details[0];
document.new_booking.pick_aline1.value = arr_details[1];
document.new_booking.pick_aline2.value = arr_details[2];
document.new_booking.pick_area.value = arr_details[3];
document.new_booking.pick_pincode.value = arr_details[4];
document.new_booking.drop_aline1.focus();
}
}
}
http.open("GET", "ajax.php?evnt=det&rid=" + rid);
http.send();
}
</script>
and its ajax.php file is given below
<?php
if ($_GET['evnt'] == 'det') {
$rid = $_GET['rid'];
include("configure.php");
$select = mysql_query("select * from new_booking where ph_number = '$rid'");
$count = mysql_num_rows($select);
if ($count > 0) {
$row = mysql_fetch_array($select);
echo $row['cus_name']
. "~" . $row['pick_aline1']
. "~" . $row['pick_aline2']
. "~" . $row['pick_area']
. "~" . $row['pick_pincode']
. "~" . $row['drop_aline1']
. "~" . $row['drop_aline2']
. "~" . $row['drop_area']
. "~" . $row['drop_pincode'];
} else {
echo "no";
}
}
?>
You can open your page with Chrome (or Chromium) and then debug your javascript code using builtin debugger (Ctrl+Shift+I, "Console" tab). I guess you will see some JS errors there.
Basically, your code works OK (at least when I removed all database access from it, since I don't have your DB).
If you don't like Chrome, use Firefox and FireBug extension. On 'Network' page you can see that your ajax request was executed (or not executed).
If I had to guess, I would say that some whitespace is sneaking into your AJAX response somewhere. Because "no " isn't equal to "no", it is always hitting your else branch.
You might consider sending back a whitespace-agnostic value. You could rewrite the whole mess to use JSON, which would require a lot less work on both ends:
// PHP:
if ($_GET['evnt'] == 'det') {
$rid = $_GET['rid'];
include("configure.php");
$select = mysql_query("select * from new_booking where ph_number = '$rid'");
$count = mysql_num_rows($select);
if ($count > 0) {
$row = mysql_fetch_array($select);
// YOU PROBABLY WANT TO WHITELIST WHAT YOU PASS TO JSON_ENCODE
echo json_encode($row);
} else {
echo json_encode([ "error" => "no" ]);
}
}
// js:
http.onreadystatechange = function() {
if (http.readyState == 4) {
var str_d;
try {
str_d = JSON.parse(http.responseText);
} catch(e) {
str_d = false;
}
if (str_d && str_d.error === "no") {
document.getElementById('cus_name').focus();
} else {
document.new_booking.cus_name.value = str_d.pick_aline1;
document.new_booking.pick_aline1.value = str_d.pick_aline2;
document.new_booking.pick_aline2.value = str_d.pick_area;
// etc...
}
}
}
I was having similar problem. This worked for me.
if (str_d.replace(/^\s+|\s+$/g, '') == "no")
Related
I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.
I'm trying to load an xml file using ajax. I tried to modify the example of W3Schools
<html>
<head>
<script>
function showBus(str) {
if (str == "") {
document.getElementById("txtHint").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 == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getbus.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>Select your bus route:
<select name="NUMBER" onchange="showBus(this.value)">
<option value="">Select a Bus:</option>
<option value="102">102</option>
</select>
<div id="txtHint"><b>Bus info will be listed here...</b>
</div>
</form>
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("routes.xml");
$x = $xmlDoc->getElementsByTagName('NUMBER');
for ($i = 0; $i <= $x->length - 1; $i++) {
//Process only element nodes
if ($x->item($i)->nodeType == 1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y = ($x->item($i)->parentNode);
}
}
}
$BUS = ($y->childNodes);
for ($i = 0; $i < $BUS->length; $i++) {
//Process only element nodes
if ($BUS->item($i)->nodeType == 1) {
echo("<b>" . $BUS->item($i)->nodeName . ":</b> ");
echo($BUS->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
XML File:
<TT>
<BUS>
<NUMBER>102</NUMBER>
<DEPARTING_STOP>102</DEPARTING_STOP>
<DESTINATION>102</DESTINATION>
<TIME>102</TIME>
</BUS>
</TT>
This is what I get when I select the bus number from drop down menu:
Select your bus route:
load("routes.xml"); $x=$xmlDoc->getElementsByTagName('NUMBER'); for ($i=0; $i<=$x->length-1; $i++) { //Process only element nodes if ($x->item($i)->nodeType==1) { if ($x->item($i)->childNodes->item(0)->nodeValue == $q) { $y=($x->item($i)->parentNode); } } } $BUS=($y->childNodes); for ($i=0;$i<$BUS->length;$i++) { //Process only element nodes if ($BUS->item($i)->nodeType==1) { echo("" . $BUS->item($i)->nodeName . ": "); echo($BUS->item($i)->childNodes->item(0)->nodeValue); echo("
"); } } ?>
Open <yourserver>getbus.php?q=102 in your browser. Do you get something like this:
NUMBER: 102
DEPARTING_STOP: 102
DESTINATION: 102
TIME: 102
If you get something like:
load("routes.xml"); $x=$xmlDoc->getElementsByTagName('NUM...
I'd personally think you are not running an http server but are excuting everything locally.
Your getbus.php file is a php sourceode file that needs to be interpreted by a php processor. This is all being done by a webserver (if correctly configured). To get started you can use xampp ( https://www.apachefriends.org/ ) which has all the necessary modules for your sample. It is a preconfigured server to run php.
Then put all your files in the according htdocs folder in your xampp installation and the sample should work.
EDIT:
As it seems the getbus.php most of the time responses with an empty response. The problem apears to be the load(file) method by domdocument. loadXML seems to work better. So this always works for me:
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML("<TT>
<BUS>
<NUMBER>102</NUMBER>
<DEPARTING_STOP>102</DEPARTING_STOP>
<DESTINATION>102</DESTINATION>
<TIME>102</TIME>
</BUS>
<BUS>
<NUMBER>103</NUMBER>
<DEPARTING_STOP>104</DEPARTING_STOP>
<DESTINATION>105</DESTINATION>
<TIME>107</TIME>
</BUS>
</TT>");
$x = $xmlDoc->getElementsByTagName('NUMBER');
for ($i = 0; $i <= $x->length - 1; $i++) {
//Process only element nodes
if ($x->item($i)->nodeType == 1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y = ($x->item($i)->parentNode);
}
}
}
$BUS = ($y->childNodes);
for ($i = 0; $i < $BUS->length; $i++) {
//Process only element nodes
if ($BUS->item($i)->nodeType == 1) {
echo("<b>" . $BUS->item($i)->nodeName . ":</b> ");
echo($BUS->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
note that the entire XML file is now inside the PHP file as a string. To make it working the way you want you could try to load the file contents into a string using file() or file_get_contents() in the php file.
I have an AJAX session that gets called once on page load and again after a click. It's not getting a readystate change the second time so I decided to test it by putting an alert box in the function. The alert box shows up on the page load. But on the click it doesn't show up - get this - even though the PHP side executes. More puzzling is that if I try to measure the readystate it never appears (not 0,1,2,3 or 4 - an alert box won't even show up), and I don't get an return text.
What I ultimately am trying to achieve is for the xmlhttp.responseText to return a value like it does on the page load. What am I missing?
JavaScript:
function ajaxSession()
{
alert();
xmlhttp = undefined;
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)
{
z = xmlhttp.responseText;
}
}
}
function stateCheck()
{
ajaxSession();
xmlhttp.open('POST', thisurl + '/favoritecheck.php',false);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send("0=" + perform + "&1=" + thisplace + ",&2=" + thisusername);
}
function firstCheck()
{
perform = 0;
stateCheck();
if (z == 'found')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if ( z == 'nouser')
{
perform = 1;
stateCheck();
}
}
function heartCheck()
{
perform = 2;
stateCheck();
if (z == 'added')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if (z == 'subtracted')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-off.png";
document.getElementById("favtext").innerHTML="Add to your favorites.";
}
}
if (loggedin == 1)
{
document.writeln('<img id="favorite" style="cursor: pointer;" onclick="heartCheck()" src="http://www.********.com/images/favorite-off.png" alt="Favorite" />'
+ '<br />'
+ '<div id="favtext" style="color: #D20425;">'
+ 'Add to your favorites.'
+ '</div>');
firstCheck();
} else if (loggedin == 0)
{
document.writeln('<img id="favorite" style="cursor: pointer;" src="http://www.********.com/images/favorite-off.png" alt="Favorite" />'
+ '<br />'
+ '<div id="favtext" style="color: #D20425;">'
+ '<a style="color: #800000; font-weight: bold;" href="' + thisurl + '/wp-login.php">Log in</a> to add favorites.'
+ '</div>');
}
PHP:
<?php
include('connect.php');
$salt = "********";
$perform = $_POST[0];
$place = $_POST[1];
$user = $_POST[2];
$usercrypt = crypt(md5($user),$salt);
$placeid = trim($place,",");
function checkNow()
{
global $usercrypt;
global $place;
global $conn;
$urow = mysqli_query($conn, "SELECT Users.User FROM Users WHERE Users.User='" . $usercrypt . "';");
if (mysqli_num_rows($urow) > 0)
{
$favcheck = mysqli_query($conn, "SELECT Users.Favorites FROM Users WHERE Users.User='" . $usercrypt . "';");
$favcheck = mysqli_fetch_array($favcheck);
$favcheck = $favcheck[0];
if (strpos($favcheck, $place) !== false)
{
$answer = 'found';
}
else
{
$answer = 'notfound';
}
}
else
{
$answer = 'nouser';
}
return array($answer,$favcheck);
unset($answer);
}
if ($perform == "0")
{
$sendback = checkNow();
echo $sendback[0];
unset($sendback);
}
if ($perform == "1")
{
global $usercrypt;
global $conn;
mysqli_query($conn, "INSERT INTO Users (User) VALUES ('" . $usercrypt . "')");
}
if ($perform == "2")
{
$sendback = checkNow();
global $place;
global $placeid;
global $usercrypt;
global $conn;
$currentnum = mysqli_query($conn, "SELECT Places.Favorites FROM Places WHERE Places.PlaceID=" . $placeid);
$currentnum = mysqli_fetch_array($currentnum);
$currentnum = $currentnum[0];
if ($sendback[0] == 'found')
{
$currentnum--;
$change = str_replace($place,'',$sendback[1]);
mysqli_query($conn, "UPDATE Users SET Favorites='" . $change . "' WHERE User = '" . $usercrypt . "'");
mysqli_query($conn, "UPDATE Places SET Places.Favorites=" . $currentnum . " WHERE Places.PlaceID =" . $placeid);
$answer = 'subtracted';
}
if ($sendback[0] == 'notfound')
{
$currentnum++;
$change = $sendback[1] . $place;
mysqli_query($conn, "UPDATE Users SET Favorites='" . $change . "' WHERE User = '" . $usercrypt . "'");
mysqli_query($conn, "UPDATE Places SET Places.Favorites=" . $currentnum . " WHERE Places.PlaceID =" . $placeid);
$answer = 'added';
}
return $answer;
unset($answer);
}
unset($_POST);
?>
The value of z will be evaluated before the xmlhttp object receives the readystate change. You need to put all the code that deals with the returned value into a onreadystatechange function itself, since that is the only function which is guaranteed to be called after you receive an asynchronous response.
You could do something like this:
var xmlhttp = false;
// The rest of your code, but remove the `onreadystatechange` assignment from ajaxSession()
// ...
// ...
function heartCheck() {
perform = 2;
stateCheck();
xmlhttp.onreadystatechange = function() {
z = xmlhttp.responseText;
if (z == 'added')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if (z == 'subtracted')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-off.png";
document.getElementById("favtext").innerHTML="Add to your favorites.";
}
}
}
And you'd need to do a handler like that for each time you want to evaluate the AJAX response.
It'd also be most clear to declare the global variables at the beginning of the script like I did above--as #jeroen mentions, it's not explicitly required, but it's good practice and will help you keep track of scope. It's confusing that z is only defined inside the xmlhttp.onreadystatechange function, yet you're using it throughout the script globally. So a simple tip is to put var z = '' at the beginning of your JavaScript to make your intentions clearer (both to yourself and to others who may be viewing your code :))
This is a bit of a mess: You are mixing asynchronous and synchronous javascript in a way you will never know what is what and in what state you are in. Apart from that you are using global javascript variables that you reset and overwrite synchronously while you are using them for your asynchronous requests.
Check for example your firstCheck() function: That will reset your xmlhttp variable (in another function...) and make a asynchronous request but you are already checking for the return value of your asynchronous request in the next line when you are checking the z value. That value (another global variable...) will only be set when your asynchronous call finishes so that logic has no place there.
You need to rethink your architecture keeping in mind that each time you make an ajax request, the result will not be available right away, a separate event will fire - a readyState change - and only then can you do the things you want to do with the returned information from the server.
For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.
I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});