JQuery AJAX if-else not working - php

The return data for this one as I investigated is "authenticated" which means the if statement should take effect. However, to reasons I know not it goes directly to the else part of the statement making the data false even if it's true. Like "authenticated"=="authenticated". It ignores the if part and I don't know why.
function login_admin_user() {
username = $("#ad-username").val();
password = $("#ad-password").val();
$("#button-login").val("Logging in...");
$.post("ajax-login.php", {
username: username,
password: password
}, function (data) {
if (data == "authenticated") {
/* Execute if authenticated */
$("#box-login-confirmed").fadeIn("slow", function () {
$("#button-login").val("Login");
})
.delay(1000)
.fadeOut(400, function () {
window.location = "home.php";
});
} else {
/* Execute if invalid login */
$("#box-login-error").fadeIn("slow", function () {
$("#button-login").val("Login");
$("#ad-password").val("");
})
.delay(3000)
.fadeOut(400);
}
});
}

"authenciated"!="authenticated". You are missing a 't'. Also probably your response may contain spaces. So check what is coming in the response.And its better to trim your response before doing the checking. You can use jquery trim function to remove spaces.
Try like
if($.trim(data) == "authenticated"){
//Some code
}
else{
//Some code
}
Why the response contain spaces. You can find the answers here
Space Before Ajax Response (jQuery, PHP)
strange thing, ajax response includes whitespace
Trailing spaces in Ajax response

I have encountered that problem as well. Using $.trim() from the response data would help strange whitespaces to be altered.

The default return type of the $.post method is HTML. So, if you set the return type as JSON and in your PHP file you return a JSON ENCODED value as "authenticated" .. that might work

Related

Ajax returns with PHP

Alright so I am trying to put this thing together, but I do not understand what is the problem with this code. I am basically trying to return false in case name exists in the database, but no matter what ajax will just pass it as a "success"
Here is the code:
Running the
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
return true;
},
error:function(data) {
return false;
}
});
}
The code is executed perfectly and it actually passed all the things it needs, and the PHP function does get called.
PHP function bellow.
public function nameExists($name) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($name);
$name_final = ucfirst($name);
$result = $sql->query("SELECT ime FROM users WHERE ime='".$name_final."'");
if($result->num_rows != 0) return true;
else {
$handler->log_write($name, "login_fail","NULL");
return false;
}
$sql->close();
return false;
}
Now the problem is success and the error. No matter what it will always be success. It doesn't like pay attention at when I return FALSE from the PHP at all and such.
AJAX calls are literally just an HTTP request, like any other HTTP request. You're not directly "executing" PHP code when you make an ajax call, you're doing an HTTP request to the server, which (eventually) executes a PHP script on your behalf.
That means any return from the PHP code are completely invisible to Javascript.
Only OUTPUT from PHP will ever be seen by Javascript, which means you need to echo that data, not return it.
And note that any HTTP response from PHP is also literally plain text. Any output you perform in PHP will be converted to text, which means that boolean false you're trying return will be converted to the string equivalent of a boolean false - an invisible zero-length string.
"error" condition in your js code is only for bed requests, like 500, 404 etc.
return a json { error: true } or something like with and use it in your js
success:function(data){
if(data.error) {
// do...
}
},
As far as I can see your code, you're returning nothing to client. You shall return some data that represents the boolean value about the user existence. For instance:
// PHP server-side
if( nameExists( $name)) echo "T";
else echo "F";
that will return value can then be captured by the data parameter in your AJAX function for success and be tested about the server answer.
// Javascript in client
success:function(data){
if( data === "T") return true;
else return false;
},
Hope I can help!
instead of return from php you need:
echo "True" or "false"
to on javascript side:
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
if(data=='true'){
alert("success process");
}else{
alert("fail process");
};
},
error:function(data) {
console.log("error Ajax");
}
});
}
The data transferred between the client and the server is always text. You need to make sure that the client and server know how the client should deserialize the text. So you might return one of four things:
HTML (if it's going to populate page elements)
JSON (if you want a lightweight, fast way to send data to the client)
XML (if you want a heavier-weight, fast way to send data to the client)
Plain text (for whatever you want, really)
What the client does will depend on what Content-Type header you use in your PHP page.
so, use a header in PHP, for eg:
header('Content-Type', 'application/json');
...and the return this text from it:
{"success": true}
or
{"success": false}
I hope it will help.

Checking for unique username with Jquery post

So I'm running a script from my page using the Jquery post wrapper, and in chrome debugger the below cases happening:-
1) if the username is taken i'm getting `"taken"`
2) else it echo's nothing.
However, I cannot get to the alert('im here'); line it seems that if(data=="taken") statement is never run or always evaluating to false, which is not the case. What am I doing wrong?
Jquery
var flag;
$.post('welcome/check_username',{childname: $('#name').val()}, function(data){
if(data=="taken")
{
alert('im here');
return flag = true;
//tell user that the username already exists
}else{
return flag = false;
//username doesn't exist, do what you need to do
}
});
PHP
if ($this->Form_builder->check_unique_username($username, $childname))
{
echo "taken";
}
its always good to trim things. try
if(data.trim()=="taken")
Try this:
var flag;
var result = $.post('welcome/check_username',{childname: $('#name').val()});
result.done(function( data )
{
if(data=="taken")
{
alert('im here');
return flag = true;
//tell user that the username already exists
}else{
return flag = false;
//username doesn't exist, do what you need to do
}
});
Looking at the code, here are the sections I would check:
On the PHP side, check whether the function is properly getting the proper values in $username and $password. You can do this by modifying the PHP file like this:
if ($this->Form_builder->check_unique_username($username, $childname))
{
echo "taken";
}
else
{
echo $username." and ".$childname." is not taken";
}
Then on the jQuery side, before the if statement, do console.log(data) or alert(data) to see what is being returned. Perhaps, you are sending data by the POST method but the server side script expects the parameters via the GET method.

Ajax variable value to javascript

I've been on a problem for hours without finding any issue...
I have a registration form for users to create accounts. When the submit button is pressed a validateForm function is called.
In this function I do some javascript tests that work, but then I need to verify that the username is available. For this I created an external PHP file and call it using $.ajax.
Here is part of the code :
function validateRegistration(){
// Some tests....
// Check if username is already used
// Call external php file to get information about the username
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
}
});
// Other tests
}
My question is how can I make validateForm() return false from inside the $.ajax ?
Could I for instance declare a js variable before the Ajax part and set it with Ajax ?
I guess the answer is obvious but I'm absolutely new to Ajax and I can't get it...
Thanks a lot for your help!
To achieve this you can either do a synchronous ajax call like described in this answer, but that's something which is incredibly dangerous for the performance of your website.
Alternatively - and this is the right way - you should have an external variable whether the username is available, as soon as the user inputs something you do the request and if it's valid you change the variable otherwise you show an warning message. Next in your validateRegistration() function you only check the external variable (+ possible some form of callback, depending on where you call it from). The advantage being that the user can still continue doing things (like filling out the rest of the form) whilst the request is pending.
You could make a synchronous ajax call, instead of an asynchronous, as you're doing now. This means that the Ajax call will complete before the next lines of code are executed.
To do so in jQuery, just add async: false to your request object:
var someVariable;
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
someVariable = "something";
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
},
async: false
});
alert(someVariable); // should alert 'something', as long as the ajax request was successful
In the php, if you print out JSON like:
echo json_encode(array("ko"=>"good"));
shows up as:
{
"ko":"good"
}
then in the function it would be
if(data.ko == "good"){
//do stuff
}
This is how I normally do it. You can get the variable by using the name you used in the JSON so you can have other things if you need.
If the goal is to check a username availability, how about checking it as or just after the username is typed in. For example you could either bind it to the keyUp event for keystrokes or the blur event for when you leave the text box.
This would mean that by the time the user gets to the submit button, that part of the form would already be validated.
The traditional solution here is to pass a callback function to validateRegistration which expects a boolean value. Have the Ajax function call the callback function when it completes.
The onsubmit handler expects a return value immeidately, so performing an asynchronous test within your submit event handler is a fairly unituitive way to do things. You should instead perform the test as soon as possible (e.g. as soon as the user enters a username) and then store the result of username validation in a global variable, which is later checked at submit time.
// global variable indicating that all is clear for submission
shouldSubmit = false;
// run this when the user enters an name, e.g. onkeyup or onchange on the username field
function validateRegistration(callback) {
shouldSubmit = false;
// number of ajax calls should be minimized
// so do all other checks first
if(username.length < 3) {
callback(false);
} else if(username.indexOf("spam") != -1) {
callback(false)
} else {
$.ajax({
....
success: function() {
if(data == "ko") {
callback(false);
} else {
callback(true);
}
}
});
}
}
Now call validateRegistration with a function argument:
validateRegistration(function(result) {
alert("username valid? " + result);
if(result) {
$("#username").addClass("valid-checkmark");
} else {
$("#username").addClass("invalid-xmark");
}
shouldSubmit = result;
});
Now use the global variable shouldSubmit in your form's submit event handler to optionally block form submission.

$.post json request doesn't return any result

Well, another try:
this is all the jquery code i'm using maybe i made something wrong in the code before $.post(); i call the following function with the onclick of the same form...
function setLogin()
{
$('#login-form').submit(function(e) {
e.preventDefault();
//passing form field to vars
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
//checks on fields lenght
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
//the url
'?module=login',
//data got from login form
{
"username": formUsername,
"password": formPassword,
},
//response
function(data){
$("#ajax-output").html(data.reply)
},
//type
"json"
);
}
});
}
i tried with only this code in php file and it still doesn't return anything...
function Login()
{
//just to try
echo json_encode(array('reply'=>'foo'));
}
it still doesn't work...
Are you sure the post is being run in the first place?
Use Firebug! (or chrome's built-in developer tools)
You can use firebug to pick apart every bit of a web page.
It has a "net" tab that shows every request that is made by the browser, including AJAX requests, and their results, headers and contents.
Use it to see if your requests is really being made, and what the result is. Then take it from there.
Make sure that you're setting a header for the content type when responding - the browser may not attempt to use the JSON if it doesn't know it's receiving JSON.
function Login()
{
header('Content-Type: application/json');
echo json_encode(array('reply'=>'foo'));
}

PHP and JQuery Button trigger not working

Im currently new to PHP and JQuery after having using ASP.Net and C Sharp for the 2 years. I have this major problem in which i require some assistance in.
I have a HTML <input type="submit" id="btnWL" value="Add to Wishlist"> button. Basically when this button is pressed a table called 'wishlist' in the database is checked to see if the current product is already in a wishlist. If no the button will trigger a database save else it will return a JQuery alert pop up error message.
I having difficulty in passing 2 PHP variables: $_SESSION["username"] and $_GET["ProductId"] into this JQuery method:
<script type="text/javascript">
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php");
});
});
</script>
As you can see this JQuery method must pass those values to an external PHP File which checks for an already exsisting record in the 'wishist' table with those details.
<?php
$WishlistDAL = new WishlistDAL();
$result = $WishlistDAL->get_ProductInWishlistById($_GET["ProductId"]);
if (isset($_POST["isPostBack"])) {
if (isset($_SESSION["username"])) {
if (isset($_GET["btnWL"])) {
//Check if ProductId is in Cart
if (mssql_num_rows($result)>0)
{
//Return an error
//Sumhow this has to trigger an alert box in the above JQuery method
}
else
{
//Write in Wishlist Table
$WishlistDAL->insert_ProductInWishlist($_GET["ProductId"], $_SESSION["username"]);
}
}
}
else
{
//Return Error
}
}
?>
Another problem I have is then displaying an alert box using the same JQuery method for any errors that where generated in the php file.
Any Ideas how I can implement this logic? Thanks in advance.
Your "$.post()" call isn't passing any parameters, and has no callback for interpreting the results:
$.post('addToWishlist.php', { username: something, password: something }, function (response) {
});
The "something" and "something" would probably come from your input fields, so:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
});
Now the callback function would interpret the response from the server:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
if (response === "FAIL") {
alert("fail");
}
else {
// ... whatever ...
}
});
Exactly what that does depends on your server code; that "FAIL" response is something I just made up as an example of course.
jQuery accepts an callback:
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php", {'isPostBack':1}, function(res){
if (res.match(/err/i)){
alert(res);
}
});
});
});
Then, in the php, just (echo('Error adding record')) for this jquery to see there's an error string in the response and pop up the error message.
Other methods would be to use json, or http status codes and $.ajaxError(function(){ alert('error adding'); });.
from what i can tell so far is you'll only need to pass in the product id in and you can do this by appending your $.post call with the value; this will pass to your php script as a query string variable. i'm not sure which php script you posted, but if you're sending your data with jquery, it's using post and not get, so you may need to make an adjustment there and the session data should be available regardless, since it's the same session.
again this is without seeing all the code and since some of it isn't labeled, it's hard to determine. another thing, i like to use $.ajax for most actions like this, you have a lot more room to define and structure, as well as create one generic ajax function to call the methods and post data, as well as make a response callback. here's the documentation for you to look into $.ajax
i hope this helps.

Categories