So I have a js file that posts a JSON object using $.ajax, and then my php script takes that JSON object and does stuff to it, however, i can't get a json response back from the php script (the success callback function never runs).
register_script.js:
$.ajax({
method: "post",
dataType: "json",
url: "http://localhost/login/webservices/register2.php",
data: {
reg_username: username,
email: email,
reg_password: password,
confirm_password: confirm_pass
},
success: function (data) {
alert("hello?");
//alert(data.status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
});
register2.php:
if (isset($_POST['reg_username'], $_POST['email'], $_POST['reg_password'], $_POST['confirm_password'])) {
$username = $_POST['reg_username']; //$_POST['from html']
$email = $_POST['email'];
$password = hash('md5', ($_POST['reg_password']));
$confirm_password2 = hash('md5', ($_POST['confirm_password']));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username','$email','$password')";
if ($password == $confirm_password2) {
$response = sqlsrv_query($conn, $sql);
if ($response) {
$data = array(
"username" => $username,
"email" => $email,
"password" => $password,
"confirmPass" => $confirm_password2,
"status" => "Registered",
);
echo "Registered \n";
}
}
}
//...
//some other validations
//...
echo json_encode($data);
I have a feeling the way i am handling the json object is incorrect. any help would be really appreciated.
you should not
echo
anything other than json_encode when working with ajax dataType : json you have
echo "Registered \n";
before
echo json_encode
remove that and it should work
EDIT:
when you set the dataType : "json" in your ajax call then the response is expected to be in json when the call is finished, and any text other than json encoded string in response will result in an error. if you still need to debug and see what route the script is taking, you can add another index in $data (i assume that $data is an array), so it would be like
if($registered){
$data['debug_logs'] .='Registration successfull----';
}
if($emailSent){
$data['debug_logs'].='Email sent for registration-----';
}
echo json_encode($data);
and then in your ajax success function you can use it like
success:function(data){
console.log(data.debug_logs);
}
hope it clears your confusion.
Please remove echo "Registered \n"; the line from your code when you echo "Register"; the Ajax request return this back to the browser, and your actual data echo json_encode($data); never return back to the browser.
Related
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.
<script>
function submitForLogin()
{
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" }}).done(function(data){alert(data);});
}
</script>
When user clicks on login button it calls submitForLogin() function.
Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.
Note : example#abc.com and 123 both email and password stored in Wamp server database.
This is the PHP file :
<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection
$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
echo "userExist";
}
else
{
echo "fakeUser";
}
mysqli_close($con);
?>
Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.
Is there something I missing? I'm running the website in wamp server too.
UPDATE
When I check console errors it shows;
And when I click on login.html line 112, it shows;
And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.
There was a jquery error and now it's fixed. But syntax error exists.
Try this code working for me on my machine. Don't forgot to place Jquery File.
PHP (ajax.php) :
<html>
<head>
<script src="jquery.min.js"></script>
<script>
function submitForLogin()
{
alert("23");
var email = document.getElementById("txtUserName").value;
var password = document.getElementById("txtPassword").value;
$.ajax({
type: "POST",
url: "login1.php",
data: { email: email,password:password },
success : function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<input type="text" placeholder = "Enter user name" id="txtUserName"/>
<input type="password" placeholder = "Enter password" id="txtPassword"/><br>
<input type="button" onclick="submitForLogin();" value="Login"/>
</body>
</html>
Server Side (login1.php) :
<?php
var_dump($_POST);
?>
You need to include a function for when the request is successful, which includes the response.
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success:function(data){
alert(data)
};
});
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success: function (data) {
alert(data);
}
});
your data in AJAX call is in JSON format.
in your php script you should use json decode as below
$data = file_get_contents("php://input");
$data = json_decode($data,true);
$userEmail=$data['email'];
$userPass=$data['password'];
i hope this might help you. your login will work as u expect it
Change your php file like below :
<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection
header('Content-type: application/json');
$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
$res = "userExist";
$data = json_encode($res);
echo $data;
die();
}
else
{
$res = "fakeUser";
$data = json_encode($res);
echo $data;
die();
}
mysqli_close($con);
?>
And your script :
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success:function(data){
alert(data);
};
});
I have a file called login.php, in this file there is the box to fill from send the login data to the server. Now when the user press the login button, this code is fired:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// Some stuff..
}, 'json');
the postUrl is valorized correctly by:
http://localhost/App_Name/application/controllers/user.php/ajax_check_login
now I have a list of my own controller that allow me to manage the web app. One of this controller is user.php, how you can see I call the ajax_check_login function. This function check if the data passed from this request exists in the database and if are correct. This is the content:
public function ajax_check_login()
{
echo "Test?";
try
{
if(!isset($_POST['username']) || !isset($_POST['password']))
{
throw new Exception('Bad credentials!');
}
$this->check_login($_POST['username'], $_POST['password']);
if($user_data)
{
$output[] = array(
"some content..."
echo json_encode($output);
}
else
{
echo json_encode(AJAX_FAILURE);
}
}
catch(Exception $exc)
{
echo json_encode(array(
'Exception ' => array(exceptionToJavaScript($exc))
));
}
}
Now, at the top of all I inserted an echo, just to test if is printed. But nothing. In the Chrome console I get:
This request has no response data available.
I don't know what is wrong, someone could enlighten me?
First, you'd like to check what's the return from server, say HTTP200 without contents? or Error 500. Why I'm saying this because your snippet tells there are few variables/functions missing. Check my comments:
public function ajax_check_login()
{
echo "Test?";
try
{
if(!isset($_POST['username']) || !isset($_POST['password']))
{
throw new Exception('Bad credentials!');
}
$this->check_login($_POST['username'], $_POST['password']);
if($user_data) // $user_data is never defined in this function, and it's not a global variable
{
$output[] = array(
"some content..." // syntax error; here missing end parenthesis
echo json_encode($output);
}
else
{
echo json_encode(AJAX_FAILURE);
}
}
catch(Exception $exc)
{
echo json_encode(array(
'Exception ' => array(exceptionToJavaScript($exc)) // unknown function exceptionToJavaScript(); it could encounter fatal error
));
}
}
Second, I will suggest you send header to define you're sending JSON encoded content, and exit() after echo. See example:
header('Content-type: application/json');
echo json_encode(/** return **/);
exit();
I am new to Ajax & JavaScript. But i am stuck with this error. I am making post request using Ajax.
var sentdata = {"name":"gourav", "email":"email"};
var sentd = JSON.stringify(sentdata);
this.url = "http://localhost/Working/board.php";
$.ajax({
type: "POST",
url: $(this).url,
data: sentd,
contentType: "application/json",
//dataType : "json",
success: function (response) {
alert(response.message);
console.log( "Done with success: ");
},
error: function (xhr, thrownError) {
alert(thrownError);
}
});
I am calling this request to simple code where i am not even checking the $_POST variable and just trying to write some data in mysql table.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true);
// selecting database
mysql_select_db(DB_DATABASE, $con);
if(1)
{
$tb_name = "tb_appuser";
$name = "name1";
$email="email1";
$deviceId="0";
$platform="1";
$query = sprintf("INSERT INTO %s (user_name, email, device_regid, platform_type) VALUES ('%s', '%s', '%s', '%d')" , $tb_name, $name, $email, $deviceId, $platform);
echo "$query\n";
$res = mysql_query($query);
}
I already tested this board.php code and verified it is inserting the data in table.
But when i am doing this via $ajax i am getting "The page at localhost says: undefined" and nothing got written in my database also.
url: this.url, not $(this).url.
$(this) does not have a property called "url" in your context I think.
I use this jQuery function to get data through Ajax:
function addContentPrt(cid){
$.ajax({
url: "<?=parseLink('addContent.php')?>",
type: "POST",
cache: true,
dataType:'json',
data: {id: cid},
success: function(returnedData){
console.log(returnedData);
},
error: function (xhr, tst, err) {
console.log(err);
}
});
}
and on the receiving end:
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo $r['title'];
echo $id;
?>
the echo $id does return to ajax, but not $r['title'], with that it goes null in console. If I add some dummy text like hello world, I get a synthax error SyntaxError: Unexpected token h {stack: (...), message: "Unexpected token h"}
What could be the cause of this and what could I do to fix it?
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo json_encode('id' => $id, 'title' => $r['title']);
?>
and in your ajax success:
success: function(returnedData){
console.log(JSON.parse(returnedData));
},
In the ajax, you specified the datatype as json which is the format expecting from the server, So in order to get a result, you need to return the json result from the server. Either by using json_encode($r) where $r can be any array.
return json_encode($r); then you can read variable $r in sucess
I have this working to a point, but would like, after true is returned, to set localstorage to value of the id passed in mySQL query. I'm unsure how to pass this, as my php currently echos only true or false.
<script type="text/javascript">
$(document).ready(function() {
$('#loginButton').click(function(){
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "login.php",
cache: false,
data: { username: username, password: password },
success: function(res) {
switch(res) {
case ('true'):
alert('true');
break;
case ('false'):
alert('false');
break;
}
}
});
return false;
});
});
</script>
<?php
$username = $_POST['username'];
$password = md5($_POST['password']);
if(!empty($username) && !empty($password)) {
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindValue('username', $username);
$stmt->bindValue('password', $password);
$stmt->execute();
if($stmt->rowCount() == 0) {
echo 'false';
} else {
echo 'true';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
}
}
}
$conn = null;
?>
If you want to respond with several values when using AJAX you may use JSON.
In php code it should be like this (paste it after $stmt->execute(); line instead of if-else construction):
if($stmt->rowCount() == 0) {
echo json_encode(array('success' => false));
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];
echo json_encode(array(
'success' => true,
'user_id' => $user_id
));
}
Then in javascript you should specify that you expect JSON as a response. This is a code:
$.ajax({
type: "POST",
url: "login.php",
cache: false,
dataType: 'json', //this is where we specify JSON response
data: { username: username, password: password },
success: function(res) {
if (res.success) {
localStorage.setItem('user_id', res.user_id); //set user id to local storage
alert(res.user_id);
} else {
alert('false');
}
},
error: function() {
//this will trigger in case the server send invalid JSON (or other types of errors)
alert('false');
}
});
I would also recommend to use GET method instead of POST in this case. POST is usually used when you need to change something of a server (database, session, file system, etc.), but when you want just get some data, it's better to use GET. However no one restricts you to do as you want, but I think it better to follow standard.
Good luck!