AJAX call and UPDATE query not functioning correctly - javascript

I am trying to send an UPDATE query to my update_divisions.php file via an AJAX call to update a player's division. I have a select box that I can choose the user from and then another select box that I can choose the division that I want to send. I did not include this, but I have an AJAX call that get's information from a php file that shows the usernames and the division they are currently in. That works perfect. So, I am just trying to update the division now. I have php error code on and I do not get any errors for that. I get an error in my network tab after I hit submit to send this of:
Uncaught syntax error...for this line in my AJAX call..
"username="+$user,
What am I doing wrong?
Here is my full code.
try {
//Prepare
if ($division_stmt= $con->prepare("SELECT * FROM team_rankings WHERE user_id=user_id")) {
$division_stmt->execute();
$division_stmt->bind_result($division_id, $division_user_id, $division_firstname, $division_username, $division_division, $division_wins, $division_losses);
//var_dump($division_stmt);
if (!$division_stmt) {
throw new Exception($con->error);
}
$division_stmt->store_result();
echo "<span class='top_bottom_margin'>Select a user to modify their team rank</span>". "<br>";
echo "<select id = 'member_division'>";
while ($division_row = $division_stmt->fetch()) {
echo "<option value='{$division_username}' data-username='{$division_username}'>{$division_username}</option>";
}
echo "</select>";
} else {
echo "<p>There are not any team players yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}
?>
<label>Current Division
<input type="text" id="current_division">
</label>
<form name="update_group_form" action="" type="POST">
<select name="division_name">
<option value="1">East</option>
<option value="2">West</option>
</select>
<input type="submit" value="submit" name="division_update_button">
</form>
AJAX call
$(document).ready(function(){
$("#update_group_form").on("change", function(){
$user = this.value;
$.ajax({
url: "update_division.php",
type: "POST",
data: {
"username="+$user,
division_name: $(this).find('select[name="group_id"]').val()
},
success: function(text){
alert(data);
},
error: function(jqXHR, textStatus,errorThrown )
{
// alert on an http error
alert( textStatus + errorThrown );
}
});
return false;
});
});
PHP file - update_division.php
$update_division = $_POST['division_name'];
$con = mysqli_connect("localhost","","","");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE division FROM team_rankings WHERE username = :user");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User Group update prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('i', $update_division)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('User Group update execute() failed: ' . htmlspecialchars($stmt->error));
}

You are trying to merge php and jquery as I can see.
Try to change this:
$user = this.value;
For this:
var user = this.value;
And this:
"username="+$user,
For this:
"username="+user,
Tell me if it works.

Related

updating MYSQL table gives success msg, but does'nt update the table

the AJAX msg gives successful, but the data doesn't update in DB, can you help plz!
html code:
<div class="row">
<input type="text" ng-model="updateId" class="form-control" placeholder="user Id To Update Phone">
<input type="text" ng-model="updatePhone" class="form-control" placeholder="user New Phone">
</div>
<div class="col-xs-3">
</div>
<div class="col-xs-2">
<button ng-click="updateuser()" type="button" class="btn btn-primary">Update </button>
</div>
</div>
javascript code:
$scope.updateuser = function () {
var data = {
updateId: $scope.updateId,
updatePhone: $scope.updatePhone
};
$.ajax({
data: data,
type: "post",
url: "update.php",
success: function(data){
alert("Data Updated");
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'Unauthorized') {
alert('custom message. Error: ' + errorThrown);
} else {
alert('custom message. Error: ' + errorThrown);
}
}
});
};
update.php code:
<?php
header('Content-Type: application/json');
include 'connect.php';
$db = new database();
$db->setDb_name('training');
$db->connect();
if(isset($_POST)){
$id = $_POST['updateId'];
$phone = $_POST['updatePhone'];
$data = $db->update('user',array('phone'=>$phone),array('id',$id));
echo json_encode($data);
}
mysql_close();
?>
the update() function:
public function update($table,$rows,$where)
{
for($i = 0; $i < count($where); $i++)
{
if($i%2 != 0)
{
if(is_string($where[$i]))
{
if(($i+1) != null)
$where[$i] = '"'.$where[$i].'" AND ';
else
$where[$i] = '"'.$where[$i].'"';
}
}
}
$where = implode('=',$where);
$update = 'UPDATE '.$table.' SET ';
$keys = array_keys($rows);
for($i = 0; $i < count($rows); $i++)
{
if(is_string($rows[$keys[$i]]))
{
$update .= $keys[$i].'="'.$rows[$keys[$i]].'"';
}
else
{
$update .= $keys[$i].'='.$rows[$keys[$i]];
}
// Parse to add commas
if($i != count($rows)-1)
{
$update .= ',';
}
}
$update .= ' WHERE '.$where;
$query = #mysql_query($update);
}
}
I am using angularJS, and when trying to run updating in update.php it works correctly, but using AJAX it gives "Data Updated" msg but actually doesnt update table.. why?
First of all, the ajax success callback from (I'm assuming) jQuery just means the HTTP request succeeded. This means it got a 200 response code. With most minor and some major errors in PHP the request will still be successful. If you want to know what went wrong, enable error reporting in PHP and be sure the errors are displayed:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Now, you should be able to see any errors. Use something like Chrome's developer console to see what error happened in your PHP code. Another option would be to log the error in PHP and check the error log after the request.

Session not sending correctly through AJAX

I have the following code that I thought worked correctly, but it turns out the users session is not being sent correctly. Let's say I was on trying to make a post, it does not take my id, it takes the id of the last user who registered for my site. Why would this be?
I have this as my $userid variable and it should be taking my session. I am initializing the session at the top of the page.
What am I doing wrong?
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP and Form
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
}
$user_stmt->store_result();
$user_result = array();
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
UPDATE: PHP file to show an example
// $announcement_user_id= $_POST['user_id'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $userid, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
You're selecting all of the users:
SELECT `id` FROM users
So when you get one record from that result, it's probably going to coincidentally be the latest record in the table.
You're trying to bind a parameter to i:
$user_stmt->bind_result($user_id);
so maybe you meant to have a WHERE clause?
SELECT `id` FROM users WHERE `id` = ?
Though, that seems... unnecessary. Since you already have the ID. You seem to be posting the ID from client-side, and keeping it in session state, and getting it from the database. So it's not entirely clear what you're even trying to do here. But one thing that is clear is that query is going to return every record from that table.

Secure AJAX POST/GET jquery

So basically my question is simple.
Imagine situation when you a making a login or register form. With jquery.post i make ajax call
$.post( "pages/form_handle.php", name: $.(".username").val(), pass: $.(".pass").val() , function( data ) {
$( ".result" ).html( data );
});
it's simple call(i belive so)...
How to make it secure?
So if user look in my source code he or she know where i send my data in example pages/form_handle.php also he or she know what data i send to this page.
One of idea what i have simple send all ajax calls to one page ajax.php adding extra variables who will call right php function for ajax call...
But does it is the right way? Or maybe there is some better way to make it secure?
Stick to basics, and keep salting your passwords.
AJAX is not server side language, its a javascript plugin that does the same thing as forms, actions, etc... just in background as a new request.
Your ajax is not in danger, but your php files are, you can use jquery-validate.js to check on users input, but also you should make validation check in your ajax.php.
Here is a simple ajax login request:
function loginUser() {
var process = "loginUser";
var data = $("form").serializeArray();
data[1].value = data[1].value; // data to ajax.php page
data = JSON.stringify(data);
$("#loginButton").html('Login');
$.ajax({
type: "POST",
url: "ajax.php",
data: {"process": process, "data": data},
success: function(data) {
if (data.response.state == "success") {
// if ajax.php returns success, redirect to homepage or whatever
} else {
// if ajax.php returns failure, display error
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
// error handling
},
dataType: "json"
});
}
And the simple ajax.php login:
<?php // ajax.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])){
$un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username='$un_temp'";
$result = mysql_query($query);
if (!$result) die("Database access failed: " . mysql_error());
elseif (mysql_num_rows($result)){
$row = mysql_fetch_row($result);
$salt1 = "qm&h*";
$salt2 = "pg!#";
$token = md5("$salt1$pw_temp$salt2");
if ($token == $row[3]) echo "$row[0] $row[1] :
Hi $row[0], you are now logged in as '$row[2]'";
else die("Invalid username/password combination");
} else die("Invalid username/password combination");
}else{
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function mysql_entities_fix_string($string){
return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string){
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
?>

How to define an element with a a sql row id usng JSON encoded data

I'm using jQuery AJAX to process form data, the PHP side of it should delete two files on the server and then the SQL row in the database (for the id that was sent to it). The element containing the SQL row should then change color, move up, delete and the next SQL rows move into its place. The animation stuff occurs in the beforeSend and success functions of the ajax callback.
This script is not working, when user clicks button, the page url changes to that of the php script but the item and files do not get deleted either on the server or in the database. Nor does any of the animation occur.
This is my first time using jQuery ajax, I think there is a problem with how I define the element during the call back. Any help would be great:
js
$("document").ready(function(){
$(".delform").submit(function(){
data = $(this).serialize() + "&" + $.param(data);
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function() {
$( "#" + data["idc"] ).slideUp(600,function() {
$( "#" + data["idc"] ).remove();
});
}
});
return false;
}
});
});
php
if (isset($_POST["id"]))
{
$idc = $_POST["id"];
if (isset($_POST["ad_link"]) && !empty($_POST["ad_link"]))
{
$ad_linkd=$_POST["ad_link"];
unlink($ad_linkd);
}
if (isset($_POST["listing_img"]) && !empty($_POST["listing_img"]))
{
$listing_imgd=$_POST["listing_img"];
unlink($listing_imgd);
}
try {
require('../dbcon2.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM listings WHERE id = $idc";
$conn->exec($sql);
}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo json_encode($idc);
}
html
<div id="record-<?php echo $id; ?>">
*bunch of stuff*
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>
You should fix your php code like this
try {
require('../dbcon2.php');
// It's better, if you will going to use MySQL DB, use the class designed to connect with it.
$conn = mysqli_connect("Servername", "usernameDB", "PasswordDB", "NameDB");
$sql = "DELETE FROM listings WHERE id = $idc";
mysqli_query($conn, $sql);
// you have to create a asociative array for a better control
$data = array("success" => true, "idc" => $idc);
// and you have to encode the data and also exit the code.
exit(json_encode($data));
} catch (Exception $e) {
// you have to create a asociative array for a better control
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// and you have to encode the data and also exit the code.
exit(json_encode($data));
}
Now in you JS code Ajax change to this.
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function(response) {
// the variable response is the data returned from 'delete_list.php' the JSON
// now validate if the data returned run well
if (response.success) {
$( "#" + response.idc ).slideUp(600,function() {
$( "#" + response.idc ).remove();
});
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
// add a handler to error cases.
error: function() {
alert("An Error has ocurred contacting with the server. Sorry");
}
});

Error in $.ajax call

I have an $.ajax call in one of my pages that links to a simple php page.
I am getting my alert for the error: property. I am not getting anything back in the errorThrown variable or in the jqXHR variable. I have never done this kind of thing before and i am not seeing what is wrong with my page.
JQuery $.ajax call :
function jsonSync(json) {
$.ajax({
type: 'POST',
url: 'http://www.cubiclesandwashrooms.com/areaUpdate.php',
dataType: 'json',
data: json,
context: this,
success: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error has occured! \n ERR.INDEX: Sync failed, ' + jqXHR.responseText + ';' + textStatus + ';' + errorThrown.message);
return false;
}
});
And this is my PHP Page :
$JSON = file_get_contents('php://input');
$JSON_Data = json_decode($JSON);
//handle on specific item in JSON Object
$insc_area = $JSON_Data->{'insc_area'};
//mysqlite connection.open() equivilent
$insc_db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($insc_db)) {
die('Could not connect: ' . mysql_error());
echo "Failed to connect to MySql: " . mysqli_connect_error();
//mysqli_close($insc_db);
}
//$insc_area.length equivilent
$insc_area_size = sizeof($insc_area);
//cycle through reult set
for ($i = 0; $i < $insc_area_size; $i++) {
//assign row to DataRow Equivilent
$rec = $insc_area[$i];
//get specific column values
$area = $rec->{'area'};
$id = $rec->{'srecid'};
//sqlcommand equivilent
$query = "SELECT * FROM insc_products WHERE id='$id' LIMIT 1";
$result = mysqli_query($insc_db, $query);
$num = mysqli_num_rows($result);
//dataReader.Read equivilent
while ($row = $result->fetch_array()) {
$query = "UPDATE insc_products SET area='$area' where id = '$id'";
$res = mysqli_query($insc_db, $query);
//checking if update was successful
if ($res) {
// good
error_log('user update done');
echo 'update was successful';
} else {
error_log('user update failed');
echo 'error in update';
}
}
}
echo 'testing php';
dataType: 'json'
means: give me json back. your PHP file isn't returning json formatted data
similar question: jQuery ajax call returns empty error if the content is empty
to buid a json response fill an array in the php file with the return information and use echo json_encode($array); at the end of the file. if you are using dataType:'json' because the code is copy/pasted, and you won't need the response to be in json format, simply remove this option...
Add following line in php file, $JSON_Data encode then it will work.
echo json_encode($JSON_Data);

Categories

Resources