jQuery Ajax function does not work? - javascript

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);
};
});

Related

PHP not receiving AJAX POST from js File

I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}

Unable to parse response using ajax

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.

Posting a comment in PHP with Ajax

I know there are a few of these questions posted on here already but i am having trouble finding a solution to my problem. I am very bad with anything javascript/ajax and i am having difficulties trying to get my ajax code to work.
I am building a simple commenting system on a video page for my website. I have built the commenting system with php but now i want to get more advance and post the data to my comments.php file via ajax. I want the comments to display dynamically without refreshing the page. I've read a few tutorials but for some reason whenever i try work with js i get really confused. I think it's the syntax :S. I'll post my code below and if anyone can tell me where i am going wrong it will be a massive help!
videos.php
// comment box
if($user->isLoggedIn()){
//login to comment
} else { ?>
<div id="user-comment" class="comment-post">
<form id="comment-form" method="post">
<textarea id="comment_body" name="comment"> </textarea>
<input id="submit-btn" type="submit" name="comment_post" value="Post Comment" >
// csrf-token generator
<input type="hidden" id="auth-token" value="<?php echo token::generate(); ?>"></input>
</form>
</div>
//post comments
<div id="comments_post" class="comments-box">
<?php
$get_comments = // query the db here
if(!$get_comments->results()){ ?>
//no comments...
<?php
} else {
foreach ($get_comments->results() as $comment) { ?>
<div class="comment-header">
<?php echo $comment->username . ' | ' . $comment->added;
if ($user == $comment->user OR $user->hasPermission('admin')) { ?>
<i class="fa fa-trash-o onl-link-icon text-right"></i>
<?php
}
?>
</div>
<div class="comment-body">
<p><?php echo $comment->comment; ?></p>
</div>
<?php
}
}
?>
</div>
ajax request
<script type="text/javascript">
$(document).ready(function(){
//Post Comment
$("#submit-btn").on('.submit','click',function(){
var body = $('#comment_body');
$.ajax({
url: 'comments.php',
type: 'post',
async: false,
data:{
'comment_body' : body
},
success:function(){
$('#comment-box').toggleClass("comment-hide");
}
});
});
});
</script>
comments.php
if($_POST['auth_token'] === session::get('access_token')){
if(isset($_POST['comment_body'])) {
$validate = new validate();
// Validate Data from $_POST
$validation = $validate->check($_POST, array(
'comment_body' => array(
'name' => '<b>Comments</b>',
'required' => true,
'str_min' => 1,
'str_max' => 400,
'comment_filter' => true,
'sql_safe' => true
),
));
if($validation ->passed()){
$comment = escape($_POST['comment']);
try {
$user->create('video_comments', array(
'comment' => $comment,
'user_id' => $user->id,
'video_id' => $video,
'username' => $user->username,
'added' => date('Y-m-d H:i:s')
));
} catch(Exception $e) {
die($e->getMessage());
}
redirect::to($page);
} else {
session::flash('comment_error', 'Comment Failed');
redirect::to($page);
die();
}
} else { redirect::to(404); }
} else { redirect::to(404); }
UPDATE #1
the console error is showing me this:
GET (localhost/WEBSITES/myvideosite/css/homepage.css) - Failed to load resource: the server responded with a status of 404 (Not Found)
it points to my jquery <script src="js/jquery-1.11.3.min.js"></script> file which is defiantly there?
Sucess!
After a long day of researching and trying out different things I have finally got it to work!!
<script type="text/javascript">
$(document).ready(function(){
$("#submit-btn").click(function(){
var body = $('#comment_body').val();
var token = $('#auth-token').val();
if(body== null)
{
window.alert('Please enter a comment.');
}
else
{
$.ajax({
type: 'POST',
url: 'comment.php',
async: false,
data:{
'auth_token' : token,
'comment_body' : body
},
success: function(result){
//alert(result);
$('.comment-post').toggleClass("comment-hide");
$('.comment-sucess-hide').toggleClass("comment-sucess");
$('#comments_post').load(document.URL + ' #comments_post');
}
});
}
return false;
});
$('.del-com').click(function(){
var comid = $(this).attr('id');
$.ajax({
url: 'comment.php',
type: 'POST',
async: false,
data:{
'rmv' : comid
},
success:function(){
$('#comments_post').load(document.URL + ' #comments_post');
}
});
});
});
</script>
If anyone has some better suggestions please feel free to share as i am a real novice with js and really want to improve. Thanks to all that shared comments.

Get ID from mySQL and set localstorage in ajax with php

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!

Set a mysql table to Javascript variable using AJAX

I have a mysql table with 'user_name' and 'user_round'. I want the 'user_round' to be set to whatever the value of 'Level' (this is a javascript variable). My code brings up errors like POST 404 not found. Here is what I have:
<script type="text/javascript" src="jQuery.js"></script>
var <?php echo $_SESSION['user_name']; ?>; //Without this I get username not defined error?
var Level = 1;
function Fail() {
$.ajax({
type: "POST",
url: "phpfiles/savestage.php",
data: {
name: '<?php echo $_SESSION['user_name']; ?>',
stage: Level
},
success: function() {
console.log("Finished uploading stage");
}
});
Here is my php page:
<?php
include 'connect.php';
$sql="INSERT INTO DB NAME (user_round, user_name) VALUES ('$stage', '$name')";
$result = mysql_query($sql, $cn) or
die(mysql_error($cn));
?>
I've made a test here and the inspector says the ajax posted variable Level with value of 1
<script>
var Level = 1;
function Fail() {
$.ajax({
type: "POST",
url: "phpfiles/savestage.php",
data: {
name: 'test_name',
stage: Level
},
success: function() {
console.log("Finished uploading stage");
}
});
}
Fail();
</script>

Categories