Returning True/False from PHP to Ajax Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How can I prevent SQL injection in PHP?How to manage a redirect request after a jQuery Ajax callPHP: Delete an element from an arrayAbort Ajax requests using jQueryHow do you parse and process HTML/XML in PHP?Reference — What does this symbol mean in PHP?Returning JSON from a PHP ScriptHow does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?How do I return the response from an asynchronous call?

representation of vector and matrix in latex

Using et al. for a last / senior author rather than for a first author

Around usage results

What is the longest distance a player character can jump in one leap?

Extracting terms with certain heads in a function

Amount of permutations on an NxNxN Rubik's Cube

Dating a Former Employee

Do I really need to have a message in a novel to appeal to readers?

Circuit to "zoom in" on mV fluctuations of a DC signal?

How to answer "Have you ever been terminated?"

First console to have temporary backward compatibility

Do I really need recursive chmod to restrict access to a folder?

Is there any way for the UK Prime Minister to make a motion directly dependent on Government confidence?

Irreducible of finite Krull dimension implies quasi-compact?

Why does the resolve message appear first?

Did MS DOS itself ever use blinking text?

Do square wave exist?

Would "destroying" Wurmcoil Engine prevent its tokens from being created?

Delete nth line from bottom

How come Sam didn't become Lord of Horn Hill?

How to react to hostile behavior from a senior developer?

Why do we bend a book to keep it straight?

Can anything be seen from the center of the Boötes void? How dark would it be?

Maximum summed powersets with non-adjacent items



Returning True/False from PHP to Ajax



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How can I prevent SQL injection in PHP?How to manage a redirect request after a jQuery Ajax callPHP: Delete an element from an arrayAbort Ajax requests using jQueryHow do you parse and process HTML/XML in PHP?Reference — What does this symbol mean in PHP?Returning JSON from a PHP ScriptHow does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?How do I return the response from an asynchronous call?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















The past day's I've been trying to return a true or false boolean to Ajax.



The Process: Someone submit's a form > Send to a PHP file > From PHP, check everything is correct. If yes, return true and echo 'correct'. > Output the result. In this case, it'll have to echo correct. And check if it's true or false.



The problem is, it will always return a false. Even when everything is correct. So when my login is correct, it will return a correct, as I expect. But it won't return a true.



My form:



<form id="loginform" class="col s12" name="loginform" method="post">
<div class="input-field col s12">
<i class="fas fa-user material-icons prefix"></i>
<input id="hn" type="text" class="validate" name="hn">
<label for="hn">Gebruikersnaam</label>
</div>
<div class="input-field col s12">
<i class="fas fa-key material-icons prefix"></i>
<input id="ww" type="password" class="validate" name="ww">
<label for="ww">Wachtwoord</label>
</div>
<button class="mui-btn mui-btn--raised mui-btn--primary" id="forminlog"><i class="fas fa-chevron-right"></i> Inloggen</button>


Ajax:



$("#forminlog").click(function()
$.ajax(
type: 'POST',
data: hn: document.getElementById("hn").value, ww: document.getElementById("ww").value,
url: 'login.php',
success: function(output)
swal(output);
if(output == true)
alert("true");
else
alert("false");


);
event.preventDefault()
);


PHP:



<?php
function login() empty($pww))
echo 'Vul alle velden in';


else
//DATA VANUIT DB
include("connection.php");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT * FROM gebruikers WHERE gebruikersnaam = :gebruiker");
$pdoExec = $sth->execute(array(":gebruiker"=>$pgebruiker));
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
//GEBRUIKERSNAAM
$gebruikersnaam = $result->gebruikersnaam;
//WACHTWOORD
$wachtwoord = $result->wachtwoord;
if(!strcasecmp($pgebruiker, $gebruikersnaam) == 0)
echo 'Verkeerd gebruikersnaam.';

elseif(!password_verify($pww, $wachtwoord) /*strcasecmp($pww, $wachtwoord) == 0*/)
echo 'Verkeerd wachtwoord';

else
echo 'Correcte gegevens.';
return true;
/*session_start();
$_SESSION['gebruiker'] = $gebruikersnaam;
header('Location: veilig.php');*/
//exit;



login();
?>









share|improve this question



















  • 1





    JS script knows nothing about returned values in your php code. JS script gets the output of your php code.

    – u_mulder
    Mar 8 at 18:20







  • 2





    In your php code rather that return true you should write echo true.That will parse by javascript as boolean.

    – Vitthal
    Mar 8 at 18:23











  • I recommend to look at your browser console and see what is the output of your PHP call. Since you would like to output JSON I am pretty sure you should't have echo 'Correcte gegevens.'; before it.

    – Dharman
    Mar 8 at 18:25











  • @suraj thanks, I removed the echo before the return true, and changed that to echo true. Worked

    – Prabh
    Mar 8 at 18:32

















1















The past day's I've been trying to return a true or false boolean to Ajax.



The Process: Someone submit's a form > Send to a PHP file > From PHP, check everything is correct. If yes, return true and echo 'correct'. > Output the result. In this case, it'll have to echo correct. And check if it's true or false.



The problem is, it will always return a false. Even when everything is correct. So when my login is correct, it will return a correct, as I expect. But it won't return a true.



My form:



<form id="loginform" class="col s12" name="loginform" method="post">
<div class="input-field col s12">
<i class="fas fa-user material-icons prefix"></i>
<input id="hn" type="text" class="validate" name="hn">
<label for="hn">Gebruikersnaam</label>
</div>
<div class="input-field col s12">
<i class="fas fa-key material-icons prefix"></i>
<input id="ww" type="password" class="validate" name="ww">
<label for="ww">Wachtwoord</label>
</div>
<button class="mui-btn mui-btn--raised mui-btn--primary" id="forminlog"><i class="fas fa-chevron-right"></i> Inloggen</button>


Ajax:



$("#forminlog").click(function()
$.ajax(
type: 'POST',
data: hn: document.getElementById("hn").value, ww: document.getElementById("ww").value,
url: 'login.php',
success: function(output)
swal(output);
if(output == true)
alert("true");
else
alert("false");


);
event.preventDefault()
);


PHP:



<?php
function login() empty($pww))
echo 'Vul alle velden in';


else
//DATA VANUIT DB
include("connection.php");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT * FROM gebruikers WHERE gebruikersnaam = :gebruiker");
$pdoExec = $sth->execute(array(":gebruiker"=>$pgebruiker));
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
//GEBRUIKERSNAAM
$gebruikersnaam = $result->gebruikersnaam;
//WACHTWOORD
$wachtwoord = $result->wachtwoord;
if(!strcasecmp($pgebruiker, $gebruikersnaam) == 0)
echo 'Verkeerd gebruikersnaam.';

elseif(!password_verify($pww, $wachtwoord) /*strcasecmp($pww, $wachtwoord) == 0*/)
echo 'Verkeerd wachtwoord';

else
echo 'Correcte gegevens.';
return true;
/*session_start();
$_SESSION['gebruiker'] = $gebruikersnaam;
header('Location: veilig.php');*/
//exit;



login();
?>









share|improve this question



















  • 1





    JS script knows nothing about returned values in your php code. JS script gets the output of your php code.

    – u_mulder
    Mar 8 at 18:20







  • 2





    In your php code rather that return true you should write echo true.That will parse by javascript as boolean.

    – Vitthal
    Mar 8 at 18:23











  • I recommend to look at your browser console and see what is the output of your PHP call. Since you would like to output JSON I am pretty sure you should't have echo 'Correcte gegevens.'; before it.

    – Dharman
    Mar 8 at 18:25











  • @suraj thanks, I removed the echo before the return true, and changed that to echo true. Worked

    – Prabh
    Mar 8 at 18:32













1












1








1








The past day's I've been trying to return a true or false boolean to Ajax.



The Process: Someone submit's a form > Send to a PHP file > From PHP, check everything is correct. If yes, return true and echo 'correct'. > Output the result. In this case, it'll have to echo correct. And check if it's true or false.



The problem is, it will always return a false. Even when everything is correct. So when my login is correct, it will return a correct, as I expect. But it won't return a true.



My form:



<form id="loginform" class="col s12" name="loginform" method="post">
<div class="input-field col s12">
<i class="fas fa-user material-icons prefix"></i>
<input id="hn" type="text" class="validate" name="hn">
<label for="hn">Gebruikersnaam</label>
</div>
<div class="input-field col s12">
<i class="fas fa-key material-icons prefix"></i>
<input id="ww" type="password" class="validate" name="ww">
<label for="ww">Wachtwoord</label>
</div>
<button class="mui-btn mui-btn--raised mui-btn--primary" id="forminlog"><i class="fas fa-chevron-right"></i> Inloggen</button>


Ajax:



$("#forminlog").click(function()
$.ajax(
type: 'POST',
data: hn: document.getElementById("hn").value, ww: document.getElementById("ww").value,
url: 'login.php',
success: function(output)
swal(output);
if(output == true)
alert("true");
else
alert("false");


);
event.preventDefault()
);


PHP:



<?php
function login() empty($pww))
echo 'Vul alle velden in';


else
//DATA VANUIT DB
include("connection.php");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT * FROM gebruikers WHERE gebruikersnaam = :gebruiker");
$pdoExec = $sth->execute(array(":gebruiker"=>$pgebruiker));
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
//GEBRUIKERSNAAM
$gebruikersnaam = $result->gebruikersnaam;
//WACHTWOORD
$wachtwoord = $result->wachtwoord;
if(!strcasecmp($pgebruiker, $gebruikersnaam) == 0)
echo 'Verkeerd gebruikersnaam.';

elseif(!password_verify($pww, $wachtwoord) /*strcasecmp($pww, $wachtwoord) == 0*/)
echo 'Verkeerd wachtwoord';

else
echo 'Correcte gegevens.';
return true;
/*session_start();
$_SESSION['gebruiker'] = $gebruikersnaam;
header('Location: veilig.php');*/
//exit;



login();
?>









share|improve this question
















The past day's I've been trying to return a true or false boolean to Ajax.



The Process: Someone submit's a form > Send to a PHP file > From PHP, check everything is correct. If yes, return true and echo 'correct'. > Output the result. In this case, it'll have to echo correct. And check if it's true or false.



The problem is, it will always return a false. Even when everything is correct. So when my login is correct, it will return a correct, as I expect. But it won't return a true.



My form:



<form id="loginform" class="col s12" name="loginform" method="post">
<div class="input-field col s12">
<i class="fas fa-user material-icons prefix"></i>
<input id="hn" type="text" class="validate" name="hn">
<label for="hn">Gebruikersnaam</label>
</div>
<div class="input-field col s12">
<i class="fas fa-key material-icons prefix"></i>
<input id="ww" type="password" class="validate" name="ww">
<label for="ww">Wachtwoord</label>
</div>
<button class="mui-btn mui-btn--raised mui-btn--primary" id="forminlog"><i class="fas fa-chevron-right"></i> Inloggen</button>


Ajax:



$("#forminlog").click(function()
$.ajax(
type: 'POST',
data: hn: document.getElementById("hn").value, ww: document.getElementById("ww").value,
url: 'login.php',
success: function(output)
swal(output);
if(output == true)
alert("true");
else
alert("false");


);
event.preventDefault()
);


PHP:



<?php
function login() empty($pww))
echo 'Vul alle velden in';


else
//DATA VANUIT DB
include("connection.php");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT * FROM gebruikers WHERE gebruikersnaam = :gebruiker");
$pdoExec = $sth->execute(array(":gebruiker"=>$pgebruiker));
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
//GEBRUIKERSNAAM
$gebruikersnaam = $result->gebruikersnaam;
//WACHTWOORD
$wachtwoord = $result->wachtwoord;
if(!strcasecmp($pgebruiker, $gebruikersnaam) == 0)
echo 'Verkeerd gebruikersnaam.';

elseif(!password_verify($pww, $wachtwoord) /*strcasecmp($pww, $wachtwoord) == 0*/)
echo 'Verkeerd wachtwoord';

else
echo 'Correcte gegevens.';
return true;
/*session_start();
$_SESSION['gebruiker'] = $gebruikersnaam;
header('Location: veilig.php');*/
//exit;



login();
?>






php ajax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 18:36









Barmar

437k36261366




437k36261366










asked Mar 8 at 18:16









PrabhPrabh

418




418







  • 1





    JS script knows nothing about returned values in your php code. JS script gets the output of your php code.

    – u_mulder
    Mar 8 at 18:20







  • 2





    In your php code rather that return true you should write echo true.That will parse by javascript as boolean.

    – Vitthal
    Mar 8 at 18:23











  • I recommend to look at your browser console and see what is the output of your PHP call. Since you would like to output JSON I am pretty sure you should't have echo 'Correcte gegevens.'; before it.

    – Dharman
    Mar 8 at 18:25











  • @suraj thanks, I removed the echo before the return true, and changed that to echo true. Worked

    – Prabh
    Mar 8 at 18:32












  • 1





    JS script knows nothing about returned values in your php code. JS script gets the output of your php code.

    – u_mulder
    Mar 8 at 18:20







  • 2





    In your php code rather that return true you should write echo true.That will parse by javascript as boolean.

    – Vitthal
    Mar 8 at 18:23











  • I recommend to look at your browser console and see what is the output of your PHP call. Since you would like to output JSON I am pretty sure you should't have echo 'Correcte gegevens.'; before it.

    – Dharman
    Mar 8 at 18:25











  • @suraj thanks, I removed the echo before the return true, and changed that to echo true. Worked

    – Prabh
    Mar 8 at 18:32







1




1





JS script knows nothing about returned values in your php code. JS script gets the output of your php code.

– u_mulder
Mar 8 at 18:20






JS script knows nothing about returned values in your php code. JS script gets the output of your php code.

– u_mulder
Mar 8 at 18:20





2




2





In your php code rather that return true you should write echo true.That will parse by javascript as boolean.

– Vitthal
Mar 8 at 18:23





In your php code rather that return true you should write echo true.That will parse by javascript as boolean.

– Vitthal
Mar 8 at 18:23













I recommend to look at your browser console and see what is the output of your PHP call. Since you would like to output JSON I am pretty sure you should't have echo 'Correcte gegevens.'; before it.

– Dharman
Mar 8 at 18:25





I recommend to look at your browser console and see what is the output of your PHP call. Since you would like to output JSON I am pretty sure you should't have echo 'Correcte gegevens.'; before it.

– Dharman
Mar 8 at 18:25













@suraj thanks, I removed the echo before the return true, and changed that to echo true. Worked

– Prabh
Mar 8 at 18:32





@suraj thanks, I removed the echo before the return true, and changed that to echo true. Worked

– Prabh
Mar 8 at 18:32












1 Answer
1






active

oldest

votes


















2














Two thing are to be returned from your login() function:



  • a message

  • a boolean

So I suggest you to output the data as a json string like this:



Before the login() function, declare an array:



$response = [];


Then, within all the conditions you have... just set msg and success accordingly, like, for example if the login is correct:



$response["msg"] = "You're logged in buddy!";
$response["success"] = true;


At the end of all conditions echo the array as a json string:



echo json_encode($response);


It will send the following string:



"msg":"You're logged in buddy!","success":true


** Make sure that echo is the only echo in that PHP file!



On client-side now, in the success callback, it would be:



success: function(output) 

// Parse the string.
var json = JSON.parse(output);

swal(json.msg); // Sweet Alert...
if(json.success)
// something to do with the boolean true
else
// Something else







share|improve this answer

























  • Damn bro.... excellent solution

    – Prabh
    Mar 8 at 18:42











  • Thanks! ;) Have fun customizing that... You can send as many info you want now. ;)

    – Louys Patrice Bessette
    Mar 8 at 18:43











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068834%2freturning-true-false-from-php-to-ajax%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Two thing are to be returned from your login() function:



  • a message

  • a boolean

So I suggest you to output the data as a json string like this:



Before the login() function, declare an array:



$response = [];


Then, within all the conditions you have... just set msg and success accordingly, like, for example if the login is correct:



$response["msg"] = "You're logged in buddy!";
$response["success"] = true;


At the end of all conditions echo the array as a json string:



echo json_encode($response);


It will send the following string:



"msg":"You're logged in buddy!","success":true


** Make sure that echo is the only echo in that PHP file!



On client-side now, in the success callback, it would be:



success: function(output) 

// Parse the string.
var json = JSON.parse(output);

swal(json.msg); // Sweet Alert...
if(json.success)
// something to do with the boolean true
else
// Something else







share|improve this answer

























  • Damn bro.... excellent solution

    – Prabh
    Mar 8 at 18:42











  • Thanks! ;) Have fun customizing that... You can send as many info you want now. ;)

    – Louys Patrice Bessette
    Mar 8 at 18:43















2














Two thing are to be returned from your login() function:



  • a message

  • a boolean

So I suggest you to output the data as a json string like this:



Before the login() function, declare an array:



$response = [];


Then, within all the conditions you have... just set msg and success accordingly, like, for example if the login is correct:



$response["msg"] = "You're logged in buddy!";
$response["success"] = true;


At the end of all conditions echo the array as a json string:



echo json_encode($response);


It will send the following string:



"msg":"You're logged in buddy!","success":true


** Make sure that echo is the only echo in that PHP file!



On client-side now, in the success callback, it would be:



success: function(output) 

// Parse the string.
var json = JSON.parse(output);

swal(json.msg); // Sweet Alert...
if(json.success)
// something to do with the boolean true
else
// Something else







share|improve this answer

























  • Damn bro.... excellent solution

    – Prabh
    Mar 8 at 18:42











  • Thanks! ;) Have fun customizing that... You can send as many info you want now. ;)

    – Louys Patrice Bessette
    Mar 8 at 18:43













2












2








2







Two thing are to be returned from your login() function:



  • a message

  • a boolean

So I suggest you to output the data as a json string like this:



Before the login() function, declare an array:



$response = [];


Then, within all the conditions you have... just set msg and success accordingly, like, for example if the login is correct:



$response["msg"] = "You're logged in buddy!";
$response["success"] = true;


At the end of all conditions echo the array as a json string:



echo json_encode($response);


It will send the following string:



"msg":"You're logged in buddy!","success":true


** Make sure that echo is the only echo in that PHP file!



On client-side now, in the success callback, it would be:



success: function(output) 

// Parse the string.
var json = JSON.parse(output);

swal(json.msg); // Sweet Alert...
if(json.success)
// something to do with the boolean true
else
// Something else







share|improve this answer















Two thing are to be returned from your login() function:



  • a message

  • a boolean

So I suggest you to output the data as a json string like this:



Before the login() function, declare an array:



$response = [];


Then, within all the conditions you have... just set msg and success accordingly, like, for example if the login is correct:



$response["msg"] = "You're logged in buddy!";
$response["success"] = true;


At the end of all conditions echo the array as a json string:



echo json_encode($response);


It will send the following string:



"msg":"You're logged in buddy!","success":true


** Make sure that echo is the only echo in that PHP file!



On client-side now, in the success callback, it would be:



success: function(output) 

// Parse the string.
var json = JSON.parse(output);

swal(json.msg); // Sweet Alert...
if(json.success)
// something to do with the boolean true
else
// Something else








share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 18:46

























answered Mar 8 at 18:37









Louys Patrice BessetteLouys Patrice Bessette

20.7k42347




20.7k42347












  • Damn bro.... excellent solution

    – Prabh
    Mar 8 at 18:42











  • Thanks! ;) Have fun customizing that... You can send as many info you want now. ;)

    – Louys Patrice Bessette
    Mar 8 at 18:43

















  • Damn bro.... excellent solution

    – Prabh
    Mar 8 at 18:42











  • Thanks! ;) Have fun customizing that... You can send as many info you want now. ;)

    – Louys Patrice Bessette
    Mar 8 at 18:43
















Damn bro.... excellent solution

– Prabh
Mar 8 at 18:42





Damn bro.... excellent solution

– Prabh
Mar 8 at 18:42













Thanks! ;) Have fun customizing that... You can send as many info you want now. ;)

– Louys Patrice Bessette
Mar 8 at 18:43





Thanks! ;) Have fun customizing that... You can send as many info you want now. ;)

– Louys Patrice Bessette
Mar 8 at 18:43



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068834%2freturning-true-false-from-php-to-ajax%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

1928 у кіно

Захаров Федір Захарович

Ель Греко