$('#registerForm').submit(
function()
{
event.preventDefault();
callAjaxSubmitMethod(this);
}
);
function callAjaxSubmitMethod(form)
{
$.ajax({
type: "POST",
url: "lib/registration_validate.php",
data: $("#registerForm").serialize(),
dataType: 'json',
success: function(response)
{
console.log("cominggggg");
alert("s"+response.status);
},
error:function(response)
{
alert("e"+response.status);
},
complete:function(response)
{
console.log("Completed.");
}
});
}
This is how i am sending data to my php page.
<?php
include 'configdb.php';
session_start();
global $connection;
echo "oops";
if(isset($_POST['submit']) && $_POST['email']!='' && $_POST['password']!='')
{
$email= $_POST['email'];
$sql1 = "SELECT * FROM Users WHERE emailID = '$email'";
$result1 = mysqli_query($connection,$sql1) or die("Oops");
$response = array();
if (mysqli_num_rows($result1) > 0)
{
$response['status']='Email Already Exists';
echo json_encode($response);
exit;
}
}?>
I am just processing for duplicate email registration. If ia run this code in my chrome, i can see php in net tab. I can see completed in console and e200 in alert.
In my mozilla browser, i don't get any console strings, alerts. I din't get php page call in Net tab too.
I just cleared cache too. So it's not coming from cache too. I cleared localStorage due to out of memory error in my mozilla.
I don't even understand this behaviour. No idea to how to debug further.
I changed your code a bit, it seems that chrome accept the way you have made it, firefox does not.
So instead of this:
$('#registerForm').submit(
function()
{
event.preventDefault();
callAjaxSubmitMethod(this);
}
);
Do this:
$('#registerForm').on('submit', function(event) {
event.preventDefault();
callAjaxSubmitMethod(this);
}
);
Notice I added also the event param, you were missing that.
Related
For some reason Im getting a <br/> tag from nowhere in my response from the PHP function...
Here is the ajax:
var paid_value = 'Paid';
$.ajax({
url: 'http://localhost/myshop/owe_money/add_paid.php',
type: 'post',
data: { paid_value:paid_value } ,
beforeSend: function() {
$("#ajax-result").html('Before');
},
success: function(data) {
$("#ajax-result").html(data);
$('input[name="mark_as_paid"]').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
$("#ajax-result").html('Error');
}
});
And the PHP:
function add_paid() {
include('../db_connect.php');
$paid_value = $_POST['paid_value'];
if (is_numeric($paid_value)) {
$sql = "UPDATE paid SET first_item = $paid_value";
} else {
$sql = "UPDATE paid SET first_item = '".$paid_value."'";
}
if (mysqli_query($connect, $sql)) {
echo $paid_value;
} else {
echo "Unsuccesful".mysqli_error($connect);
}
die;
}
add_paid();
My response should simply be saying "Paid", but instead is saying "<br /> Paid".
on the face of it, it looks sound. You'll probably find that the br is going in somewhere else. Maybe it's even already in the file?
If it is finding it's way into the $_POST variable, you could temporarily hack the issue to use
$paid_value = strip_tags($_POST['paid_value]);
This answer comes with no warranty whatsoever!
In your jQuery code, change the success block to:
success: function(data) {
$("#ajax-result").html(data);
$('input[name="mark_as_paid"]').val(data);
console.log(data)
},
Open your debugger in the browser and view the console. This will write the value of data as sent from your PHP script, and may or may not have the line break in it. I suspect that the line break may be coming from the fist page but this will allow you to see this.
I cannot see any problem with the code so I think it has to do with the form/input where you are displaying the result - you have not included this.
you can use replace tag in success ajax
data.replace("but the br tag","");
but it will still exist in the database
I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); is not coming up. I think its some syntax I am missing.
$(function () {
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password },
function (result) {
alert('finished post');
//if the result is not 1
if (result == 0) {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
});
});
});
Here is the php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['username'];
$mypassword= $_POST['password'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();
$admin = $sql['admin'];
$password_hash = $sql['UserPass'];
$salt = $sql['salt'];
/*** close the database connection ***/
$dbh = null;
if(crypt($mypassword, $salt) == $password_hash){
// Register $myusername, $mypassword and redirect to file
$_SESSION['myusername'] = $myusername;
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 1;
if($admin == 1){
$_SESSION['admin'] = 1;
}
header("location:search.php");
}
else {
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 0;
echo 0;
}
Ok so I'll take a stab at this, see if we can work this out. First, let's clean up your code a little bit - clean code is always easiest to debug:
$(function () {
$("#login_form").on('submit', function(){
console.log('form submitted');
// get the username and password
var login_info = { username: $('#username').val(), password: $('#password').val() }
// use ajax to run the check
$.ajax({
url: '../php/checklogin.php',
type: 'POST',
data: login_info,
success: loginHandler
error: function(xhr, status, err){ console.log(xhr, status, err); }
});
return false;
});
function loginHandler(loggedIn){
if (!loggedIn) {
console.log('login incorrect');
} else {
console.log('logged in');
}
}
});
...ok great, we're looking a little better now. Let's go over the changes made quickly.
First, swapped alerts for console.logs - much less annoying. Open up your console to check this out -- command + optn + J if you're using Chrome.
Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. Really you should be using variables when they need to be used again, and in this case you only use them once.
Next, we swapped the $.post function for $.ajax. This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. Here are the docs for $.ajax for any further clarification.
We're also pointing the success handler to a function to minimize the nesting here. You can see the function declared down below, and it will receive the data returned by the server.
Finally we're returning false so that the page doesn't refresh.
Now, let's get to the issue. When you use this code, you should see a couple things in your console. The first will probably be a red message with something like 500 internal server error, and the second should be the results of the error callback for the ajax function. You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response.
I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead.
Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : )
Hope this helps!
Ah, so damned obvious. You aren't cancelling the default submit action so the form is submitting normally. Add this
$("#login_form").submit(function (e) {
e.preventDefault();
// and so on
See http://api.jquery.com/event.preventDefault/
you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page.
$("#login_form").submit(function (e) {
e.preventDefault();
Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this
checklogin.php?username=x&password=y
try this:
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password }, function (result) {
alert('finished post');
//if the result is not 1
if (result == '0') {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
}, 'text');
});
}, 'text');
maybe the server does not give the right data format. for example, if you request for json, and the jQuery cannot convert result sting to json. then the function would not be executed and then you would not able to get 'alert('got 0');' thing.
I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).
I have a login form using jquery ajax and a php code. The issue is that is always returns an error instead of logging me into the system. I have spent days trying to find the error but I can't. The webpage displays no errors if I visit it directly. This used to work about a week ago until I accidentally deleted the jquery and now I can't get it to work.
Here is the PHP code:
include('.conf.php');
$user = $_POST['user'];
$pass = $_POST['pass'];
$result = mysql_query("SELECT * FROM accountController WHERE username = '$user'");
while ($row = mysql_fetch_array($result)) {
if (sha1($user.$pass) == $row['pword']) {
setcookie('temp', $row['username']);
session_start();
$_SESSION['login'] = 1;
$_SESSION['uname'] = $row['username'];
echo "success";
}
}
and here is the Jquery AJAX code:
var username = $('#main_username').val();
var password = $('#main_pword').val();
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
user: username,
pass: password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
How would I check to see what is being returned like blank or success from the server. Is there any extension for safari? Thanks!
Put this in, instead. It will alert the server's response in a popup.
success: function(response) {
alert(response);
}
On your PHP side, try outputting more stuff - add an }else{ to your if statement that returns some useful data, for example
}else{
print("Post is: \n");
print_r($_POST);
print("\nMySQL gave me: \n");
print_r($row);
}
Just make sure you don't leave it in once it's working!
Look for:
hash is different
db field is different
db fields are blank for some reason
POST data is wrong / wrong field names
Edit: Here's another issue: Your first four lines should actually be:
$('.mainlogin').submit(function() {
var username = $('#main_username').val();
var password = $('#main_pword').val();
$.ajax({
Your code as it is gets the values before the form is submitted - at load - when they are blank, and as a result is sending blank strings to the server as username and password.
Take a look at the code i have in this answer here: user check availability with jQuery
You need to json encode your response, also Firefox has Firebug you can use to view your ajax post and response, chrome and IE both have developer tools
Safari also has dev tools: http://developer.apple.com/technologies/safari/developer-tools.html
Check the console to see what is happening with your AJAX