Session not sending correctly through AJAX - javascript

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.

Related

if(isset($_POST['btn-save'])) doesn't return true

Yep, this old chesnut I'm afraid. I've read through a lot of the previous answers to this question but I cannot get into this if statement even though 'btn-save' is definitely set as the name attribute on my submit button.
I'm using the code from this tutorial to post form data to my database: http://www.phpzag.com/ajax-registration-script-with-php-mysql-and-jquery/
My site structure is like this:
- root
- public_html
- js
app.js
register.php
db_connect.php
form_page.php
My register.php file looks like this and I've added an echo inside the if statement:
<?php
include_once("db_connect.php");
if(isset($_POST['btn-save'])) {
echo "in if";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_id = $_POST['email_id'];
$address_1 = $_POST['address_1'];
$address_2 = $_POST['address_2'];
$address_3 = $_POST['address_3'];
$city_town = $_POST['city_town'];
$county = $_POST['county'];
$post_code = $_POST['post_code'];
$entrant_type = $_POST['entrant_type'];
$chosen_store = $_POST['chosen_store'];
$chosen_charity = $_POST['chosen_charity'];
$agree_terms = $_POST['agree_terms'];
$sql = "SELECT user_email FROM tbl_big_challenge_registrations WHERE user_email='$email_id'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!$row['user_email']){
$sql = "INSERT INTO tbl_big_challenge_registrations('uid', 'first_name', 'last_name', 'user_email', 'address_1', 'address_2', 'address_3', 'town_city', 'county', 'postcode', 'entrant_type', 'crew_store', 'charity', 'agree_terms') VALUES (NULL, '$first_name', '$last_name', '$email_id', '$address_1', '$address_2', '$address_3', '$city_town', '$county', '$post_code', '$entrant_type', '$chosen_store', '$chosen_charity', 'agree_terms', NULL)";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);
echo "registered";
} else {
echo "1";
}
}
?>
My db_connect.php file looks like this (with dummy values for purpose of this post):
<?php
/* Database connection start */
$servername = "servername.com";
$username = "username";
$password = "password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
My form_page.php form looks like this:
<form id="2017-challenge-form" method="post" data-abide>
<!-- form fields are here -->
<input id="btn-submit" type="submit" name="btn-save" value="submit">
</form>
And finally my app.js looks like this:
$('document').ready(function() {
/* handle form submit */
function submitForm() {
var data = $("#2017-challenge-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").val('Submitting...');
},
success : function(response) {
if(response==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").val('Submit');
});
} else if(response=="registered"){
$("#btn-submit").html('<img src="ajax-loader.gif" /> Signing Up ...');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".register_container").load("welcome.php"); }); ',3000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").val('Submit');
});
}
}
});
return false;
}
$("#2017-challenge-form").submit(function(event){
// cancels the form submission
event.preventDefault();
// jumps into ajax submit function
submitForm();
});
});
I have a breakpoint set just inside the ajax success and on submission of the form I would expect the response to have a value of 'registered' (just like the Demo from the PHPZag site: http://phpzag.com/demo/ajax-registration-script-with-php-mysql-and-jquery/
But I get an empty string:
Can anybody see what I'm doing wrong or am missing?
I changed the input to a button as per the demo site and this worked. As per the comment by #frz3993 the btn-save wasn't getting added to the data so the if(isset($_POST['btn-save'])) was never true as it wasn't finding it.

ajax -- add comments asynchronously

I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".

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.

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.

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

Categories

Resources