javascript - ajax can not recieve JSON from php -
i have issues receiving json object php. can alert , ( think correct) json object datatype: 'text'
, not use data.message
--> "undefined". datatype: 'json'
,'jsonp'
or ajax call $.getjson
not work (it not fire 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 recieved string on jsonlint.com , should valid. tried json.parse(data)
, $.parsejson(data)
not work. json.stringify(data)
returning json slashes (i not know why).
postman can read aswell in html, text, xml or json...
in php tried change header header("content-type: application/json; charset=utf-8");
or force response 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 user mail = '$username' , 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 use datatype: 'json'
recieve nothing (not string), continue using 'text'. php file need change recieve json?
here things tried 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 @ position 0
any more recommendations? thank you!
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 } });
Comments
Post a Comment