How to find value (true or false) from AJAX response? - javascript

I have written a script register user. And in the last step I need value true or false from a function to find that email is already existed or not.
function do_register(user_email){
if (!isemailexist(user_email)) {
document.getElementById("error").innerHTML="email is already exist, please change!!";
document.regForm.user_email.focus()
return false;
}
if (user_email=="") {
document.getElementById("error").innerHTML="email is emphy!!";
document.regForm.user_email.focus()
return false;
}
if(document.regForm.user_name.value!=""){ process_register();} }
function isemailexist ()
xmlHttp.onreadystatechange=function () {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var str=xmlHttp.responseText;
var res=JSON.parse(str);
if (res[0]=="no"){
return false;
}
}
haha=xmlHttp.onreadystatechange.test(res[0]); ///I used test(); methode in order to find value true or false
}
I have tried alot but none of them could give me true or fals !
I have updated my script above, I hope it´s better. Some more code:
PHP CODE
if(mysql_num_rows($result)>0){ // email is already exist
$phpArray = array("no","Erroremail is aleady exist");
echo json_encode($phpArray);
}

You're doing things bit too complicated. There's no need of making an array when the response is simply false, as you're already telling the user that the email already exists.
Instead of doing
if(mysql_num_rows($result)>0){ // email is already exist
$phpArray = array("no","Erroremail is aleady exist");
echo json_encode($phpArray);
}
Just do this in your server side.
if(mysql_num_rows($result)>0){ // email is already exist
return false;
}
As you're no longer using an array, your response changes, and you need to adjust your code a little bit. Remove [0] from res[0].
Then your server response will be false, so change
if (res[0]=="no"){
return false;
}
to
if (res==false){
return false;
}
else{
//continue...
}

Related

Parameter passing with Ajax (using deferred and promise) help needed

This is most likely a repeat question since it's a common problem for learners, but I just cant find a to-the-point working solution for the issue (I've been trying to get on top this for ages!):
This works because there's no Ajax:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
function first(){
var bbb;
var test = prompt("enter a number");
if(test == 6){
bbb = true;
return bbb;
} else {
bbb = false;
}
}
function second(){
if(first()){
alert("returned true!!");
} else {
alert("returned false");
}
}
But I can't get this next piece of code to work, because the callback runs before the Ajax call is complete. I know deferred and promise are the modern way to sort callbacks like this, but after reading and watching TONS on the matter, I'm still missing some key logic or syntax and it just won't work for me.
Can someone help me get a working example of deferred in action with the following code? Then from there I'll be able to improve my learning about deferred, but currently I'm getting nowhere.
//-----------------------gets much more confusing with Ajax calls------------------
function firstAjax(){
var check = prompt("number between 1 and 10 to send (6 should return true from PHP...)");
$.post('remote.php',
{
check: check
},function(data) {
var returned = JSON.parse(data);
if(returned == true) {
alert(returned);
return true;
} else {
alert(returned);
return false;
}
});
}
function secondAjax(){
if(firstAjax()){
alert("successfull return");
} else {
alert("return failed"); //callback runs before the post returns...
}
}
Buttons to activate the functions:
<button type="button" onClick="second()">Run Local Javascript only </button>
<button type="button" onClick="secondAjax()">Run Ajax call with param passing</button>
And this is 'remote.php': simple if input = 6 return true.
<?php
$check = $_POST['check'];
if($check == 6){
echo json_encode(true);
} else {
echo json_encode(false);
}
?>
You are doing a asynchronous requests and firstAjax() will return undefined before the response have been received.
You need to define a callback function as a parameter in firstAjax(), and then call this function when the response have been received.
function firstAjax(callback) {
var check = prompt("number between 1 and 10 to send (6 should return true from PHP...)");
$.post('remote',
{check: check},
function (data) {
var returned = JSON.parse(data);
if (returned == true) {
alert(returned);
callback(true);
} else{
alert(returned);
callback(false);
}
});
}
function secondAjax() {
firstAjax(function(result){
if(result){
alert("successfull return");
}else{
alert("return failed");
}
});
}

Form submited two times (ajax with jquery)

i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});

Mistake in transferring between PHP and JavaScript

I have a PHP file and JavaScript file.
JavaScript transfers 3 variables into PHP file, PHP file transfers the result into JavaScript. The process is working and gives me the right result, however as a last action in JavaScript when I checking the result it is give me false instead of true. So please help me to find out what is wrong.
PHP:
if ((isset($_POST['st'])) && (!empty($_POST['st'])))
{
$status=$_POST['st'];
switch($status)
{
case '0': {
break;
}
case "1": {
$login = $_POST['login'];
$pas = $_POST['pas'];
check($login,$pas);
break;
}
}
exit;
}
function check ($login,$pas) {
include "php/log_bd.php";
$result = mysql_query("SELECT * FROM users WHERE Login='$login'",$db); //I know, i know, that it is dangerous in case of SQL injection, but I use it for educational example.
$row = mysql_fetch_array($result);
if (empty($row))
{
exit('er');
}
if ($row['Pas']!= $pas)
{
exit('er');
}
exit(0);
}
JavaScript:
$(document).on("click","input[name=door_open]", function () {
var login = $("input[name=login]").val();
var pas = $("input[name=pas]").val();
$.post("index.php",{ st:1, login:login , pas:pas} ,function(data)
{
alert (data); // I have 'er'
if (data == 'er')
{
alert ("Sorry incorrect data");
return false;
}
else
{alert (data);}
});
return false;
});
So It give me in JavaScript file 'er' result but when I check data == 'er', it told me that it is false.
As was suggested I add some some log console comands

How can I set a javascript boolean variable by a php variable? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 1 year ago.
I have some information from my db that is being loaded onto my page, but I would like to be able to use an if statement regarding the value of this, and then assign a javascript value to be a boolean value. How can I go about this? (at the moment I am just printing the value)
<?php
if ($_SESSION['loggedin'] = true){
print_r($_SESSION['userlevel']); // THIS IS WHAT I WANT TO SPECIFY IN AN IF STATEMENT
}
?>
<script>
var userloggedin = false;
</script>
What I would like to do in pseudocode:
<script>
var userloggedin = false;
function somefunction(){
if (userloggedin == true){
//Do stuff...//
}
}
</script>
Sorry for my lack of knowledge on the subject, I'm only beginning to learn backend web development.
Have you tried searching the forum for any previous posts with regards to parsing PHP variables to javascript?
With a simple search I found a feed relating to parsing PHP variables to JavaScript here:
Get variable from PHP to JavaScript
Anyway, from my understanding of your problem does this serve as a suitable answer?
<?php
if ($_SESSION['loggedin'] == true){
$userLevel = $_SESSION['userlevel'];
$userLoggedIn = true;
}
else {
$userLevel = null;
$userLoggedIn = false;
}
?>
<script type="text/javascript">
var userLoggedIn = "<?php Print($userLoggedIn); ?>";
var userLevel = "<?php Print($userLevel); ?>";
if (userLoggedIn == true) {
if (userLevel == "levelOne") {
//Your code here
}
else if (userLevel == "levelTwo") {
//Your code here
}
else {
//Your code here
}
}
</script>
You can echo bits of Javascript code from PHP, like this:
<script>
var userloggedin = <?php echo ($_SESSION['loggedin'] ? 'true' : 'false'); ?>;
</script>
First change your if statement to use == double equal signs if you want the expression to work as expected. Then you can simply echo a variable into javascript as in example below:
Simple solution would be similar to:
<?php
if ($_SESSION['loggedin'] == true){
$logged_in = "true";
} else {
$logged_in = "false";
}
?>
<script>
var userloggedin = <?php echo $logged_in;?>;
</script>
You can set a javascript variable with a php value by:
<script>
var jsVar='<?php echo $phpVar ?>';
</script>
A simple solution would be just to echo variable value in script tag. But this is unsafe, because variable is global, meaning it can be modified in client-side console.
Better solution would be an ajax request and php script that returns some response, this way the variable is scoped to ajax response function, so it's safe from modifications. Here's an example:
...
echo json_encode($_SESSION['loggedin'] ? 'true' : 'false');
...
In javascript, you can use jquery .get() request:
$.get("userLoggedIn.php", function(data) {
var response = JSON.parse(data);
if(data === true) {
// user is logged in
}
else {
// not logged in
}
});
If it's important that this functionality is handled before anything else, an synchronous ajax request:
$.ajax({
url: "userLoggedIn.php",
async: false, // this makes request synchronous
success: function (data) {
var response = JSON.parse(data);
if (data === true) {
// user is logged in
} else {
// not logged in
}
});
Synchronous request means that client will wait for request to finish before doing anything else. It's not recommended to be used a lot, but sometimes it's the only way to go about.

How can I use the results of various ajax requests in another function?

I have been programming a registration form with ajax validation. The way I have it set up is in my js file, I have listeners that fire when the content of the field is changed. They send the data to the server, and the server makes sure it's valid and sends back its response in the form of a JSON object. I then read the values of the JSON object to output potential error messages.
I won't copy and paste the entire files, just one example:
$(document).ready(function() {
// USERNAME VALIDATION LISTENER
$("#regUsername").change(checkName);
}
and then the checkName function looks like this, it sends my ajax request:
function checkName() {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "nameAvail",
username: $("#regUsername").val()
},
success: function(data) { // execute on success
var json = jQuery.parseJSON(data);
if (json.success) { // if usernames do match
$("#usernameAvailiability").removeClass().addClass('match');
$("#usernameAvailiability").text(json.msg);
} else { // if the user has failed to match names
$("#usernameAvailiability").removeClass().addClass('nomatch');
$("#usernameAvailiability").text(json.msg);
}
}
});
}
And depending on the response, it updates a span that tells the user if the input they wrote is valid or not.
The server validates with this part of the php file:
if(!isset($_POST['request'])) { // do nothing if no request was provided
print("no request provided");
} else { //ELSE request has been provided
if ($_POST['request'] == "nameAvail") { // if the request is to check if the username is valid
$response = array("success" => false, "msg" => " ", "request" => "nameAvail");
// CHECK USER NAME AVAILIABILITY CODE
if (!isset($_POST['username']) || empty($_POST['username'])) { // if no username is entered
$response['success'] = false;
$response['msg'] = "No username provided";
} else { // if a username has been entered
$username = $dbConn->real_escape_string($_POST['username']);
if (!ctype_alnum($username)) { // Make sure it's alpha/numeric
$response['success'] = false;
$response['msg'] = "username may only contain alpha numeric characters";
} elseif (strlen($username) < 4) { // make sure it's greater than 3 characters
$response['success'] = false;
$response['msg'] = "username must be at least 4 characters long.";
} elseif (strlen($username) > 20) { // make sure it's less than 26 characters
$response['success'] = false;
$response['msg'] = "username can be up to 20 characters long.";
} else { // make sure it's not already in use
$query = $dbConn->query("SELECT `id`, `username` FROM `users` WHERE `username` = '"
. $username . "' LIMIT 1");
if ($query->num_rows) { // if the query returned a row, the username is taken
$response['success'] = false;
$response['msg'] = "That username is already taken.";
} else { // No one has that username!
$response['success'] = true;
$response['msg'] = "That username is availiable!";
}
}
}
print(json_encode($response));
}
What I'd like to do now is create a function in my javascript for the register button. But I need to make sure all the forms are validated first.
I'm not sure what my options are. What I'd LIKE to do is somehow be able to recycle the code I've already written in my PHP file. I don't want to write out an entirely new if($_POST['request'] == "register") clause and then copy and paste all the validation code to make sure the input is valid before I insert the registrant's data into the database. It seems really repetitive!
I know I could check to see if all the spans on the page were set to 'match', but that could easily be tampered with and blank forms could be submitted.
so far, my register button function looks like this:
function register() {
if ( NEED SOME KIND OF CLAUSE HERE TO CHECK IF ALL THE FIELDS ARE VALID) {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "register",
username: $("#regUsername").val(),
password: $("#regPassword").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sQuest: $("#securityQuestion").val(),
sAns: $("#securityAnswer").val(),
ref: $("#referred").val()
}, success: function(data) {
var json = jQuery.parseJSON(data);
console.log(json);
$("#regValid").removeClass();
$("#regValid").text("");
}
}); //AJAX req done
} else {
$("#regValid").removeClass().addClass('nomatch');
$("#regValid").text("One or more fields are not entered correctly");
}
return false;// so that it wont submit form / refresh page
}
I would really appreciate some help, I've spent the last few hours scouring StackOverflow for an answer, but I can't seem to get anything to work. Will I have to duplicate code in my PHP file or is there a more elegant way to handle this?

Categories

Resources