I am trying to get a form to check if a surname already exists in the database.
It seems like it is working, it checks the database and returns values, eg the number, as a string, of times the surname exists, or 'none' if they did not enter a surname.
The problem I am having is when I try to display the results.
JavaScript:
sName = $('#sName'), sInfo = $("#sInfo");
sName.blur(function() {
$.ajax({
type: "POST",
data: "sName="+$(this).attr("value"),
url: "check.php",
beforeSend: function(){
sInfo.html("<font color='blue'>Checking Surname...</font>");
},
success: function(data){
if(data == "none")
{
sInfo.html("<font color='red'>No Surname Entered</font>");
}
else if(data != "0")
{
sInfo.html("<font color='red'>Surname Exists</font>");
}
else
{
sInfo.html("<font color='green'>Surname Not Found</font>");
}
}
});
});
check.php:
//database connection stuff
extract($_REQUEST);
if(!empty($sName))
{
$sql = "SELECT sName FROM student WHERE sName='$sName'";
$rsd = mysqli_query($DBConnect, $sql) or die('Error: '.mysqli_error($DBConnect));
$msg = mysqli_num_rows($rsd);
mysqli_free_result($rsd);
mysqli_close($DBConnect);
}
else
{
$msg = "none";
}
echo $msg;
No matter what the value of data is (eg "1", "2", "0", "none") the sInfo div always displays "Surname Exists".
When I change it to display
else if(data != "0")
{
sInfo.html("<font color='red'>Surname Exists..."+data+"</font>");
}
The result is Surname Exists...0 or Surname Exists...none when it should instead display No Surname Entered or Surname Not Found...
What am I doing wrong?
thanks.
Change the line
data: "sName="+$(this).attr("value"),
to
data: {"sName":$(this).attr("value")},
jquery will format it correctly in the post body
Related
I don't really understand why this does not work - I have read a whole lot about this specific problem, but I must be missing something.
I want to alert the "echo" from the PHP - which it doesn't.
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "json",
success: function(data){
alert(data);
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "This is your current email";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "Your email is changed";
}
} else {
echo "Please provide a correct email";
}
The database is updating, do the script itself runs perfectly, but after the "success" - it doesn't alert anything.
UPDATE
I have now tried this:
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "text",
success: function(data){
if(data == 1) {
alert("This is your current email");
}
else if(data == 2) {
alert("Your email is changed");
}
else if(data == 3) {
alert("Please provide a correct email");
}
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "1";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "2";
}
} else {
echo "3";
}
The console is returning the raw data (1,2,3) but the alert is still not showing!
I am trying to insert data using AJAX JSON but it's not working. I tried without JSON and it works, but an alert box shows with some HTML code.
HTML:
Short Break
AJAX:
$(document).ready(function() {
$('#sbreak').on('click', function() {
var name = $("SBreak").val();
$.ajax({
type: "POST",
dataType: 'json',
url: "brkrequest.php",
data: {
sname: name
}
cache: false,
success: function(server_response) {
if (server_response.status == '1') //if ajax_check_username.php return value "0"
{
alert("Inserted ");
} else if (server_response == '0') //if it returns "1"
{
alert("Already Inserted");
}
},
});
return false;
});
});
PHP: :
session_start();
date_default_timezone_set('Asia/Kolkata');
$sname=$_POST['sname'];
$sname= $_SESSION['myusername'];
$reqdate = date("Y-m-d H:i:s");
include("connection.php");
//Insert query
$query = sprintf("SELECT * FROM `breakqueue` WHERE (`sname` ='$sname')");
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
$data['status']= '1';//If there is a record match Already Inserted
}
else { // if there is no matching rows do following
$query = mysql_query("INSERT INTO `breakqueue`(`id`, `sname`, `btype`, `reqdate`, `apdate`, `status`) VALUES ('','$sname','Sbreak','$reqdate','','Pending')");
$data['status']= '0';//Record Insered
}
echo json_encode($data);
}
use it in php
header('Content-Type:application/json');
and write
success: function(server_response){
console.log(typeof server_response);
...
for finding response type,
if type of server_response isn't object
use it for convert it to object :
server_response = JSON.parse(server_response);
php Code:
session_start();
//Here added...
header('Content-Type:application/json');
date_default_timezone_set('Asia/Kolkata');
$sname=$_POST['sname'];
$sname= $_SESSION['myusername'];
$reqdate = date("Y-m-d H:i:s");
include("connection.php");
//Insert query
$query = sprintf("SELECT * FROM `breakqueue` WHERE (`sname` ='$sname')");
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
$data['status']= '1';//If there is a record match Already Inserted
}
else{ // if there is no matching rows do following
$query = mysql_query("INSERT INTO `breakqueue`(`id`, `sname`, `btype`, `reqdate`, `apdate`, `status`) VALUES ('','$sname','Sbreak','$reqdate','','Pending')");
$data['status']= '0';//Record Insered
}
echo json_encode($data);
}
Javascript Code:
$(document).ready(function()
{
$('#sbreak').on('click', function(){
var name = $("SBreak").val();
$.ajax({
type: "POST",
dataType:'json',
url: "brkrequest.php",
data: {sname: name}
cache: false,
success: function(server_response){
//TODO:REMOVE IT After seeing. alert or console.log for seeing type
alert(typeof server_response);
if(typeof server_response){
server_response = JSON.parse(server_response);
}
if(server_response.status == '1')//if ajax_check_username.php return value "0"
{
alert("Inserted ");
}
else if(server_response == '0')//if it returns "1"
{
alert("Already Inserted");
}
},
});
return false;
I'm working on a webpage in which, when the user checks a checkbox, calling a PHP function to query the table if the user exists. If so, it then displays the button to go to next page.
So far I've tried this. I am sure that my php is working fine I checked my result variable returns 0 when user exists, but for some reason it is not executing the if statement.
$(document).ready(function() {
$('#submit').hide();
$('#mobiletask').change(function(){
if($('#mobiletask').attr('checked'))
{
check_availability();
// $( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
});
//function to check username availability
function check_availability(){
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == 0) {
//show that the username is NOT available
$('#submit').show();
}
});
}
checkusername.php
$username = mysql_real_escape_string($_POST['username']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('select studentId from smartphone_scores where studentId = "'. $username .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
Based on the response you are getting:
<html><body>1</body></html>
What you have to do is to work on your PHP file and make sure to remove any HTML in it.
Try this:
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == '1'){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == '0') {
//show that the username is NOT available
$('#submit').show();
}
});
$(document).ready(function()
{
$('#submit').hide();
$('#mobiletask').on('change',function() {
if($('#mobiletask').attr('checked'))
{
check_availability();
//$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
function check_availability()
{
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.ajax({
url: 'check_username.php',
type: 'POST',
async: false,
data: {'name':'username','value':username},
success: function(result)
{
alert(result);
//if the result is 1
if(result == '1')
{
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}else if(result == '0')
{
//show that the username is NOT available
$('#submit').show();
}
}, error: function(error)
{
alert(error);
}
});
}
});
** Remove the alerts when done with testing the code. **
hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});
**var ajaxUrl='admin/includes/validation.php?ref=enquiry&name='+$("#name").val() + '&email1='+$("#email1").val() + '&phone='+$("#phone").val()/*+ '&check='+a*/;
$.ajax({
type: "POST",
url: ajaxUrl,
data: "",
dataType: 'json',
success: function(msg){
//alert(msg);
if(msg!="")
{
$(".error").html("");
$(".err").attr("style","");
$.each(msg,function(key, value) {
if(value!="") {
//alert(value);
$("#"+key).attr("style","border:2px solid #000000;");
$("#Enq_"+key).html(value);
}
});
}
else
{
$("#contact").submit();
}
}
});**
Php file:
*if(!empty($check))
{
$countema = "select id, email from contactus where email='".$email."' ";
$exe_query=$Obj->_query($countema);
$fetch_Mail= $Obj->_fetch_array($exe_query);
$mail=($fetch_Mail['email']);
if(!empty($email) && ($email== $mail)){
echo 'This Email id already subscribed ';
}
/*$query=" insert into `news` set `email`='".escapestr($email)."',`status`='1', createddate='now' ";
$exe_query=$Obj->_query($query);
}
else
{
$query=" insert into `news` set `email`='".escapestr($email)."',`status`='1', createddate='now' ";
$exe_query=$Obj->_query($query);
}*/
use json_encode here
$resp = array();
if(!empty($email) && ($email== $mail)){
$resp['data'] = 'This Email id already subscribed ';
}
echo json_encode($resp);
Your JavaScript code expects JSON, what you return is text/plain. String This Email id already subscribed is not a valid JSON object. Valid JSON would be
{ "error" : true }
or something like this. In this case it's understood how to tell the front-end whether error occurred or not.
You would use it like this:
success: function(msg){
if (msg.error) { alert('An error has occurred! Everybody, get down!'); }