Dynamically delete MySQL data using AJAX and JS - javascript

Hi I'm trying dynamically remove database entries using JS and AJAX without refreshing whole page.
Here is my data.php file:
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM message";
mysql_query("SET NAMES 'UTF8'");
$qq=mysql_query($query);
$i = 1;
echo '<div id="rezult">';
while($ff = mysql_fetch_array($qq)){
echo '<div id="id'.$ff['id'].'">'.$i++.'. Name: '.$ff['name'].' Message:'.$ff['message'].'</div>';
}
echo '</div>';
}
?>
With this code I'm retrieving a data from mysql table:
index.php
function list() {
$.get('data.php?list=1', function(o) {
$('#list').html(o);
});
}
How to dynamically delete desired entry without refreshing a page?
tried to add this code below as a link to the entry, but it getting cut javascript:$.post( like that.
<a href="javascript:$.post('delete_post.php', { id: '$ff[id]' } );" class='delete_post' title='delete post'>delete post</a>
Thanks for advices

Be careful!, if someone make a call to your php file data.php?list=ANYNUMBER he will be able to delete any row, be sure you are using security tools to avoid that.If you use ajax and Jquery I think it will be easier.
try something like this:
$.ajax({
type: "POST",
url: "list.php",
data: { list: "1", session_id: session_ID }
}).done(function( msg ) {
alert( "Data deleted: " + msg );
});
where session_id is the value of the field (in your example is 1), session_id is when someone go to your page you assign him a SESSION_ID, after he click the delete button, you compare if the session ID that you assign is equal to the the session_id from the server (you avoid people from another site to call your list.php). If session_id from the ajax is equal to session session_id on the server allow to delete take a look to this: PHP Session Security

Related

Not sending data with AJAX to database

I have a problem with catching AJAX data with PHP and send it to the database. Site is on the WordPress platform.
I have checked for the errors with mysqli_error but there nothing happened. Console not showing any error, just show there is `console.log data from the ajax, so the ajax work.
Here is what I have tried so far.
AJAX:
$.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: {
'creditCardValue':creditCardValue,
'creditCardValueCvc':creditCardValueCvc,
'phoneNumberForm':phoneNumberForm
}
});
Here is a PHP code:
<?php
if (isset($_POST['button'])) { // button name from html
$creditCardValue = $_POST['creditCardValue'];
$creditCardValueCvc = $_POST['creditCardValueCvc'];
$phoneNumberForm = $_POST['phoneNumberForm'];
$query = "INSERT INTO validations(credit_card_number, credit_card_cvc, phone_number) ";
$query .= "VALUES ({$creditCardValue}, '{$creditCardValueCvc}', '{$phoneNumberForm}' ) ";
$create_post_query = mysqli_query($connection, $query);
}
?>
I need to send all these data to the database so I can later call them and displayed them.
Thanks in advance.
Remove the check for $_POST['button'] as this is not sent with the AJAX data. If you want to check if it's an AJAX call then just check that one of the values has been POSTed:
if (isset($_POST['creditCardValue'])) { ...

Passing a php variable to another php file using ajax

I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.
When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.
<script type="text/javascript">
$(document).ready(function() {
$(".content-short").click(function() { //
$.ajax({
type: "GET",
url: "content.php", //
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
});
</script>
content.php
<?php
include "mysql.php";
$query= "SELECT Content FROM blog limit 1";
$result=mysql_query($query,$db);
while($row=mysql_fetch_array($result))
{
echo $row['Content'];
}
mysql_close($db);
?>
Is there an alternate way to do this or something that I need to correct for it to work?
Thanks
First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:
$(".content-short").click(function() {
// get the ID
var id = $(this).attr('data-id');
$.ajax({
type: "post",
url: "content.php",
data: 'id=' + id
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
Next up is reading the value you passed in using the script:
<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id = intval($id);
$query = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
echo $row['Content'];
}
mysql_close($db);
?>
There you go, I have modified your query to allow fetching by id. There are two major caveats:
First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.
The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:
echo $row['Content'];
with this:
echo json_encode(array('success' => $row['Content']));
Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:
success: function(response){
$(".content-full").html(response);
}
into this:
success: function(response){
if(response.success) $(".content-full").html(response);
else alert('No results');
}
Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php
You can look at passing a parameter to your script, generally like an id by which you can search in the db.
The easiest way to achieve this is by get parameters on the url
url: "content.php?param=2",
Then in php:
<?php $param = $_GET['param'];
...

How to send data as an object through .post() in jQuery?

When I make a .post() request such as
var data = $(this).serialize();
$('form').on('submit', function(event) {
event.preventDefault();
$.post('server.php', data, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
everything's working - the name from the database appends to the #data element withing the p tags. But, when I try to pass data as an object like this
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
than it doesn't work. I tried changing the argument of the function within the .post() to id and probably every combination of names for .post()'s arguments and variables within the PHP file also, without success. Here's the working intact PHP file compatible with the first version of my .post() request in this question:
<?php
$id = $_POST['id'];
$connection = new mysqli('localhost', 'root', '', 'dummy_db');
$query = 'SELECT name FROM dummy_db_table WHERE id = "' . $id . '"';
$result = $connection->query($query);
$row = $result->fetch_assoc();
echo $row["name"];
$connection->close();
?>
Please note that the name of the input field for the ID in the HTML file is 'id'. I do understand that it is this name attribute within HTML which helps PHP determine the value of it, but how is it doing so without me specifying the connection with the PHP through form's action attribute? I'm doing this exclusively through AJAX (.post()) and AJAX is not telling PHP anything specific about THAT id field. What am I missing here? Also, how would I go about sending the object of values instead of a single one through .post()'s data attribute? Thank you.
You have not add the form code here so lets assume your form have two fields name and address.
Actually you need to put the serialize() function under the event. Like
$('form').on('submit', function(event) {
event.preventDefault();
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
Now on your server.php file if you print the following line:
$id = $_POST['id'];
echo $id;
this will show you the results like: name=iffi&address=UK
I hope this will help you more.

getting POST data through AJAX

I have a form that will go through AJAX to set a session variable and back to the original page.
My problem is that I cannot set the session variable, thus, it is not working.
my main PHP page
<?php
if ($_SESSION['adminFunction'] == 'adminfunction'){
echo "<form id='userOptionRequest' action='request.php'>";
echo "<button name='adminFuncUserOption' onclick='adminFuncOption(1)'>User Option</button> <br /> <br />";
echo "<button name='adminFuncUserOption' onclick='adminFuncOption(2)'>Subject Option</button> <br /> <br />";
echo "<button name='adminFuncUserOption' onclick='adminFuncOption(3)'>Test Option</button> <br /> <br />";
echo "</form>";
}
if ($_SESSION['adminFunction'] == 'addusers'){
echo "hello world";
}
?>
my JS file
function adminFuncOption(option){
if (option == 1){
var userOptionRequest = new XMLHttpRequest();
userOptionRequest.open('POST','request.php',false);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
userOptionRequest.send('adminFuncUserOption=' + option);
return(1);
} }
the request.php
<?php
session_start();
$option = $_POST['option'];
if ($option != NULL){
if ($option == 1){
$_SESSION['adminFunction'] = 'addusers';
header('Location: http://rsc_naga_isd/admin');
}
}
var_dump($_POST);
var_dump($_SESSION);
var_dump($_GET);
?>
when I go back to my main PHP page, the session should now be addusers and should display 'hello world'
I have research but still had a hard time understanding AJAX or PHP
Submitting HTML form using Jquery AJAX
http://www.ajax-tutor.com/post-data-server.html
http://tutorialzine.com/2009/09/simple-ajax-website-jquery/
Oh, am still not familiar with jquery and still new to javascript, but would prefer javascript before diving in to jquery.
Hi jquery helps you to do more with less for example an AJAX call using jquery is like this:
$.ajax({
url: url,
type: 'POST',
data: data,
beforeSend: funtion(){
//DO Something before send like print a Loading text
},
success: function(data){
//DO SOMETHING IF DATA IS RETURNED
},
error: function(data){
//DO SOMETHING ON ERROR
}
});
Then you can check on you php scipt for the values sent on data for example:
if you send this data value:
data: {"adminFunction" : "mortal user not worthy" }
on your php script just do something like this:
switch($_POST['adminFunction'])
{
case 'superAdmin':
//....
break;
default:
//DO Something
break;
}
More info here:
AJAX JQUERY
In javascript you send:
userOptionRequest.send('adminFuncUserOption=' + option);
but in php:
$option = $_POST['option'];
it should be
$option = $_POST['adminFuncUserOption'];
I know you want javascript, but jquery so much easier ;)
$.post("request.php", { adminFuncUserOption: option }, function(response) {
console.log(response);
});
that's it then just check for $_POST['adminFuncUserOption']
The server side of the code (PHP) executes prior to the javascript side of the code. The server creates HTML (with javascript) to the client browser. The client browser then executes the code and javascript.
While your Session variable was updated, the requesting page was already created. You are going to need to reload the page that made the request in order to recognize the change to the session variable.
You could have the AJAX pass back non-sensitive data that you can process with javascript. If this is secure information that you don't want to be hacked, then I recommend avoiding AJAX until you get a better handle of it.

Database Driven Page Content

I am trying to make a facebook style wall on my website. The goal is to insert form data, validate all forms as required, and store this data into a database. Simultaneously and separately I want all data stored in this database to be posted into a div that acts as the facebook wall.
I seem to have accomplished storing the data from the form. I can also retrieve all data in the database except it only does it when I submit the form. Which means no page content unless the user submits a post.
How can I populate my page with rows from my database when a user opens the page or before?
Please help!
Here is my php which stores and prints data when the html form is submitted.
<?php
// Create connection
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO test (school, confession)
VALUES
('$_POST[school]','$_POST[confession]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// print $_POST['college']."-<br />".$_POST['confession'];
$result = mysqli_query($con,"SELECT * FROM test");
while($row = mysqli_fetch_array($result))
{
echo "#" . $row['ID'] . " " . $row['confession'];
echo "<br>" . "#" .$row['school'];
echo "<br>" . "<br>";
}
mysqli_close($con);
?>
Here is my JS which posts to a div called content.
$(document).ready(function(){
$("#subform").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('test.php', $("#subform").serialize(), function(data) {
$('#content').html(data);
});
}
});
});
Another approach is to load data on mouse scroll like:
//approx this
$(document).ready(function () {
var flg='1';
$(window).scroll(function () {
console.log($(document).scrollTop());
if ($(document).scrollTop() >299){
if(flg=='1')
{
$.post( 'link to server side code', function( data ) {
$('#morefrom').html(data.htmls);
},'json');
flg='0';
}
}
});});
This way you can load data on a specific mouse scroll value(like if a user gets on the bottom of the page you load new rows)
scrollTop docs
You can use a JavaScript Timer which will ticks after certain interval and load your Data, plus you must have to write a function that will just fetch the Data in your test.php file
function dataLoader()
{
//load Data with GET Request $.get(. . . );
}
dataLoader();
setInterval(dataLoader, 1000);
or the Second option will to be use jquery Timer Library to achieve performance
Thanks for the replies I solved the problem. I just called the php on load.
$(document).ready(function(){
$("#subform").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('test.php', $("#subform").serialize(), function(data) {
$('#subform').html(data);
});
}
});
});

Categories

Resources