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

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.

Related

Showing data and posted values separately in ajax post

i have a task which is about ajax post data and also ask the script to show data...I have 3 files.. HTML file perform an ajax to the php script, passwrapper.php and then include the another script to show all data in the json format on the console.log in the html file.. I implemented some ajax post values such as 'Abdullahlahlahlah' and 'Muslim' so that the passwrapper.php will receive those data and echo on the console separatley from the whole data... Developer said ajax cannot echo 2 times...... Is it totally impossible???? If there is no way, please tell me other options...
Requirement: Please do not modify the student.php as i want the that php script to echo all the data in json..
Modify the paswrapper.php and html file..
When i run the html file, the error states
Status Code: 200
ErrorThrown: SyntaxError: Unexpected token < in JSON at position 1634
jqXHR.responseText:
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]
Also there is the posted values on the console.log which states LastRowname = Abdullahlahlahlah LastRowReligion = Muslim
HTML File
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="results"</div>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullahlahlahlah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'");</script>';
}
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
in my network tab
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]<script>console.log("LastRowname = Abdullahlahlahlah LastRowReligion = Muslim");</script>
my requirement:
i want to echo all the data(except the posted values) on the html file.
i want to show the posted values on the console.log. it can either be in the passwrapper.php or html file..... Please help me....
ajax cannot echo 2 times;
1.student.php
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
//echo json_encode($json_array);
return $json_array;
2.passwrapper.php
<?php
include 'student.php';
$data['student_arr']=executePass();
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>
3.html file
success: function(data){
console.log(data.post_str);
$('#results').text(JSON.stringify(data.student_arr));
},
passwapper.php
<?php
include 'student.php';
ob_start();
executePass();
$string = ob_get_contents();
ob_end_clean();
$data['student_arr']=json_decode($string);
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>

Cannot login using php through jquery

I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?

Edit button inside table row only works in consecutive order

I am using php and javascript in order to display data from mysql in a table where each row must have an update button.
It seems to be working fine but i'm getting a weird behavior: it works when i click the buttons in consecutive order (#1 then #2 then #3..) but when i click them randomly (starting with #2 or #3...) it does nothing, just reloads the page.
Can you help me find what am i doing wrong, here's my code so far...
Thanks!
list.php:
<?php
$q= "SELECT * FROM list WHERE id = $f ORDER BY id";
if ($query = mysqli_query($db_con, $q)) {
$y=1;
echo '<table>'.
'<tr>'.
'<th>#</th>'.
'<th>Name</th>'.
'<th>Edit</th>'.
'</tr>';
while ($reg= mysqli_fetch_row($query)){
echo '<tr>';
echo '<td>'.$y.'</td>';
echo '<td>'.$reg[0].'</td>';
echo '<td>
<form id="frm_data'.$y.'" method="post">
<input type="hidden" id="name" name="name" value="'.$reg[0].'" />
<input type="hidden" id="f" name="f" value="'.$f.'" />
<input type="hidden" id="a" name="a" value="'.$a.'" />
<input id="FormSubmit" type="submit" value="EDIT">
</form>
</td></tr>';
$y = $y +1;
}
echo '</table>';
}
?>
validate.js
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
$("#FormSubmit").hide();
var myData = {
name: $("#name").val(),
a: $("#a").val(),
f: $("#f").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "update.php", //Where to make Ajax calls
dataType:"json", // Data type, HTML, json etc.
data:myData, //Form variables
success : function(data) {
if(data.status == 'success'){
alert("OK!");
} else if(data.status == 'error') {
alert("ERROR!");
}
},
error : function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
update.php
<?php
$f = $_POST["f"];
$name = $_POST["name"];
$q = "UPDATE list SET edited = '1' WHERE id = '$f' AND name = '$name' ";
$update_row = mysqli_query($db_con, $q);
if (!$update_row) {
$response_array['status'] = 'error';
} else {
$response_array['status'] = 'success';
}
?>

AJAX call and UPDATE query not functioning correctly

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.

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.

Categories

Resources