I'm trying to delete a mysql record with javascript but I fail.
So this is my js function
function delpost(id){
if(confirm('Are you sure?')){
$('#comment_'+id).hide();
http.open("get","/index.php?p=delcomment&id=" + id, true);
http.send();
}
}
And this is my delcomment.php(included through index.php)
$comment_id = $_GET['id'];
if(logged() && $status=="administrator"){
$delquery = mysql_query("DELETE FROM comments WHERE id='$comment_id' LIMIT 1");
die();
}else{
die();
}
I hope you can help me with this :)
update:
try using
http.send(null)
instead of
http.send()
also, use firebug to see if your ajax request is actually being sent to the server
better solution:
(php rusty!)
delcomment.php
$comment_id = $_POST['id'];
$comment_id = mysql_real_escape_string($comment_id);
if(logged() && $status=="administrator"){
$query = "DELETE FROM comments WHERE id='{$comment_id}'";
$result = mysql_query($query, $con);
die();
}else{
die();
}
using jquery to post (make sure to include the jquery.js), your javascript function should be like this:
function delpost(id){
if(confirm('Are you sure?')){
$.ajax({
type: "POST",
url: "/index.php",
data: {p: "delcomment", id: id},
success: function(){
$('#comment_'+id).hide();
},
error: function(){
alert('failure');
}
});
}
}
Related
I've been looking to find a way to update some data into my database when execute onclick function.
The idea is to update the value of a button contains the word "Active" and when execute onclick like to update into mysql to "Inactive"
This is the button:
$register_status = '<button class="btn btn-success btn_status btn-block" data-status="Active">Active</button>';
How to give the data variable so that we can fetch it in PHP using $_POST? The above representation of the data variable shows an error.
scripts.js
$(document).ready(function(){
$('body').click('.btn_status', function(e){
var button = jQuery(e.target);
if(button.data('status') == 'Active'){
var data = {id:id, register_status:Inactive};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/updateStatus.php",
data: data,
success: function(data) {
alert("update!");
}
});
}else if(button.data('status') == 'Inactive'){
alert("nothing");
}
});
})
ajax/updateStatus.php
include("db_connection.php");
if(isset($_POST))
{
$id = $_POST['id'];
$register_status = $_POST['register_status'];
$query = "UPDATE `users` SET `register_status` = '$register_status' WHERE `id` = '$id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
UPDATE:
This is another function to delete. This function is run correctly.
function DeleteUser(id) {
$.post("ajax/deleteUser.php", {
id: id
},
function (data, status) {
readRecords();
}
);
}
deleteUser.php
<?php
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
include("db_connection.php");
$user_id = $_POST['id'];
$query = "DELETE FROM users WHERE id = '$user_id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
?>
and when do a click I can remove:
<li onclick="DeleteUser('.$row['id'].')">Delete</li>
However, this doesn't seem to work. If there's a better way to do what I mentioned above. thanks
Based on the example, you will want to make some changes:
JavaScript
$(function(){
function updateStatus(id, st){
$.post("ajax/updateStatus.php", {"id": id, "register_status": st}, function(data, status){
console.log("Update Success", data, status);
readRecords();
});
}
$('body').on('click', '.btn_status', function(e){
var button = $(this);
updateStatus(1001, (button.data("status") === "Active" ? "Inactive" : "Active"));
});
});
First, using the click() as you had, was not exactly the best way to do it. Using .on() will be better as it can handle any new or dynamically created items.
This script will require id to be defined someplace. The AJAX needs to send the id info to the PHP. The code you posted does not show this, so I am not sure what it's value should be.
PHP (updateStatus.php)
include("db_connection.php");
if(isset($_POST['id'])){
$id = (int)$_POST['id'];
$register_status = ($_POST['register_status'] == "Inactive" ? "Inactive" : "Active");
$query = "UPDATE `users` SET `register_status` = '$register_status' WHERE `id` = '$id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
These updates can help prevent SQL Injection. I would advise using Prepared Statements to further prevent it.
Update
If you're button is going to be something like this:
<button onclick="ChangeStatus('.$row['id'].') class="btn btn-success btn_status btn-block" data-status="Active">Active</button>
Notice that this is only passing in just the ID from PHP. If these items will always be "Active", then yes, you can do this with something like:
function ChangeStatus(id){
$.post("ajax/updateStatus.php", {id: id}, function(data, status){ console.log(status, data)});
}
With PHP like:
<?php
if(isset($_POST['id']) && $_POST['id'] != ""){
include("db_connection.php");
$user_id = (INT)$_POST['id'];
$query = "UPDATE `users` SET `register_status` = 'Inactive' WHERE `id` = '$user_id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
?>
Hope this helps.
So here I want to get an ID for the specific user, using a php page, and then perform database insert using a function defined in a file named 'functions.php'. So basically, I am capturing values from a page using jQuery ajax() method and sending the data to a php page named 'follow_school.php'. The rest of what's happening would be clear from the code, I provide below:
jQuery code:
jQuery(document).ready(function() {
var school_name = jQuery('#school-name').text();
var session_var = jQuery('#session').text();
// console.log(session_var);
var button_text_onload =
localStorage.getItem("btnText_"+school_name+"_for_"+session_var);
console.log(button_text_onload);
if (button_text_onload !== null) {
jQuery('#follow-button').html(button_text_onload);
} else {
jQuery('#follow-button').html('Follow');
}
jQuery('#follow-button').click(function() {
// alert (session_var);
// console.log(session_var);
var button_text = jQuery('#follow-button').text();
// alert(button_text);
if (button_text === 'Follow') {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/follow_school.php',
data: {name : school_name,
email : session_var
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Unfollow");
jQuery('#follow-button').html('Unfollow');
}});
} else {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/unfollow_school.php',
data: {name : school_name,
email : session_var,
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Follow");
jQuery('#follow-button').html("Follow");
}});
}
});
});
follow_school.php
<?php
include_once "includes/db.php";
include_once "includes/functions.php";
$name = $_POST['name'];
$email = $_POST['email'];
$id = get_id($email);
/* for debugging purpose */
if ($id == null) {
var_dump($id);
} else {
echo $id;
}
echo $email;
/* insert operation */
insert_school($id, $name);
?>
functions.php
function get_id($email) {
global $conn;
$sql = "SELECT id FROM member WHERE email = '$email'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
return $row["id"];
}
function insert_school($id, $name) {
global $conn;
$sql = "INSERT INTO user_schools (user_id, school_name)
VALUES ('$id', '$name')";
$conn->query($sql);
}
NOTE: Here the database connection is perfectly fine, and these codes worked for some pages earlier. But apparently, other pages don't seem to run the code, or to be precise, returns "null" as id. Also, I would like to mention that, the table entries and fields are not null, or unspecified. They are perfectly fine, as I said, it worked for some pages.
Please can anyone guide me, as to what's going wrong here, because after dedicating so much of my time on this, i still am not able to understand the issue.
Thank you.
I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});
When I click on share on a users link..It shares that post fine, yet it posts it twice. I've checked firebug and when clicked (Once) it shows up two POST requests, inserts two posts to the database and then shows them in the users feed.
I really don't understand where I'm going wrong.
SHARE LINK
echo'<a class="sharelink" title="Share '.$poster_name['fullusersname'].'s status" href="#"
data-streamitem_creator='.$streamitem_data['streamitem_creator'].'
data-streamitem_target='.$_SESSION['id'].'
data-streamitem_content='.$streamitem_data['streamitem_content'].'
data-streamitem_type_id=4>Share</a>';
AJAX
$(document).ready(function() {
$('.sharelink').click(function(e) {
e.preventDefault();
var streamitem_creator = $(this).data('streamitem_creator');
var streamitem_target = $(this).data('streamitem_target');
var streamitem_content = $(this).data('streamitem_content');
var streamitem_type_id = $(this).data('streamitem_type_id');
$.ajax({
type: "POST",
url: "../include/share.php",
data: {
streamitem_creator: streamitem_creator,
streamitem_target: streamitem_target,
streamitem_content: streamitem_content,
streamitem_type_id: streamitem_type_id
},
success: function(data) {
$(".usermsg").html(data);
}
});
});
});
SHARE.php
<?
session_start();
require"load.php";
if(isset($_POST['streamitem_type_id'])&isset($_POST['streamitem_creator'])&isset($_POST['streamitem_content'])&isset($_POST['streamitem_target'])){
user_core::create_streamitem(4,$_SESSION['id'],$_POST['streamitem_content'],1,$_POST['streamitem_creator']);
}
?>
LOAD.PHP
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,UTC_TIMESTAMP(),'$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser= rawfeeds_user_core::getuser($creatorid);
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
I can't see any problem.. By any chance, don't you have that $('.sharelink').click handler registered twice within your page?
I'm assuming I have to put something in the success option. However what I have isn't working.
I declare this JS function on the page:
<script type="text/javascript">
function performAjaxSubmission() {
$.ajax({
url: 'addvotetotable.php',
method: 'POST',
data: {
},
success: function() {
}
});
}
</script>
Then in the ajax call which is working properly I declare this for the success:
success: function(data) {
performAjaxSubmission();
},
addvotetotable.php looks like:
<
?php
// If user submitted vote give the user points and increment points counter
require_once("models/config.php");
//Check to see if there is a logged in user
if(isUserLoggedIn()) {
$username_loggedin = $loggedInUser->display_username;
}
if (strlen($username_loggedin)) {
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("SELECT vote FROM points_settings WHERE id=1")or die (mysql_error());
while($info = mysql_fetch_array($query)){
$points_value=$info['vote'];
}
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("INSERT INTO points (id,username,action,points) VALUES ('','$username_loggedin','vote','$points_value')")or die (mysql_error
());
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("UPDATE userCake_Users SET points=points + $points_value WHERE Username='$username_loggedin'")or die (mysql_error());
}
?>
You have to provide a value that you want to store in your database in the "data" of the ajax-request. Than you can use this in your php-code using $_POST["something"], check if it's valid... and return f.e. html or json which you than handle in the success-function.
<script type="text/javascript">
function onSubmitVote()
{
$.ajax({
url: 'addvotetotable.php',
method: 'POST',
data: "theVoteValue=" + <read_your_vote_value_here>,
success: function(result) {
>>>return something in your addvotetotable.php which indicate success and show a message whether the vote was successful or not.<<<
}
});
return false; // prevent submit if it is a submit-type button.
}
</script>
What this does is post data of the vote (it's value) to the php-file. There you can read it with $_POST["theVoteValue"] and put it in the database. You check if the value is valid and may insert, else you return an error-message or something so that in javascript you can notify the user of it's failure.