2

I echo a simple associative array read from a mySQL table back to my jquery b.m.o the json_encode($array) method. However, my .ajax call fails back in the jquery and it seems due to the object not being a valid json object. I did some debugging in chrome and under the network tab verified the response preview- does indeed look to be in perfect json format:

{"UserName":"DehanL","UserPassword":"admin","UserEmail":"dehan@rocketmail.com"}

Here is my php:

<html>
<body>

<?php



$servername = "localhost";
$username = "root";
$password = "";
$dbName ="dbPodiumPro";

$inUsername = $_POST["name"];
$inPassword = $_POST["password"];


// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Use the dbPodiumPro
mysqli_select_db($conn,"dbPodiumPro");


$sql = "SELECT * FROM users WHERE UserName='$inUsername' AND UserPassword ='$inPassword' ";

$result = mysqli_query($conn,$sql);

// Fetch one row
$row=mysqli_fetch_assoc($result);

//Check to see if the username and password combo exists
if(!empty($row['UserName']) AND !empty($row['UserPassword'])) 
    { 

    //$_SESSION['UserName'] = $row['UserPassword']; 
    //echo $_SESSION; 

    echo json_encode($row);

    } 

else { echo "Be gone imposter!"; }


$conn->close();


?>

</body>
</html>

Then the jquery:

$.ajax({
        type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url: 'php/loginrequest.php', // the url where we want to POST
        data: formData, // our data object
        dataType: 'json' // what type of data do we expect back from the server

    })
    // using the done promise callback
    .done(function (data) {
        console.log("ajax done callback");
    })
    .fail(function (data) {
        console.log(data, "ajax failed callback");

        var IS_JSON = true;
        try {
            var json = $.parseJSON(data);
        } catch (err) {
            IS_JSON = false;
        }
        console.log(IS_JSON);
    });
user3064874
  • 125
  • 1
  • 11
  • 1
    Did you use `Content-Type: application/json` on the server? Otherwise the client might think it's not valid JSON even though the text format is correct – devnull69 May 07 '15 at 08:53
  • **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin May 07 '15 at 09:28
  • **Danger**: "Not hashing at all" is [an unsuitable hashing algorithm](http://php.net/manual/en/faq.passwords.php); you need to [take better care](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) of your users' passwords. – Quentin May 07 '15 at 09:28
  • Your code can be SQL injected, but that doesn't relate to your question. Just a heads up that you could potentially log in by using `' OR 1 OR ''='` or similar as password. Also use hashing on passwords! – EJTH May 07 '15 at 09:29
  • are you encoding the password to md5 if so check this http://stackoverflow.com/a/30097151/2536812 – chapskev May 07 '15 at 11:52
  • Injection and other security issues noted, and will be addressed as per your recommendations. This was just a first attempt at getting some server calls functional. – user3064874 May 07 '15 at 12:15

4 Answers4

2

You don't need to parseJSON when you have added dataType as JSON option in the AJAX.

The data you are getting after ajax is completed is already in JSON format.

"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

Docs: http://api.jquery.com/jQuery.ajax/

The data inside fail method is not what you've passed from server. It is the information related to the request.

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Tushar, the parseJSON part is simply to check the validity of the json object as suggested by another member. So yes @devnull69 the question is why it goes into the .fail when the debugging info shows a correct looking response. I hear you about the data in the fail loop. The data in the .done would be what has been returned from my ajax call then right Tushar? – user3064874 May 07 '15 at 09:16
2

Your PHP starts like this:

<html>
<body>

Whatever else it outputs after that, it isn't going to be valid JSON.

I did some debugging in chrome and under the network tab verified the response preview

Look at the raw preview. You seem to be looking at the rendered HTML preview.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • That was indeed the issue. Wrongly assumed that php needs to be wrapped in those tags from a sample I saw. Solved. – user3064874 May 07 '15 at 12:13
0

If you are encoding your password using MD5 and the likes, Json will not encode you can choose to unset the password from you your array or define the column you want to select from your database excluding password column.

chapskev
  • 972
  • 9
  • 27
0

Change your ajax as

$.ajax({
        type:"POST",
        url: 'php/loginrequest.php',
        data:$("#form_id").serialize(),
        dataType:"json",
        success: function(data)
        {
            alert(data.UserName);
        }
    });

you can use both data:formData or data:$("#form_id").serialize(),

if you are getting alert message then everything is working fine

Varun Naharia
  • 5,318
  • 10
  • 50
  • 84