if statement in success ajax - php

I'm having trouble implementing if statement in ajax success function.
<?php
include('../Config/config.php');
$myquery = "SELECT * FROM voters WHERE Precinct = '".$_POST['precinct']."'";
$execute = mysqli_query($mysqli, $myquery);
if (mysqli_num_rows($execute) >= 1)
{
echo "Precinct is full.\n Recheck precinct number.";
}
?>
function checkerprecinct() {
var precinct = $("#precinct").val();
$.ajax({
type: "POST",
url: "precinctchecker.php",
data: "precinct=" + precinct,
success: function(data) {
console.log(data);
if (data === "") {
alert("Data is empty!");
} else {
alert(data);
}
}
});
}
I would like to use this as a validation.
I want to alert the user if the sent data contains similar data from the database.

try this code
change with your code
PHP Code:
$data = array();
if (mysqli_num_rows($execute) >= 1)
{
$data= array('code'=>100,'message'=>"Precinct is full.\n Recheck precinct number.");
//echo "Precinct is full.\n Recheck precinct number.";
}else{
$data= array('code'=>101,'message'=>"Data is empty!");
}
echo json_encode($data);
exit;
ajax code:
var data = JSON.parse(data);
if (data['code'] == 100) {
alert(data['message']);
}

Related

Script is not fetching data from php to ajax script after success

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!

Ajax data type JSON not working

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;

Return a boolean from a PHP file to the AJAX one - Follow button

I'm creating a follow button, more or less like the twitter one.
You click the button, and you follow the user.
You click again, and you unfollow the user.
I have done this code
HTML
<div data-following="false" class='heart canal'><i class='fa fa-heart awesome'></i></div>
AJAX
$(document).ready(function() {
$(".heart.canal").click(function() {
if($(".heart").attr("data-following") == '0'){
$(".heart").attr('data-following', '1');
} else if($(".heart").attr("data-following") == '1'){
$(".heart").attr('data-following', '0');
}
var usuario = $(".left h4").attr("data-id");
var seguidor = $("#user_account_info .profile_ball").attr("data-id");
var seguir = $(".heart").attr("data-following");
$.ajax({
type: "POST",
url: "./include/php/follow.php",
data: { user: usuario, follower: seguidor, follow: seguir },
success: function(response) {
if(response == '0'){
$(".heart").addClass("like");
} else if(response == '1'){
$(".heart").removeClass("like");
}
}
});
return false;
});
});
PHP
<?php
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseƱa = "";
$conexion = new PDO($dsn, $usuario, $contraseƱa);
$resultado = null;
$sql = "";
$user = $_POST["user"];
$seguidor = $_POST["follower"];
$follow = $_POST["follow"];
if($follow == '0'){
$sql = "INSERT INTO seguidores(id_canal, id_seguidor) VALUES('$user', '$seguidor')";
} else if($follow == '1'){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
}
if($conexion){ $resultado = $conexion->query($sql); }
return $follow;
?>
The problem is, everytime I click the button, I only insert data in the database. I mean, I only create follows.
When I click twice, it doesnt remove the follow.
Is there anyway to insert data when data-following = true and remove it when data-following = false ?
UPDATED
I have changed the boolean false and true for 2 strings, 0 and 1. But it doesn't work anyway.
There are numerous problems here. For one, like #Mark said, you need to understand that when sending ajax requests to PHP, you are sending strings. Also, in your JS, you are binding a click function to the .heart.canal, but then the function changes all elements with that class rather than the actual clicked element. Lastly, once you send the right information to PHP you need to print your results in order to see it in ajax.
Try the following:
JS:
$(document).ready(function () {
$(".heart.canal").click(function () {
var $heart = $(this);
if ($heart.data("following")) {
$heart.data("following", false)
} else {
$heart.data("following", true);
}
var usuario = $(".left").find("h4").data("id");
var seguidor = $("#user_account_info").find(".profile_ball").data("id");
$.ajax({
type: "POST",
url: "follow.php",
data: {user: usuario, follower: seguidor, follow: $heart.data("following")},
success: function (result) {
if (result) {
console.log("true");
} else {
console.log("false");
}
}
});
return false;
});
});
PHP:
$user = (int)$_POST["user"];
$seguidor = (int)$_POST["follower"];
$follow = ($_POST["follow"] === 'true') ? true : false;
if ($follow) {
// insert
} else {
// delete
}
print $follow;

Using AJAX to return JSON from PHP

Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.

submit ajax form with condition

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

Categories