Ajax doesn't do anything when php connected to database - javascript

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

Related

Communication between JavaScript, PHP and MySQL

I'm trying to learn JavaScript to code for Cordova.
I read many tutorials, but none of them helped me with the folowing problem.
My cordova app is for testing very simple. Just a textbox and 2 buttons. Both Buttons calls a PHP script on my server. One button sends data to the PHP script to insert the value of the textfield in a MySQL database, the second button calls the same script and should write the values of the database to my cordova app.
Here is my
<?PHP
$response = array();
require_once __DIR__ . '/db_config.php';
$db_link = mysqli_connect (
DB_SERVER,
DB_USER,
DB_PASSWORD,
DB_DATABASE
);
mysqli_set_charset($db_link, 'utf8');
if (!$db_link)
{
die ('keine Verbindung '.mysqli_error());
}
if(isset($_POST['action']) && $_POST['action'] == 'insert'){
$name = $_POST['name'];
$sql = "INSERT INTO test.testTable (name) VALUES ('$name')";
$db_erg = mysqli_query($db_link, $sql);
if (!$db_erg){
echo "error";
}else{
echo "ok";
}
}
if(isset($_POST['action']) && $_POST['action']=='read'){
$sql = "SELECT * FROM testTable";
$db_erg = mysqli_query( $db_link, $sql );
if (!$db_erg )
{
$response["success"] = 0;
$response["message"] = "Oops!";
echo json_encode($response);
die('Ungültige Abfrage: ' . mysqli_error());
}
while ($zeile = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
{
//$response["success"] = $zeile['pid'];
//$response["message"] = $zeile['name'];
$response[]=$zeile;
}
echo json_encode($response);
mysqli_free_result( $db_erg );
}
?>
and here are my 2 functions in the cordova app:
function getNameFromServer() {
var url = "appcon.php";
var action = 'read';
$.getJSON(url, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
function sendNameToServer() {
console.log("sendNameToServer aufgerufen");
var url2send = "appcon.php";
var name = $("#Name").val()
var dataString = name;
console.log(dataString);
if ($.trim(name).length>0) {
$.ajax({
type: "POST",
url: url2send,
data: { action: 'insert', name: dataString },
crossDomain: true,
cache: false,
beforeSend: function () {
console.log("sendNameToServer beforeSend wurde aufgerufen");
},
success: function (data) {
if (data == "ok") {
alert("Daten eingefuegt");
}
if (data == "error") {
alert("Da ging was schief");
}
}
});
}
}
My Questions/Problems:
The sendNameToServer funtion works in that case, that the data will be inserted in my Database. But I never get the alert (the success: never called).
How can I pass "action = read" to the PHP script in the getNameFromServer() function?
The third question is a bit off topic, but is this art of code "save" or is it simple to manipulate the data between the cordova app and the server? What's the better way or how can I encrypt the transmission?
Here is one part answer to your question.
$.getJSON has a second optional parameter data that can be an object of information you want to pass to your script.
function getNameFromServer() {
$.getJSON("appcon.php", { action: 'read' }, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
Edit: Since you are using $.getJSON(), the request method is a GET, which means you have to use $_GET in your third if statement in your PHP script.
if(isset($_GET['action']) && $_GET['action'] == 'read'){

Ajax code is not working in JavaScript

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 :)

Ajax login issues

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.

Using Ajax code to display a popup message when data get inserted in to the database

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>

Passing jQuery variable to PHP for error-handling

So I have taken a look around and I cannot seem to find the answer!
I'm trying to send a jQuery variable to PHP.
Code will explain it easier:
jQuery:
$error = 0;
$pageName = $(document).find("title").text();
$referrer = document.referrer;
if ($pageName == "Index") {
$('#index').hide();
console.log($pageName);
} else if ($pageName == "Testing") {
$('#testing').hide();
console.log($pageName);
} else if ($pageName == 'Test') {
$('#test').hide();
console.log($pageName);
} else {
$error = 1;
$.ajax({
type: "POST",
url: "../Ajax/post.php",
data: { param: $error, ref: $referrer }
}).done(function (msg) {
alert("Data Saved: " + $pageName + " " + $referrer );
});
}
PHP:
<?php
$error = $_POST['param']; //I have also tried putting '$error' here.
$referrer = $_POST['ref'];
if ($error == 1)
{
error_log("There has been an error with the pageName = " . $error . $referrer,
1,"Email#host.com","From: Email#host.com");
}
?>
TL;DR:
I am checking for the in my pages and then doing some jQuery functions, if the is unknown then email an error.
So the result I am getting in my email is "1" and that is it. Just the number 1 (which I presume is the $error value?
I'm just playing around with some error handling.
Check the if in PHP... the equals operator is ==, not =
if ($error==1)

Categories

Resources