-1

I have issues with receiving a JSON object from PHP. I can alert it and get a ( I think correct) JSON Object with dataType: 'text', but not use it like data.message --> it is "undefined". With dataType: 'json','jsonp' or the ajax call $.getJSON it does not work (It does not fire this request).

AJAX

$('#login').click(function () {
var name = $('#username').val();
var pass = $('#password').val();
$.ajax({
    url: "http://localhost/weltenbummler/Weltenbummler1/Weltenbummler1/app/login.php?username=" + name + "&password=" + pass,
    dataType: 'text',
    type: 'GET',
    success: function (d) {
        alert(d);
        alert(d.message);
    }
});});

Alerted JSONs

{"status":"f","message":"Benutzername und Passwort stimmen nicht ueberein"} or

{"status":"t","message":"Erfolgreich eingeloggt!","data":{"id":"1","mail":"abc","password":"123"}}

I tested the received String on jsonlint.com and it should be valid. I tried to JSON.parse(data) , $.parseJSON(data) what does not work. JSON.stringify(data) is returning the JSON with slashes (I do not know why).

Postman can read it as well in HTML, text, XML or JSON...

In php I tried to change the header to header("Content-type: application/json; charset=utf-8"); or to force the response as JSON.

connect.php file:

<?php
$host = "127.0.0.1";
$user= "root";
$pw="";
$db = "weltenbummler";

//Create connection
$con = new mysqli($host,$user,$pw,$db);


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

login.php file:

<?php
header('Content-type: application/json');
require 'connect.php';

$username = $_GET['username'];
$password = $_GET['password'];

$response = array();
if(empty($username)){
    $response = array(
        "status " => " f",
        "message " => " Gebe einen Benutzernamen ein!"
    );
    die(json_encode($response));
}
if(empty($password)){
    $response = array(
        "status" => "f",
        "message"=> "Gebe ein Passwort ein!"
    );
    die(json_encode($response));
}

$sqlstatement= ("SELECT id,mail,password FROM user WHERE mail = '$username' AND password = '$password'");
$result = mysqli_fetch_assoc($con->query($sqlstatement));

if (!$result) {
    $response = array(
        "status" => "f",
        "message" => "Benutzername und Passwort stimmen nicht ueberein"
    );
} else {
    $response = array(
        "status" => "t",
        "message" => "Erfolgreich eingeloggt!",
        "data" => $result
    );
}
$con->close();

echo json_encode($response);?>

EDIT 1:

As soon as I use dataType: 'json' I receive nothing (not even the string), so I continue using 'text'. Does my PHP file need a change to receive JSON?

Here are the things I tried the comments:

console.log(typeof d); returns string

alert(JSON.stringify(d)); returns "{\"status\":\"f\",\"message\":\"Benutzername und Passwort stimmen nicht ueberein\"}"

alert(JSON.parse(d)); returns Uncaught SyntaxError: Unexpected token in JSON at position 0

Any more recommendations? Thank you!

Roham Rafii
  • 2,645
  • 6
  • 31
  • 41
  • This `dataType: "text",` should be `dataType: "JSON",` – Milan Chheda Aug 15 '17 at 04:44
  • If `JSON.parse(data)` does not work and `JSON.stringify(data)` returns the data with additional slashes then this indicates that you might have some characters (e.g. Invisible ones) that might make the json invalid. What error do you get for `console.dir(JSON.parse(data))`, how does the output of `console.log(JSON.stringify(data))` look like? – t.niese Aug 15 '17 at 04:59
  • try moving $con->close(); before echo and try console.log(typeof d); – Ye Lwin Soe Aug 15 '17 at 07:25

4 Answers4

1

Try this

$.ajax({
    url: 'http://localhost/weltenbummler/Weltenbummler1/Weltenbummler1/app/login.php?username=' + name + '&password=' + pass,
    dataType: 'json',
    type: 'get',
    success: function (e) {
        alert( JSON.parse(e.message) ); // undefined
    }
});
Juliver Galleto
  • 7,927
  • 19
  • 69
  • 138
  • For the data shown in the question `e.message` is a text and not JSON, why should the OP try to parse that? If the retruned data is correctly recognized as JSON then `e` would alread hold the parsed object. – t.niese Aug 15 '17 at 05:04
  • if datatype is text, he could just do "alert(e)", op said, its json, so he/she needs to parse in order to transform the return data unto a proper javascript objects. – Juliver Galleto Aug 15 '17 at 06:34
  • Yes but the OP says that `alert(d);` shows the JSON string, and `alert(d.message);` shows `undefined`. So if `dataType: 'json'` would correct the problem that the returned data is not parsed by jQuery, then `JSON.parse(e.message)` would try to parse the `"Benutzername und Passwort stimmen nicht ueberein"` which is not JSON. If it would not solve the problem, the `d.message` would still be `undefined` and `JSON.parse(e.message)` would show an error because of parsing `undefined`. – t.niese Aug 15 '17 at 07:27
  • sadly this did not work...as soon as I change the dataType to "json" I recieve nothing, not even the string anymore. with "text" i get the string but the alert of '( JSON.parse(e.message) );' //nothing happens – Leonard Traeger Aug 19 '17 at 00:37
0

You can read out the exact recieved data with chrome developer: 1. I recieved a string with hidden variables: #$63434;{"status":false,...} and with 2. With PHP errors aswell

To 1.: PHP buffering variables fireing your code --> scope it with ob_start(); and ob_end_clean(); reference: https://stackoverflow.com/a/9985307/8036245

To 2.: Just fix your php code: I had the issue, that not defined variables alert missing reference

After that I could even fire the $.getJSON(..) call! Hope this will help somone :)

-1
  • contentType is the header sent to the server, specifying a particular format. Example: I'm sending json or XML
  • dataType is you telling jQuery what kind of response to expect. Expecting JSON, or XML, or HTML, etc....the default it for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.

$.ajax({
    url: "http://localhost/weltenbummler/Weltenbummler1/Weltenbummler1/app/login.php?username=" + name + "&password=" + pass,
    dataType: 'JSON',
    type: 'GET',
    success: function (d) {
        console.log(JSON.parse(d.message))
    },
});
Milan Chheda
  • 7,851
  • 3
  • 18
  • 35
  • For the data shown in the question `d.message` is a text and not JSON, why should the OP try to parse that? If the retruned data is correctly recognized as JSON then `d` would alread hold the parsed object. – t.niese Aug 15 '17 at 05:05
-1
echo json_encode($response, true);
Carl Binalla
  • 5,153
  • 5
  • 25
  • 44
syntaxe
  • 112
  • 4