I am using this code for my php MySql validation.
CheckID = document.getElementById('checkID_' + idCounter).value;
$.ajax({
type: "POST",
url: "checkval.php",
data: { check : CheckID }
}).done(function( data ) {
if(data !== "success");
{
var val = confirm(data);
if (val === false) {
return false;
}
}
});
This code is not working, Script wrote after that also not working. No idea about check the bug. help me.....
this is my php script
<?php
$check = $_POST['check'];
$host = 'localhost';
$database = 'database';
$username = 'user';
$password = 'password';
$dbc = mysqli_connect($host,$username,$password,$database);
$counter = count(checkArray);
$checkno = $check;
$sql = "select claimno from check_details where checkno = $checkno";
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
$claim = mysqli_fetch_array($result,MYSQLI_BOTH);
$claimno = $claim['claimno'];
$str = "Check Number:$checkno is already applied for $claimno.Are you sure to contniue ???";
echo $str;
}
else
{
echo "success";
}
?>
You could write your function to return "a promise to return the boolean status value":
function getMeStatus(checkID){
var def = $.Deferred(); // Create a deferred object
$.ajax({ // Make the ajax call
type: "POST",
url: "checkval.php",
data: {check: CheckID}
}).done(function (data) {
if (data !== "success"); {
var val = confirm(data);
if (val === false) {
// Status was false?
def.resolve(false);
}
else {
// Status was true?
def.resolve(true);
}
}
else {
// Status was true?
def.resolve(true);
}
}
// return a promise to supply the boolean status value later
return def.promise();
});
and use it like:
CheckID = document.getElementById('checkID_' + idCounter).value;
getMeStatus(checkID).done(function(status){
alert(status); // Use the value here
});
Note:
(Before everyone jumps on this,) this is not an anti-pattern if the return value has to be changed
This can be shortened a little, but the required logic from the question is not clear :)
Related
I'm trying to establish a simple connection between Javascript and my database using ajax and PHP. Javascript is supposed to receive a name from an HTML form, modify it and post it to PHP to check whether the name is already in the database and return true/ false back to javascript for further use.
Everything works fine as long as I don't add the part of code that connects to the database. Calling only the PHP file in Chrome also works and it will correctly print true or false.
As soon as I connect both together, nothing works. Neither success nor error will execute any of the code inside their functions.
JS1 + PHP1: Nothing happens
JS1 + PHP2: Correctly shows result in Alert1 and Alert2
PHP1 alone: Correctly prints either true or false
JS1
var boo = false;
if(str.length > 1) boo = true;
if (boo)
$.ajax ({
url: 's5Check.php',
type: 'post',
data: { str : str },
success: function( result ) {
alert(result); //Alert1
if(result != false){
boo = false;
alert(str + " already exists!"); //Alert2
} else {
boo = true;
alert(str + " doesn't exist!"); //Alert3
}
},
error: function( e ) {
alert("Error: " + e); //Alert4
}
});
PHP1
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$temp = mysqli_real_escape_string($con, $_POST['str']);
$check = "SELECT id FROM handle WHERE name = '$temp'";
$result = $con -> query($check);
if($result->num_rows > 0) {
echo true;
} else{
echo false;
}
} else{
echo "error";
}
?>
PHP2
<?php
echo $_POST['str'];
?>
Thanks.
echo true will output 1. echo false will output nothing. You're not checking for either of these in your success function.
Using JSON is a simple solution to this, and allows for easy enhancement to more complex results.
JS:
$.ajax({
url: 's5Check.php',
type: 'post',
data: {
str: str
},
dataType: 'json',
success: function(result) {
alert(result); //Alert1
if (result === false) {
boo = false;
alert(str + " already exists!"); //Alert2
} else if (result === true) {
boo = true;
alert(str + " doesn't exist!"); //Alert3
} else if (result === "error") {
alert("Error");
} else {
alert("Unknown problem");
}
},
error: function(jqXHR, txtStatus, e) {
alert("Error: " + e); //Alert4
}
});
PHP:
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$check = "SELECT id FROM handle WHERE name = ?";
$stmt = $con->prepare($check);
$stmt->bind_param("s", $_POST['str']);
$result = $stmt->execute();
$response = $result->num_rows > 0;
} else{
$response = "error";
}
echo json_encode($response);
?>
I have two files. 1 is the controller.php and 2nd verification.js
I need to redirect once the verify function successfully executed.
Controller.php
<?php
session_start();
error_reporting(E_ALL & ~ E_NOTICE);
require ('textlocal.class.php');
class Controller
{
function __construct() {
$this->processMobileVerification();
}
function processMobileVerification()
{
switch ($_POST["action"]) {
case "send_otp":
$mobile_number = $_POST['mobile_number'];
$apiKey = urlencode('aphfkjshjkskshfkjshfksjhfksjdh');
$Textlocal = new Textlocal(false, false, $apiKey);
$numbers = array(
$mobile_number
);
$sender = 'TXTLCL'; //urlencode('TXTLCL')
echo $otp = rand(100000, 999999);
$_SESSION['session_otp'] = $otp;
$message = "Your One Time Password is " . $otp;
try{
$response = $Textlocal->sendSms($numbers, $message, $sender);
require_once ("verification-form.php");
exit();
}catch(Exception $e){
die('Error: '.$e->getMessage());
}
break;
case "verify_otp":
$otp = $_POST['otp'];
ob_start();
if ($otp == $_SESSION['session_otp']) {
//unset($_SESSION['session_otp']);
echo json_encode(array("type"=>"success", "message"=>"Your mobile number is verified!"));
} else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
}
}
}
$controller = new Controller();
?>
2nd file verification.js
function sendOTP() {
$(".error").html("").hide();
var number = $("#mobile").val();
if (number.length == 10 && number != null) {
var input = {
"mobile_number" : number,
"action" : "send_otp"
};
$.ajax({
url : 'controller.php',
type : 'POST',
data : input,
success : function(response) {
$(".container").html(response);
}
});
} else {
$(".error").html('Please enter a valid number!')
$(".error").show();
}
}
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#mobileOtp").val();
var input = {
"otp" : otp,
"action" : "verify_otp"
};
if (otp.length == 6 && otp != null) {
$.ajax({
url : 'controller.php',
type : 'POST',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
}
I am not sure, where I need to put a redirection code. I want, once my mobile number is verified. This should be redirected to the abc.php page.
Thanks in advance, help me to resolve this issue.
The issue I am having is that I cannot seem to USE the result passed back to the original JS file from the PHP file called from the request. This is the result and handler:
if(creds_verification() == true){
$.ajax({
url:"scripts/scripts.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {url: URL, user: USER, password: PASS},
success:function(result){
var verdict = result
if(verdict == "Yes"){
Call another external function
}else{
console.log(results.abc)
}
}
});
}
The console is constantly printing "Yes", aka the result of results.abc... why would this happen? It SHOULD be executing the next function...
Added Info
PHP script running shell command and echoing the result:
scripts.php
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
echo json_encode(array("abc" => shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD")));
?>
And the JS file this is calling from the shell command:
test.js
var system = require('system')
var page = require('webpage').create()
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var URL = system.args[1]
var USER = system.args[2]
var PASS = system.args[3]
var steps = [
function() {
page.open('http://'+URL+'/login.html')
},
function() {
page.evaluate(function(USER, PASS) {
document.querySelector('input[name="log"]').value = USER
document.querySelector('input[name="pwd"]').value = PASS
document.querySelector('form').submit()
}, USER, PASS)
},
function(){
var newURL = page.url
if(newURL == 'http://'+URL+'/user.html'){
console.log('Yes')
}else{
console.log('No?')
}
}
]
var stepindex = 0
var loading = false
setInterval(executeRequestsStepByStep, 5000)
function executeRequestsStepByStep(){
if (loading == false && steps[stepindex]) {
steps[stepindex]()
stepindex++
}
if (!steps[stepindex]) {
phantom.exit()
}
}
page.onLoadStarted = function() { loading = true }
page.onLoadFinished = function() { loading = false }
It's because the code you call on the server (this means the result of scripts/scripts.php) instead of returning 'Yes' as the result is putting the 'Yes' in the abc property of a returned object.
Change the php code to:
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
$res = shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD");
echo json_encode($res == 'Yes' ? $res : array("abc"=>$res));
?>
Edit if the result of test.js is just "Yes" or "No" then change the PHP to
<?php
$URL = $_POST['url'];
$USER = $_POST['user'];
$PASSWORD = $_POST['password'];
$res = shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2>&1 $URL $USER $PASSWORD");
echo json_encode(preg_replace("/[^A-Za-z]/", '', $res));
?>
and the javascript to
if(creds_verification() == true){
$.ajax({
url:"scripts/scripts.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {url: URL, user: USER, password: PASS},
success:function(result){
if(result == "Yes"){
Call another external function
}else{
console.log(result)
}
}
});
}
I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.
When submitting my form I need to check in the database whether chassis and pin exists. If it exists i need to display a pop up message through Ajax. This is my code. But i am not getting any pop up message if the data has been inserted or if there is any error.Can you guys help me figure out where I am going wrong? Thanks in advance for your help.
AJAX CODE :
<script type="text/javascript">
$(document).ready(function () {
$("#user_submit_form").submit(function () {
var user_data = $("#user_submit_form").serialize();
if ($('#chassis').val() == '') {
alert('Please enter chassis');
} else if ($('#pin').val() == '') {
alert('Please enter pin');
} else
{
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function (user_data) {
if (user_data == "Data inserted") {
alert("Data inserted");
} else {
alert("fail!");
}
}
}); // End ajax method
}
});
});
</script>
PHP CODE:
<?php
session_start();
$hostname = '*****';
$database = '****';
$username = '****';
$password = '*****';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT chassis,pin FROM checking_chassis WHERE chassis="'.$chassis.'" && pin="'.$pin.'" ');
if(mysql_num_rows($sql) == 1)
{
echo "Data inserted";
}
else
{
echo "Error";
}
?>
first do this after submitting and check
$("#user_submit_form").submit(function(e){
e.preventDefault();
});
and when alerting return false;
OR
pass data like this
$data = array(
'status' => 1,
'message' => 'Data inserted'
);
echo json_encode($data);
and in success function use
var json = $.parseJSON(user_data);
alert(json.message);
I am trying this now but I don't think that the value is getting returned. It is just printing the content of the else statement
<script type="text/javascript">
$(document).ready(function (){
$("#user_submit_form").submit(function(){
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
var pincode = new Array();
pincode = $('#pincode').val().split("");
if($('#chassis').val() =='')
{
alert('Please enter chassis');
}
else if($('#pin').val() =='')
{
alert('Please enter pin');
}
else
{
$.post("validate_user.php",{"chassis":$('#chassis').val(),"pin":$('#pin').val(),"title":$('#title').val(),"fname":$('#fname').val(),"lname":$('#lname').val(),"email":$('#email').val(),"mobile":$('#mobile').val(),"dob":$('#dob').val(),"anniversary":$('#anniversary').val(),"company":$('#company').val(),"designation":$('#designation').val(),"home_business":$('#style').val(),"add1":$('#add1').val(),"add2":$('#add2').val(),"city":$('#city').val(),"state":$('#state').val(),"pincode":$('#pincode').val()},function(data) {
if(data == true)
{
alert("Error");
}
else
{
alert("Success");
}
});
}
});
});
</script>