Get ID from mySQL and set localstorage in ajax with php - javascript

I have this working to a point, but would like, after true is returned, to set localstorage to value of the id passed in mySQL query. I'm unsure how to pass this, as my php currently echos only true or false.
<script type="text/javascript">
$(document).ready(function() {
$('#loginButton').click(function(){
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "login.php",
cache: false,
data: { username: username, password: password },
success: function(res) {
switch(res) {
case ('true'):
alert('true');
break;
case ('false'):
alert('false');
break;
}
}
});
return false;
});
});
</script>
<?php
$username = $_POST['username'];
$password = md5($_POST['password']);
if(!empty($username) && !empty($password)) {
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindValue('username', $username);
$stmt->bindValue('password', $password);
$stmt->execute();
if($stmt->rowCount() == 0) {
echo 'false';
} else {
echo 'true';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
}
}
}
$conn = null;
?>

If you want to respond with several values when using AJAX you may use JSON.
In php code it should be like this (paste it after $stmt->execute(); line instead of if-else construction):
if($stmt->rowCount() == 0) {
echo json_encode(array('success' => false));
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];
echo json_encode(array(
'success' => true,
'user_id' => $user_id
));
}
Then in javascript you should specify that you expect JSON as a response. This is a code:
$.ajax({
type: "POST",
url: "login.php",
cache: false,
dataType: 'json', //this is where we specify JSON response
data: { username: username, password: password },
success: function(res) {
if (res.success) {
localStorage.setItem('user_id', res.user_id); //set user id to local storage
alert(res.user_id);
} else {
alert('false');
}
},
error: function() {
//this will trigger in case the server send invalid JSON (or other types of errors)
alert('false');
}
});
I would also recommend to use GET method instead of POST in this case. POST is usually used when you need to change something of a server (database, session, file system, etc.), but when you want just get some data, it's better to use GET. However no one restricts you to do as you want, but I think it better to follow standard.
Good luck!

Related

is there any more parameters that i must add to AJAX function

I'm using $.ajax to insert data into database. But no data will be inserted and I don't receive any data in success function. Do I have to set more parameters into the success function?
That's what I currently have:
JS:
$.ajax({
url: '/pro.php',
data: {
'name':name,
'email':email,
'reply':reply
},
type: 'post',
success: function() {
}
});
PHP:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'redskydb';
$connection = mysqli_connect('localhost','yasi','ucsc','redskydb');
$name = $_POST['name'];
$email = $_POST['email'];
$reply = $_POST['reply'];
$query="INSERT INTO feedbacks (CusId,Reply,Name)VALUES('$email','$reply','$name')";
Check your ajax. Don't put the object keys in quotes and pass the success function the result parameter.
$.ajax({
url: './pro.php',
data: {
name: 'nameValue',
email: 'emailValue',
reply: 'replyValue',
},
type: 'POST',
success: function(result) {
console.log('this is result from call', result);
}
});
UPDATE
Please check your pro.php first it is not save an on the other hand, your Values(...) are set incorrectly. My code is just an example, how you could going through.
$mysqli = new mysqli("localhost", "root", "", "redskydb");
if($mysqli->connect_error) {
exit('Error connecting to database');
}
$stmt = $mysqli->prepare("INSERT INTO feedbacks (CusId, Reply, Name) VALUES (?, ?, ?)");
$stmt->bind_param($_POST['email'], $_POST['reply'], $_POST['name']);
$stmt->execute();
//here you could select with last_id and fetch the inserted row, but don't return before close()
$stmt->close();

Unable to parse response using ajax

So I have a js file that posts a JSON object using $.ajax, and then my php script takes that JSON object and does stuff to it, however, i can't get a json response back from the php script (the success callback function never runs).
register_script.js:
$.ajax({
method: "post",
dataType: "json",
url: "http://localhost/login/webservices/register2.php",
data: {
reg_username: username,
email: email,
reg_password: password,
confirm_password: confirm_pass
},
success: function (data) {
alert("hello?");
//alert(data.status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
});
register2.php:
if (isset($_POST['reg_username'], $_POST['email'], $_POST['reg_password'], $_POST['confirm_password'])) {
$username = $_POST['reg_username']; //$_POST['from html']
$email = $_POST['email'];
$password = hash('md5', ($_POST['reg_password']));
$confirm_password2 = hash('md5', ($_POST['confirm_password']));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username','$email','$password')";
if ($password == $confirm_password2) {
$response = sqlsrv_query($conn, $sql);
if ($response) {
$data = array(
"username" => $username,
"email" => $email,
"password" => $password,
"confirmPass" => $confirm_password2,
"status" => "Registered",
);
echo "Registered \n";
}
}
}
//...
//some other validations
//...
echo json_encode($data);
I have a feeling the way i am handling the json object is incorrect. any help would be really appreciated.
you should not
echo
anything other than json_encode when working with ajax dataType : json you have
echo "Registered \n";
before
echo json_encode
remove that and it should work
EDIT:
when you set the dataType : "json" in your ajax call then the response is expected to be in json when the call is finished, and any text other than json encoded string in response will result in an error. if you still need to debug and see what route the script is taking, you can add another index in $data (i assume that $data is an array), so it would be like
if($registered){
$data['debug_logs'] .='Registration successfull----';
}
if($emailSent){
$data['debug_logs'].='Email sent for registration-----';
}
echo json_encode($data);
and then in your ajax success function you can use it like
success:function(data){
console.log(data.debug_logs);
}
hope it clears your confusion.
Please remove echo "Registered \n"; the line from your code when you echo "Register"; the Ajax request return this back to the browser, and your actual data echo json_encode($data); never return back to the browser.

Return value from Ajax [duplicate]

This question already has answers here:
Get response from PHP file using AJAX
(5 answers)
Closed 5 years ago.
I'm new to programming and i'm not good at all with Ajax.
I want to get a value back from a php script in Ajax.
I send a javascript variable to a php script like that :
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
});
return false;
}
});
This is sent to the following php script which is deleting messages according to the id contained in the checkboxIdArray:
if (isset($_POST['checkboxIdArray'])) {
$checkboxIdArray = $_POST['checkboxIdArray'];
$str = json_encode($checkboxIdArray);
$tab = explode(",", $str);
$deleteSuccess = true;
foreach($tab as $id)
{
$id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
if (!$messageModelDb->delete($id)) {
$deleteSuccess = false;
die();
}
}
if ($deleteSuccess === true) {
$message = 'Success';;
} else {
$message= "Error";
}
}
I want to get the $message variable back to my javascript in order to display a message according to the result of the script.
I would really appreciate some help ...
Thank you.
You have to use success function and actually include the message in the response
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
},
success : function(response){
// your code or logic
alert(response);
}
});
PHP
if ($deleteSuccess === true) {
$message = 'Success';
} else {
$message= "Error";
}
echo $message;
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
},
success: function(response){
alert(response);
}
});
return false;
}
});
There is nothing special about an HTTP request made with JavaScript.
You output data in the response to it in from PHP in the same way as any other HTTP response.
echo $message;
In JavaScript, you process it as described in the documentation for jQuery.ajax.
Write a function that accepts a the response content as the first argument.
Then call done on the jqXHR object that .ajax returns and pass it that function.
function handleResponse(data) {
alert(data);
}
var jqXHR = $.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
});
jqXHR.done(handleResponse);
Try out the code to get the value in ajax
<script>
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
}).done(function(result)
{
alert(result);
});
return false;
}
});
</script>
Here is the php code
<?php
if (isset($_POST['checkboxIdArray'])) {
$checkboxIdArray = $_POST['checkboxIdArray'];
$str = json_encode($checkboxIdArray);
$tab = explode(",", $str);
$deleteSuccess = true;
foreach($tab as $id)
{
$id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
if (!$messageModelDb->delete($id)) {
$deleteSuccess = false;
die();
}
}
if ($deleteSuccess === true) {
$message = 'Success';;
} else {
$message= "Error";
}
echo $message;
}
?>
Since jQuery implemented deferreds, .done is the preferred way to implement a success callback. You should also implement a .fail method with a failure response code.

Posting data using Ajax

I've been trying to post data using AJAX that will update a field in my database however I am having trouble doing so. Everything seems like it should run fine and I get no errors in the console but I've no idea why my db won't update.
Can someone help me out here please?
AJAX:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
console.log("success");
}
});
}
Confirm.php:
$name=$_POST['var1'];
$age=$_POST['var2'];
if($name == "Stuart") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
else if($name == "Peter") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
The connection to my database is working as I have $connection setup and went to the page /ajax/confirm.php in my browser and I see "Connection successful" in my console as I defined if successful.
So I am unsure as to why this isn't updating?
Are my values not being posted correctly?
I'm new to AJAX so forgive me if this is something very simple!
Thanks
Try the following:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: arr,
success: function(data) {
console.log("success");
}
});
}
Instead of converting the object into json string send it as is.
Edit: Also remove dataType and probably contentType too. Your code is at risk of SQL Injection. Look into prepared statements and escaping mysql data.
Maybe this well help.
<script type="text/javascript">
function ajaxUpdate() {
var data = $('#formID').serialize();
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: data,
dataType: 'json',
encode : true,
success: function(data) {
if(data == "ok"){
console.log("success");
}else{
console.log(data);
}
}
});
}
</script>
confirm.php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
switch ($name) {
case 'Stuart':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
case 'Peter':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
default:
echo json_encode('Unknown name ');
}

Does ajax need contentType to send to php ? if so why error?

I been trying to figure this one out but i don't seem to find the error but in my script
My script
$('#Bshift').click(function(){
var isValid=false;
isValid = validateForm();
if(isValid)
{
var ArrId= <?php echo json_encode($arrId ); ?>;
var ArrQty= <?php echo json_encode($arrQty ); ?>;
var counter= <?php echo json_encode($i ); ?>;
var productId;
var productQty;
for (i = 0; i < counter; i++) {
productQty = ArrQty[i];
productId= ArrId[i];
var pLocal= document.getElementById(productId).value;
var prodData = 'pLocal=' + pLocal+ '&proId='+productId;
$.ajax ({
url: 'shiftSave.php',
type: 'POST',
data: prodData,
dataType: 'json',
contentType: "application/json; charset=utf-8", // this is where have the error
});
}
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = 'pettyCash=' + pettyCash+ '&comment='+comment;
$.ajax ({
url: 'shiftSave.php',
type: 'POST',
data: prodData1,
dataType: 'json',
contentType: "application/json; charset=utf-8 ", // Error here too
}).done(function(data){
alert("Data Saved. Shift Started.");
document.getElementById("register").reset();
document.getElementById("Bshift").disabled = true;
document.getElementById("StartingB").disabled = true;
}).fail(function(error){
alert("Data error");
});
}
});
Everytime i put the ContentType the script goes to done but if I take it off then my sql on my php executes and gives me a responce
Php code shiftSave.php
<?php
include "connection.php";
session_start();
$data=array();
$location="";
if (isset($_SESSION['location'])) {
$location=$_SESSION['location'];
}
if (isset($_SESSION['eId'])) {
$empId=$_SESSION['eId'];
}
if(#$_POST['pLocal']) {
$proQty = $_POST['pLocal'];
$proid = $_POST['proId'];
try {
$sql = "UPDATE location_product SET productQty='".$proQty."' WHERE productId='".$proid."' and productLocation='".$location."'";
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
echo "Record updated successfully!";
//$data["secion"]=$stmt. " this ";
if ( !$stmt) {
$data["match"]=false;
} else {
//echo "Error updating record: " . $conn->error;
echo "Record updated successfully!";
$data["match"]=true;
}
echo json_encode($data);
} catch (Exception $e) {
$data["match"]=false;
echo json_encode($data);
}
}
if (#$_POST['pettyCash']) {
$pettyCashIn=$_POST['pettyCash'];
$comment= $_POST['comment'];
try {
$sql = "INSERT INTO `customer_service_experts`.`shift` ( `empId`, `pettyCashIn`, `note`) VALUES ( '$empId', '$pettyCashIn', '$comment')";
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
if ( !$stmt) {
$data["match"]=false;
} else {
echo "Record updated successfully!";
$data["match"]=true;
}
echo json_encode($data);
} catch (Exception $e) {
$data["match"]=false;
echo json_encode($data);
}
}
?>
when i execute without the contentType it goes true but it fails and gives me Data error (the alert that i used on the function fail), but if I use the contentType it goes to the function .done and goes trough but the query does not execute.
You also need to stringify the data you send like so
data: JSON.stringify(prodData1),
You could make a helper function which you can use everywhere you want to do a JSON POST
function jsonPost(url, data, success, fail) {
return $.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: success,
error: fail
});
}
Does ajax need contentType to send to php ?
And you have a contentType: "application/json; charset=utf-8", which sends data in request payload but if you omit it/remove it from ajax then by default contentType for jquery ajax is application/x-www-form-urlencoded; charset=UTF-8.
Lets see both of them here:
A request with Content-Type: application/json may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
And if you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded (It is default for jquery ajax) or Content-Type: multipart/form-data your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
So if you send the data in request payload which can be sent via Content-Type: application/json you just can't take those posted values with php supergloabals like $_POST.
You need to fetch it yourself in raw format with file_get_contents('php://input').
Firstly remove the content-type option. Let jQuery use the default.
Second,
change:
var pLocal= document.getElementById(productId).value;
var prodData = 'pLocal=' + pLocal+ '&proId='+productId;
to:
var pLocal= document.getElementById(productId).value;
var prodData = { pLocal: pLocal, proId: productId };
and:
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = 'pettyCash=' + pettyCash+ '&comment='+comment;
to:
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = { pettyCash: pettyCash, comment: comment };

Categories