Ajax datatable Update with PHP MySql - php

I want to update data using Ajax and below is the sample code. The SweetAlert get displaced that it has been updated but it doesn't take effect in the database non thus it gives an error.
Ajax Code
This is the Ajax Script for the form submission when the submit button is clicked.
<script>
$('#submit').on('click', function(event){
event.preventDefault();
var firstname = $('#firstname').val();
var othername = $('#othername').val();
var gender = $('#gender').val();
var id_type = $('#id_type').val();
var id_number = $('#id_number').val();
var issue_date = $('#issue_date').val();
var business_place = $('#business_place').val();
var food_type = $('#food_type').val();
var screened = $('#screened').val();
var sub_metro = $('#sub_metro').val();
var telephone = $('#telephone').val();
var get_date = $('#get_date').val();
var chit_number = $('#chit_number').val();
var remarks = $('#remarks').val();
var user_id = $('#user_id').val();
var vendor_id = $('#vendor_id').val();
if (firstname!="" &&othername!="" && food_type!=""){
$.ajax({
url: "action/vendor_update.php",
type: "POST",
data: {
firstname:firstname, othername:othername, gender:gender,
id_type:id_type, id_number:id_number, issue_date:issue_date,
business_place:business_place, food_type:food_type, screened:screened,
sub_metro:sub_metro, telephone:telephone, get_date:get_date,
chit_number:chit_number, remarks:remarks, user_id:user_id, vendor_id:vendor_id,
},
cache: false,
success: function(data){
if(data.statusCode=200){
$('#dataForm').find('input:text').val('');
alert('Updated');
})
}
else if (data.statusCode=201)
{
alert('Cannot Update');
}
}
});
}else{
alert('All fields are mandatory');
}
});
PHP Code ---> action/vendor_update.php
This code is for the php server side for data insertion into the database.
<?
session_start();
// include('../includes/session.php');
include('./includes/connection.php');
$query = $dbh->$prepare("UPDATE vendors SET Firstname=:firstname, Othername=:othername, Telephone=:telephone, Gender=:gender, IdType=:id_type, IdNumber=:id_number, IdDate=:issue_date, BusinessPlace=:business_place, FoodType=:food_type, Notes=:remarks, ScreenStatus=:screened, ChitNumber=:chit_number, UpdatedBy=:user_id WHERE VendorId=:vendor_id");
$query->execute([
$firstname = $_POST['firstname'];
$othername = $_POST['othername'];
$telephone = $_POST['telephone'];
$gender = $_POST['gender'];
$id_type = $_POST['id_type'];
$id_number = $_POST['id_number'];
$issue_date = $_POST['issue_date'];
$business_place = $_POST['business_place'];
$food_type = $_POST['food_type'];
$remarks = $_POST['remarks'];
$screened = $_POST['screened'];
$chit_number = $_POST['chit_number'];
$user_id = $_POST['user_id'];
$vendor_id = $_POST['vendor_id'];
]);
// $query->execute($_POST);
if ($query->execute()){
echo json_encode(array("statusCode"=>200));
} else {
echo json_encode(array("statusCode"=>500));
}
?>

Here's the cleaned up PHP code:
<?php
// Tip:
// * Use named placeholders
// * Define the query string inside prepare() so you can't "miss" and run
// the wrong query by accident
// * Use single quotes so you can't interpolate variables by accident
// and create ugly SQL injection bugs
$query = $dbh->prepare('UPDATE vendors SET Firstname=:firstname, Othername=:othername, Telephone=:telephone, Gender=:gender, IdType=:id_type...');
// Use ONE of:
// A) if you have slight differences
$query->execute([
'firstname' => $_POST['firstname'],
'othername' => $_POST['othername'],
'telephone' => $_POST['telephone'],
...
]);
// OR
// B) if you're confident the placeholders match 100% and no clean-up
// such as trim() is necessary.
$query->execute($_POST);
if ($query->execute()) {
echo json_encode(array("statusCode"=>200));
} else {
echo json_encode(array("statusCode"=>500));
}
?>
Note: It's worth noting that code like this does not need to exist, that any decent ORM will make this trivial to do. It's worth exploring what options you have there as this could be so much easier.

Related

Ajax cannot display json data from php. What's wrong with json format?

I have read all the related questions that reference to this topic, but still cannot find answer here. So, php and ajax works great. The problem starts when i try to include json, between php and ajax, to passing data.
here is my ajax:
function likeButton(commentId, userId, sessionUserId) {
// check if the comment belong to the session userId
if(sessionUserId == userId) {
alert("You cannot like your own comment.");
}
else if(sessionUserId != userId) {
var like_upgrade = false;
$.ajax({
url: "requests.php",
type: "POST",
dataType: "json",
data: {
keyLike: "like",
commentId: commentId,
userId: userId,
sessionUserId: sessionUserId,
like_upgrade: like_upgrade
},
success: function(data) {
var data = $.parseJSON(data);
$("#comment_body td").find("#updRow #updComLike[data-id='" +commentId+ "']").html(data.gaming_comment_like);
if(data.like_upgrade == true) {
upgradeReputation(userId);
}
}
});
}
}
Note, that i try not to include this:
var data = $.parseJSON(data);
Also i tried with diferent variable like so:
var response = $.parseJSON(data);
and also tried this format:
var data = jQuery.parseJSON(data);
None of these worked.
here is requests.php file:
if(isset($_POST['keyLike'])) {
if($_POST['keyLike'] == "like") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sessionUserId = $_POST['sessionUserId'];
$sql_upgrade_like = "SELECT * FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result_upgrade_like = mysqli_query($conn, $sql_upgrade_like);
if($row_upgrade_like = mysqli_fetch_assoc($result_upgrade_like)) {
$gaming_comment_like = $row_upgrade_like['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update_like = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update_like = mysqli_query($conn, $sql_update_like);
$sql_insert_like = "INSERT INTO gaming_comment_likes (gaming_comment_id, user_id, user_id_like) VALUES ('$commentId', '$userId', '$sessionUserId')";
$result_insert_like = mysqli_query($conn, $sql_insert_like);
$like_upgrade = true;
//json format
$data = array("gaming_comment_like" => $gaming_comment_like,
"like_upgrade" => $like_upgrade);
echo json_encode($data);
exit();
}
}
Note: i also try to include this to the top of my php file:
header('Content-type: json/application');
but still not worked.
What am i missing here?
Don't call $.parseJSON. jQuery does that automatically when you specify dataType: 'json', so data contains the object already.
You should also learn to use parametrized queries instead of substituting variables into the SQL. Your code is vulnerable to SQL injection.

Ajax Form Validate Php Insert Query

i'm trying to add data to database with jquery. My code is here, but its not working.
Using bootstrap form, with that form i'm trying to send input datas to specific page (in this situation, adduser.php) in that page, i'm trying to check this values to database for be sure there is no same data (i'm checking email adresses)
Can you help me guys?
<script>
$(document).ready(function(){
$('#adduser').click(function(){
var add_name = $('#add_name').val();
var add_surname = $('#add_surname').val();
var add_email = $('#add_email').val();
var add_password = $('#add_password').val();
if(add_name == '' || add_surname == '' || add_email == '' || add_password == '' ){
$('#add_user_error').html("<strong class='text-danger'>*** Please enter all details</strong>");
}else{
$.ajax({
url: "adduser.php",
method: "post",
data:{add_name:add_name,add_surname:add_surname,add_email:add_email,add_password:add_password},
success: function(data){
if (data == 1) {
$('#add_user_error').html("<strong class='text-danger'>This email have in database</strong>");
}else{
$('#add_user_error').html("<strong class='text-success'>Success</strong>");
}
}
}); return false;
}
});
});
</script>
<?php
include ('setup.php'); //Database connection dbc
if(isset($_POST['adduser'])){
$add_name = $_POST['add_name'];
$add_surname = $_POST['add_surname'];
$add_email = $_POST['add_email'];
$add_password = $_POST['password'];
$q = "SELECT * FROM users WHERE email = '$add_email'";
$r = mysqli_query($dbc, $q);
$adduser = mysqli_fetch_assoc($r);
if($adduser['email'] !== $add_email){
$q = "INSERT INTO users (name,surname,email,password) VALUES ('$add_name','$add_surname','$add_email','$add_password')";
$r = mysqli_query($dbc, $q);
}
}
?>
There could be any other mistake too but I think you need to send adduser from ajax. Then only $_POST['adduser'] will be true (it is false now, as it isn't set)
Replace your data line with line below and try
data:{add_name:add_name,add_surname:add_surname,add_email:add_email,add_password:add_password,adduser:1}
In your ajax code pass your form data using serialize method
$.ajax({
url: "adduser.php",
method: "post",
data:$('#yourformid').serialize(),
/* your remaining code as it is */

PHP/MySQL/AJAX - Refresh query values with AJAX

I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.

Returning AJAX Success and Error

I have built a login script that uses AJAX to submit form data.
The PHP part works fine without AJAX. But the system doesnt work with AJAX Implementation.
It always Displays the below message even though the PHP file returns true[correct username & password] ... Seems like the if condition in Jquery is not working.
Incorrect Username/Password
HTML Result Div
<div id="user-result" align="center"></div>
Jquery
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data == "true") {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>
fn_login.php
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo "true";
}
else {
die();
}
}
}
?>
Can someone please point out the mistake in the code/practice.
EDIT
Just Tried disabling AJAX, the PHP file works correctly echoing true when username/pass is correct
You have spaces after ?>
So, the AJAX response is having spaces after true.
Solution:
Remove ?> from the end of PHP file.
It will not affect any PHP functionality.
And you AJAX response will be without spaces.
Excluding closing tag ?> from the end of PHP file is standard practice for modern PHP frameworks and CMSs.
Tips for debugging AJAX:
1) Always use Firefox (with Firebug Add) on Or Chrome.
2) Use Console tab of Firebug, to check which AJAX requests are going.
3) Here, you can see input parameters, headers and most important response.
4) So, in short you can debug a whole AJAX request life cycle.
You can echo json_encode(array('success'=>true)) from php code and modify your if condition in jquery with if(data.success){} Your modified code becomes
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo json_encode(array('success'=>true));
}
else {
die();
}
}
}
AND JQuery becomes
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data.success) {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

Categories