Update MySQL table with button without refreshing page using ajax - php

I am trying to update a value in a database without refreshing the page using AJAX. I am completely new to AJAX but I have have managed to create a function after searching for answers on Stackoverflow but I am unable to make it work.
One the main page...
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "del_reason.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
The button (which is in a form)
<input type="button" name="delete_pos" value="Delete" class="delRow_pos"
onClick="UpdateRecord(<? echo $row['reasonID']; ?>);"/>
The contents of del_reason.php
$var = #$_POST['id'] ;
$sql = "UPDATE gradeReason SET current = 0 WHERE reasonID = $var";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
//added for testing
echo 'var = '.$var;
The database connection is ok because other functions on the same page connecting to the database work fine and so do other jquery functions but when the button is clicked the alert says the record is upodated but it isn't

The MySQL query on the del_reason.php failed because it needed it's own MySQLi connection to the database.
As soon as I added it the script worked

Related

PHP ajax returns duplicate from external PHP file

I've looked everywhere for an answer to this one, hopefully someone can help me out. I have the following ajax/JS code, as well as an external PHP file that I call below and then an index.php page to display results.
This code works well with my external php file. It grabs the posted data return from a MySQL database and displays the contents in the #show div. Essentially I am querying a MySql database for host details (ip, mac, etc). This all returns just fine without page refresh. The problem and my question is when I submit the form again with another code the results are again returned BUT appended to the previous results. Question: how do I avoid this?! I have looked into caching and clearing Ajax vars (content) and emptying the PHP page but have had zero luck in getting the previous Ajax call to clear on another submission. Is this a problem with my ajax code? or is there something I need to be clearing on the PHP side of things?
I am relatively new to ajax, generally speaking, but understand how the script works to retrieve information. Is there a way to refresh the external php file to dump the previous post after I scrape the results back to my index.php page?
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "HOST_gethost.php",
data: dataString,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
});
}
return false;
});
});
</script>
Thanks ahead of time!!
EDIT more details as I am still having the same issue: after(data) works and html(data) does not. For the life of me, especially after mark explained the two functions, I cannot figure out why one would work and the other not the return for html(data) is just blank, nothing in the debug either.
JS code:
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "HOST_gethost.php",
data: dataString,
success: function(data){
$("#show").html(data);
document.getElementById('content').value='';
}
});
return false;
});
});
</script>
PHP external file:
<?php
$conn = mysql_connect('','','') or die (mysql_error);
$db=mysql_select_db('blah', $conn) or die (mysql_error);
$content=$_POST['content'];
$fetch= mysql_query("SELECT * FROM blah.blahblah WHERE hostname LIKE '%$content%' ");
$row=mysql_fetch_array($fetch);
?>
<div class="showbox">
<table>
<th>Attributes</th><th>Details</th>
<tr><td>Name</td><td><?php echo $row['hostname']; ?></td></tr>
<tr><td>Last Known IP</td><td><?php echo $row['ipv4']; ?></td></tr>
<tr><td>Last Known User</td><td><?php echo $row['username']; ?></td> </tr>
<tr><td>Last Seen</td><td><?php echo $row['updated']; ?></td></tr>
<tr><td>Protection</td><td><?php echo $row['encryption_status']; ?></td></tr>
<tr><td>Firewall</td><td><?php echo $row['firewall_explanation']; ?></td></tr>
<tr><td>Script Policy</td><td><?php echo $row['policy']; ?></td></tr>
<tr><td>GPO Check-in</td><td><?php echo $row['gpo']; ?></td></tr>
</table>
</div>
Use
$("#show").html(html);
instead of
$("#show").after(html);

Insert into mysql database from html form without redirecting [duplicate]

This question already has answers here:
Form submit with AJAX passing form data to PHP without page refresh [duplicate]
(10 answers)
Closed 7 years ago.
I'm working with a mysql database and a webpage that i'm trying to make comunicate with it.
Here's my situation:
i have the listmat.php file that echoes all the records in the table Material and it works.
Now i manage to show the output of the listmat.php file inside a specific div witouth refreshing the hole page with the following code:
<script>
$(document).ready(function(){
$("#matbutton").click(function(){
$("#matins").load('listmat.php');
});
});
</script>
Where matbutton is the id of the submit button in the form and matins is the id of the div where i show the output of listmat.php
Here's my form:
<form id="formmatins" method="post" action="listmat.php">
<p>Name:<input type="text" Name="Mat" id="Material"></p>
<center><input type="submit" value="Insert/Remove" id="matbutton"></center>`
</form>
What i'd like to do is to use the matbutton to also insert the value of the textbox in the table that listmat.php echoes all his records. So that everytime i click a record is inserted and in the div is shown the new table
The problem is that if i insert the button in the form with the method post , by clicking it redirects to the output changing page but if i put it out the echoes work but i cannot pass obviously the value of the textbox to the listmat.php file to be the argument of the insert because the button is not interested by the method post.
I looked around and looks like the solution is using some articulated structure in jquery/ajax but i really don't know how to fix. Any help would be really appreciated
UPDATE
<script>
$(function () {
$('#formmatins').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function () {
$("#matins").load('listmat.php');
alert('form was submitted');
}
});
});
});
</script>
And again it switch page
UPDATE
<?php
$user = "**";
$pass = "**";
$db = "**";
$host = "localhost";
$con = mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$m = $_POST['Mat']; //the text box in the form
$ins = $con->query("INSERT INTO mattemp (Material) VALUES ('$m')");
$query = $con->query("SELECT Material FROM mattemp");
while ($row = $query->fetch_assoc()) {
echo $row['Material']."<br>";
}
?>
It print the table updated everytime but still in a new page...what am i doing wrong?
SOLVED BY MYSELF
Thanks to all have tried to help me. The solution that gave me -1 on the post was not correct and here the solution of my code , in case someone would encounter the same problem
`<script>
$(function () {
$('#matbutton').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function (data) {
$("#matins").load('listmat.php');}
});
});
});
</script>`
You'll need $.ajax
For exemple :
$.ajax({
url: "your_url.php",
type: "POST",
data: $('#formmatins').serialize(),
success: function(response){
// Do something, or not...
}
})

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

Show DIV with AJAX in PHP After Saving Data to Mysql

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

Jquery not connecting to .php

I am having some trouble with my jquery. I am not sure if it is connecting to doc.php but I am not getting anything inserted into my database.
I have an insert command in doc.php which I know is working.
I'm trying to create a way to update prices in a database, from doc.php, that searches out items one at a time.
The doc.php is searching by var, then updating in the same page.
The foreach loop function then, takes the var one by one, sends them to the doc.php page that then searches by var and updates into the database.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die (mysql_error());
$sql = "SELECT var FROM table";
$query = mysql_query($sql) or die (mysql_error());
while ($result = mysql_fetch_array($query)) {
$variable = array($result['var']);
foreach ($variable as $variable1) {
?>
<script src="jquery-1.7.2.min.js" type="text/javascript">
$(function() {
var valueToSend = '<?php echo $variable1; ?>';
$.ajax({
url: "doc.php",
dataType: "json",
type: "POST",
data: { Variable: valueToSend },
success: function (m) {
alert(m);
},
error: function (e) {
alert("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
}
}
?>
First of all, what do you want to do with this code? If you want to read & write to db using php, ajax call is unnecessary. If you want to practice ajax & php you need to read some howto because your code is somewhere strange ;). This is nice collection of tutorials for jQuery and some for PHP read some and practice.

Categories