Issues inserting data into my database after user has logged in - javascript

I have a script that I would like to have run using jQuery and PHP. After a user logs in, they fill out a form and hit the 'save' button. The jQuery attaches a click event which runs the PHP script. I've got console logs at certain break points and I'm showing that my script is actually stopping at a certain point, however, I have no idea why.
TABLE CREATION AND DATABASE CONNECTION
$create_table_scenarios = "CREATE TABLE IF NOT EXISTS $scenarios(id VARCHAR(25), PRIMARY KEY(id))";
mysqli_query($connect, $create_table_scenarios);
I know that the connection is being made and the table is being created because it shows up in the database.
THE FORM
<form id="scenario_builder" method="post" action"../php/processing.php">
<div id="form_general" class="form_view">
<h3>General Info</h3>
<div class="half">
<fieldset for="center_menu">
<label>Center:</label>
<div class="select" name="center_menu" id="center_menu">
<div class="arrow"></div>
<div class="option-menu">
<div class="option"></div>
<?php
$query = "SELECT * FROM $centers";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$center_name = "{$row['center']}";
echo "<div class='option'><input type='hidden' name='center' id='center' value='" .$center_name ."' />" .$center_name ."</div>";
}
?>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<input type="submit" name="save" id="save" class="button" value="Save" />
</form>
PROCESSOR
ob_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$center = $_POST["center"];
$query = "INSERT INTO `$scenarios`(`id`) VALUES('" .$center ."')";
mysqli_query($connect, $query);
}
ob_clean();
echo json_encode(array("success" => 1));
jQUERY
$("input[id='save']").on("click", function(){
console.log("Save clicked");
$.post("..php/processing.php", {}, function(response){
if(response.success == "1"){
console.log("Data entered.");
}
else{
console.log("Data not entered.");
}
}, "json");
})
The only console message I'm getting is the "Save clicked" one. So, for some reason, the $.post function isn't running. Can someone show me why based on the code I've provided? On a different note, yes, I understand that my queries are vulnerable to injection, I'm just trying to get the basics to work right now.

From what i see you are double submitting the form. You once submit the form due to the form's submit button push and the second time you submit the form with the AJAX request due to the event handler you added to the button. You either let the form submit with a regular POST, or on the submit button press you prevent the event's default behavior and submit the data by AJAX.

Related

How do I get my delete button to remove data from database?

I have a delete button which when clicked it prompts user for conformation. It suggets it is working but when I check the database the data is still there.
How do I get my delete button to remove data from the database?
<?php
// build query
$sql= "SELECT blogID, title, made_by, description FROM blogs";
// execute query
$res=$mysqli->query($sql);
// get multiple results
while($row = $res->fetch_assoc()){
$blogID=$row['blogID'];
$title=$row['title'];
$made_by=$row['made_by'];
$description=$row['description'];
?>
<form action = "post_action.php" method="POST">
<div style="text-align:left">
<div class="row">
<div class="leftcolumn">
<div class="card">
<td><?php print($title);?></td><br>
<td> <?php print($description);?> </td> <br>
<td><?php print($made_by);?> </td><br>
<?//Create edit, comment and delete buttons for each blog?>
<button onclick="window.location.href = 'edit_blog.php';">Edit Blog </button>
<input type = "hidden" name="blogID" value= "<?php print($blogID);?>" >
<input type="submit" name="action" value="Insert Comment"/>
<input type="submit" onclick="deleteme(<?php echo $row['blogID']; ?>);" name="action" value="Remove Blog"/>
<? //Javascript code?>
<script language="javascript"> //inserts javascript code
function deleteme(delid)
{
if(confirm("You're about to delete this blog. Click OK to continue or click cancel.")){ //opens an alert window asking the user if they're they want ot remove the blog
window.location.href='post_action.php?del_id=' +delid+''; //If they click OK then it'll run the delete function on post_action.php
return true;
}
}
</script> <?//ends javascript code ?>
</form>
</div>
This is post_action.php
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_POST['blogID']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
Because you did not execute your delete action. Execute your delete query to remove the data to your database.
$mysqli -> query($query)
The problem is in $_POST['blogID'].
You are redirecting the user and passing the blog id in the query string, so it should be $_GET. Also the key is del_id and not blogID.
So in post_action.php, do
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_GET['del_id']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
PS: I am really worried about if you should delete something this way.

How to avoid inserting two time in double click time in codeigniter

I am search the other result of related question and that i implement in my code but that not working ,i have 2 button in a form
my form
<form id="InVoice" action="<?php echo base_url('Staff/add_invoice_spare');?>" method="post" class="form-horizontal">
/*-- content herer--*/
<button style="float:right;" type="submit" name="ready" value="Ready For Bill" class="btn btn-danger" style="border-radius:60px;">Add to Ready for Bill</button>
<button style="float:right;margin-left:15px;" type="submit" name="print" class="btn btn-danger" style="border-radius:60px;">Print</button>
<?php echo form_close(); ?>
and used script is
<script type="text/javascript">
$(document).ready(function() {
$("form#InVoice").submit(function() {
alert();
$('button[type=submit]').prop('disabled',true);
return true;
});
});
</script>
this my controller for inserting
public function add_invoice_spare()
{
$bill=$this->input->post('ready');
if($bill)
{
$reg=$this->input->post('rno');
$data=array(
/*-----------datas here-----*/
);
$ans=$this->Bill_model->check_registration($reg);
$form_data= $this->input->post();
$result=$this->Bill_model->invoice_dtls_ready($form_data,$data);
if($result){
redirect('Staff/list_invoice/'.$result);
}
}else{
$reg=$this->input->post('rno');
$data=array(
/*-----------datas here-----*/
);
}
$form_data= $this->input->post();
$result=$this->Bill_model->invoice_dtls($form_data,$data);
if($result)
{
?>
<script type="text/javascript" language="Javascript">
window.open('invoice_pdf/<?PHP echo $result ?>', '_blank');
window.location.href = "invoice_labour";
</script>
<?php }
}
}
but in double click or single click the Add to Ready for Bill button the print button is work why that redirect?
any way to solve this issue and only one time submitte the data ?
thanks in advance!!!
Both the buttons that you are clicking on are of the type submit or they are submit buttons. So the only way to differentiate this will be at the backend.
For eg, according to the above example when you submit the $_POST array will have the submit button value. It is based on this value that you have to build your code logics.
If you click on Print then $_POST['submit'] will be the value will be print and when you click on "Add to Ready for Bill" the $_POST['submit'] value will be ready.
If you want to control it in the Frontend i.e., jQuery end you can by using the preventDefault (the example of which is given by #pradeep) but I suggest you modify the Backend as well to differentiate between these 2 submit buttons.
Hope this helps.

Variable assigned to HTML input's value through PHP is not understood by JS script

I'm working on a project of a website which shows a chart. User should be able to change a displayed chart (without changing the website) by clicking one of 'Available sensors' from dropdown options. Dropdown connects to MySQL database with used sensors. The sensor's id is assigned to HTML-input ID and its name is assigned to input value.
My intension is to use sensor ID in another data.php file which is responsible for connecting to tables (MySQL) with data collected by sensors. This ID would tell to which of the tables this programm should connect.
At the moment JS script's task is to alert an ID of the chosen sensor when it's clicked on the dropdown menu. Instead of a number I get a message saying 'undefined'. Eventually it would transfer the stored id to the mentioned data.php file.
Could you please tell me whether it's necessary to use AJAX in this case or what's a possible reason of this error in my code?
I also tried to use button insted of input. When clicking on sensors names on dropdown I've received only messages with '1'. However assigning sensorName worked out in both cases. Sensors ID is stored as INT, name as VARCHAR in MySQL table.
Thank you in advance for your help :)
<div id="header_btn" class="dropdown">
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?>
<input onclick="changeSensorID(this.value)" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>" value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script>
function changeSensorID() {
var sensorID = document.getElementsByClassName("btn_drop").id;
alert(sensorID);
};
</script>
</div>
please check this code, working fine
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?><input onclick="changeSensorID(event)" onmouseover="this.style.textDecoration='underline'"
onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>"
value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script >
function changeSensorID(event){
var sensorID = event.target.id;
alert(sensorID);
}
</script>
</div>
getElementsByClassName returns array of at least one item if found any. You have to provide index of element that you want to use.
Example
var sensorID = document.getElementsByClassName("btn_drop")[0].id;

Guestbook application doesn't work. I used html, php, mysql, javascript. Can't add messages to the guestbook page

I have a simple application to make and i'm struggling to make it work.
It's a guestbook page which I have to make and it must have 3 fields:
Name
Email
Message box
A submit button.
All of the message must be at least 5 chars and at the push of the button, it must get under the message box.
For this, I created
I. Three files:
1.index.html - where is the main code in JS and also html
2.addcomment.php
3.guestbook.php
II. One Database (which I named it "db1")
The Problem is that when I click submit, instead of recording the comment underneath, the addcomment.php code appears in my html page. What could be the problem.
I won`t put the "head" part of the index.html page here because it's only JS which checks the fields to be correct. I'll put the "body" of the html page so you can tell me if something it's wrong:
//Update:
<body>
<div id="wrapper"
</div>
<div id="menu">
<hr/>
<ul id="mainMenu">
<li>Home</li>
<li>Guestbook</li>
</ul>
<hr/>
</div>
<div id="content">
//finished update
<h2>Sign to the Guest Book </h2>
<form name="guest" method="post" action="addcomment.php" onsubmit="return Validate();">
<span>Name:</span> <input type="text" name="name"/><br />
<span>Email:</span> <input type="text" name="email"/><br />
<p>Message:</p> <textarea name="message" rows="10" cols="50"> </textarea> <br />
<input type="submit" value="Sign this in the Book" />
</form>
</div>
</div>
<div id="footer">
<hr/>
<p>Thank you for the visit! </p>
</div>
</body>
</html>
the addcomment.php code which is called above:
<?php
$host="localhost";
$user="db1";
$pass="test123";
$dbname="db1";
$con=mysqli_connect($host,$user,$pass,$dbname);
if (mysqli_connect_errno($con))
{
echo "<h1>Failed to connect to MySQL: " . mysqli_connect_error() ."</h1>";
}
$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['message'];
$sql="INSERT INTO db1(name,email,message) VALUES('$name','$email','$message')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
echo "Values stored to db!";
mysqli_close($con);
?>
So. I installed XAMMP. and using xammp control panel I started the server Apache and MySql. Using that, I created a db using localhost/phpmyadmin which I named "db1". I gave the user and db the same name and I granted all acces for that user to my database.
Here is the SQL query I used for the table creation in phpmyadmin to my "db1":
CREATE TABLE db1(
id int(5) NOT NULL auto_increment,
name varchar(60) NOT NULL default ' ',
email varchar(60) NOT NULL default ' ',
message text NOT NULL,
Primary key(id)
);
Can you tell me why my page doesn't work? Why the messages doesn`t post? I simply don't get it and tried everything the past weekend.
Thanks a lot
Update: It worked. It seems that if we call it from the address bar and not from the folder with double click, it works. I just wrote in the address bar: localhost/guestbook, and it worked.
Here is my other file "guestbook.php" which I used to show on the index.html page the comments from the users:
<?php
$host="localhost"; //Add your SQL Server host here
$user="db1"; //SQL Username
$pass="test123"; //SQL Password
$dbname="db1"; //SQL Database Name
$con=mysqli_connect($host,$user,$pass,$dbname);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT name,message FROM db1");
while($row = mysqli_fetch_array($result))
{ ?>
<h3><?php echo $row['name']; ?></h3>
<p><?php echo $row['message']; ?></p>
<?php }
mysqli_close($con);
?>
I also updated the html code above so you can see how I created the menu for guestbook list.

Submitting form data with javascript (No page reload)

I've got a wall/social system (much like facebook) where there's statuses, but I want to be able to like, dislike and comment on a status without the page reloading, with the form below how could I complete this?
if(empty($_GET['action'])){
postupdate();
if(isset($_POST['sComment'])){
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$comment = mysqli_real_escape_string($dbc, trim($_POST['comment']));
$sid = mysqli_real_escape_string($dbc, trim($_POST['sID']));
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "INSERT INTO comments (`user`, `post`, `time`, `content`) VALUES ('".$_SESSION['user_id']."', '$sid', NOW(), '$comment')";
$data = mysqli_query($dbc, $query);
}
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "SELECT posts.*, user.* FROM posts JOIN user ON user.user_id = posts.user_id JOIN friends ON friends.user = ".$userinfo['id']." AND friends.with = posts.user_id ORDER BY posts.post_id DESC";
$data = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($data)){
echo'<div class="shadowbar">
<div class="postedBy"><b> Posted by '. $row['firstname'] .' '. $row['lastname'] .' On '. date('M j Y g:i A', strtotime($row['postdate'])) .'</b></div>';
$parsed = $parser->parse($row['post']);
echo '<pre>'.$parsed.'</pre>
<hr>
<form method="post" action="index.php" class="commentForm">
<fieldset>
<div class="input-group">
<textarea cols="150" rows="1" style="resize: none;" placeholder="Comment..." class="form-control" type="text" id="commentBox" name="comment"></textarea>
</div>
<input type="hidden" value="'.$row['post_id'].'" name="sID">
</fieldset>
<input class="Link LButton" type="submit" value="Add comment" name="sComment" />
</form>
</div>';
}
echo '</div>';
}
the form can be changed to fit the code. I'm assuming it's JavaScript that I will need to use.
Here's some code to get you started.
First of all, add an ID or class in order to easily identify the form(s):
<form method="post" action="index.php?action=comment" class='commentForm'>
Since you tagged jQuery, I shall use that:
$(document).on('submit', '.commentForm', function(e) {
e.preventDefault(); // Prevents the default page reload after form submission
$.ajax({
type: $(this).prop('method'),
url: $(this).prop('action'),
data: $(this).serialize()
}).done(function() {
// Do something after it submits
alert('Thanks for the comment!');
}).fail(function() {
// There was an error
alert('An error occurred');
});
});
You can read more about jQuery.ajax in the jQuery documentation.
Yes, you'll need to use JavaScript to send a POST request to the server. There are several jQuery plugins, but none of them are perfectly fit to your needs, so I recommend that you write your own.
The workflow should be like this:
Initiate an XMLHttpRequest object
Set the target equal to the form's action= attribute (extra points if you can get this information from the DOM without typing it manually again)
Grab the data you want to submit from the form (again, using DOM)
Send a POST request with the data you got from the form, to the target page.
Target page should return a response of some sort, to tell the client that the submission went smoothly
Client reads that response and displays a success message to the user.
Here is something that should be useful for you.
http://www.9lessons.info/2009/11/facebook-style-application-with-jquery.html
In short you need to use ajax to post request to your form's action url. you can use jQuery for that.
http://api.jquery.com/jquery.ajax/
Use ajax to send and receive data. Use the code below
<form method="post" action="index.php?action=comment" id="Form">
<fieldset>
<legend>Status Update</legend>
<div class="input-group">
<textarea cols="150" rows="5" style="resize: none;" placeholder="Comment..." class="form-control" type="text" id="text" name="comment"></textarea>
</div>
<input type="hidden" id="hidden" value="$statusID" name="sID">
</fieldset>
<input class="Link LButton" type="submit" value="Add comment" name="submit" />
</form><div class="container"></div>
<script>
$(document).ready(function(){
$('#Form').submit(function(e) {
e.preventDefault(); // This will prevent the form to be submitted
var hidden=$("#hidden").val();
var comment=$("#text").val();
$.post(
"index.php", {
comment: comment,
sID:hidden
},
function (data) {
$('#check').html(data);
});
});
</script>
Your PHP file should look like this
<?php
$comment=$_REQUEST['comment'];
$sID=$_REQUEST['sID'];
echo $comment."<Br>".$sID;
?>
Hope this helps you

Categories