Posting data using Ajax - javascript

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

Related

AJAX not updating MySql data

I have created this PHP script to update the status of users. I am having some difficulty while running the below code. The code of the page is given below: -
$query = "DELETE FROM users WHERE id='$id' ";
$query_run = mysqli_query($conn, $query);
if($query_run)
{
$_SESSION['status'] = "Successfully Deleted";
header('Location: index.php');
}
else
{
$_SESSION['status'] = "Something Went Wrong.!";
header('Location: index.php');
}
The query here fails to run. The below ajax code sends the data to this page using a POST request
$.ajax({
type: "POST",
url: "code.php",
data: {
'checking_edit_btn': true,
'student_id': stud_id,
},
success: function (response) {
$.each(response, function (key, value) {
$('#edit_id').val(value['id']);
});
$('#editStudentModal').modal('show');
};
});
update It's working now, here is the final code:
$.ajax({
type: "POST",
url: "code.php",
data: {
'delete_student': true,
'student_id': stud_id,
},
success: function (response) {
$.each(response, function (key, value) {
$('#edit_id').val(value['id']);
});
$('#editStudentModal').modal('show');
};
});
where you sending 'update_student'/'delete_student'?
try to add to data
update_student: true
or
delete_student: true
depends on button

PHP not receiving AJAX POST from js File

I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}

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

Jquery AJAX with codeigniter, always returns error

I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.

Get ID from mySQL and set localstorage in ajax with php

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!

Categories