1

Im trying to get data from my php file using success function(data)

When im using console.log(data) i get; true/false/exists But i cant make a if statement, if i do it dosent alert!!

Heres my js file

function ajaxCall(username, email, password){

$.ajax({
    type: 'POST',
    url: '../register.php',
    data:   {
        'username' : username,
        'email' : email,
        'password' : password,
    },
    success: function(data) {
     if(data === "exists")
     alert("user exists");
    }
});

}

heres my .php file

<?php

$servername = "#";
$username = "#";
$password = "#";
$dbname = "#";

$regusername = $_POST['username']; 
$email = $_POST['email']; 
$regpassword = $_POST['password'];   

$mysqli = new mysqli($servername, $username, $password, $dbname);
$selectQuery = "SELECT username FROM users WHERE username = '$regusername'";
$select = $mysqli->query($selectQuery);
// var_dump($select->num_rows);

if( $select->num_rows == 0) {
    $insertQuery = "INSERT INTO users (username, password, email) VALUES ('$regusername','$regpassword','$email');";
    $insert = $mysqli->query($insertQuery);

        if( $insert == true) {
            echo "true";
        }else {
            echo "false";
        }
}else {
    echo "exists";
}

?>
1
  • 1
    Thanks for the help guys, really appreciate it. ($.trim(data) did the job. But will use a more properly structured data format. Anyways, this was my first post on stackoverflow, and you guys who help people here are awesome. This will probably not be my last post here ;-) Thanks for now! Commented Oct 23, 2015 at 11:39

5 Answers 5

2

Use a properly structured data format, such as json:

php:

$data=['exists'=>false];
if( $select->num_rows == 0) {
    $insertQuery = "INSERT INTO users (username, password, email) VALUES ('$regusername','$regpassword','$email');";
    $data['inserted'] = (bool) $mysqli->query($insertQuery);
}else {
    $data['exists']=true;
}
header('Content-Type: application/json');
echo json_encode($data);
die();

JS

$.ajax({
    type: 'POST',
    url: '../register.php',
    data:   {
        'username' : username,
        'email' : email,
        'password' : password,
    },
    success: function(data) {
       if(data.exists){
           alert("user exists");
       }elseif(data.inserted){
           alert("inserted");
       }else{
           alert("did not insert");
       }
});
Sign up to request clarification or add additional context in comments.

3 Comments

@charlietfl answer worked! But should i rebuild my code like you did it?
@JonasAlvarson Thats entirely up to you - however if you ever want to send more than a single variable back to the javascript, then json is the way, so you might as well get into the habit.
@JonasAlvarson I would use the json. In the long run you will find it better as you may decide to add additional information later also and it is simple to add another property
1

Chances are there is extra whitespace in the response

Try:

if($.trim(data) === "exists")

1 Comment

if($.trim(data) worked like a charm! But should i rebuild my code like @steve did?
1

I think its better to work with HTTP-Status codes like 404 or 403 (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) instead of retuning a string. This can by done with PHP (http://php.net/manual/de/function.http-response-code.php) and use the error callback of your ajax call (http://api.jquery.com/jquery.ajax/ --> StatusCode)

Comments

1

You are not responding with an answer to the front, you just echoing 'exist' word in your php handler. Try using json_encode, because the dataType is "json" by default not "html"

Lets's say

if($insert) { 
 $response['exist_status'] = 'exist' 
}else{ 
 $response['exist_status'] = 'do not exist' 
} 
echo json_encode($response);

In your jquery

success: function(response) { 
 if(response.exist_status && response.exist_status == 'exist')  { 
  alert(1); 
 } 
}

4 Comments

ah im sorry. yeah ill rewrite my code a bit. Thanks for the help. Really appreciate it!
You might want set an appropriate content type header, and use booleans instead of strings where appropriate. However +1 as this is still a better option than echoing a string
Combine both answers and you will get what you need, don't forget the die() as Steve posted it in his answer...
@MancharyManchaary Just noticed you are not actually outputting the json - return does not work in this context, you need to echo or print the response. Please edit for future visitors
-1
if(data == "exists") instead of  if(data === "exists")

5 Comments

Allready tried that.. it didnt do the job.. am i misssing something out? Like dataType: 'json',
text will be default . you are not returning json data so no need to write json
write console.debug(data); in success and debug in console.
if im using console.debug(data); i get "exists" even when im randomly typing in different user/email & passwords that i know dont exists in the database.
@JonasAlvarson also check length of data and it likely isn't 6 due to whitespace that you don't see

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.