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!