JS
<script>
function myAjax() {
$.ajax({
type: "POST",
url: 'ajax.php',
data:{action:'call_this'}
});
</script>
HTML
<a href="'. $row['link'] .'"target="_blank" onclick="myAjax()">
PHP
<?php
require ("static/php/inc/betaconfig.inc.php");
if($_POST['action'] == 'call_this') {
$conn->query("UPDATE users SET clicks = (clicks + 1) WHERE id = 13");
}
?>
Normally it should be $uid instead of 13 but I don't know how to do that too...
First of all, why this doesnt work ? 2nd $uid is $id = $_REQUEST['id']; and then
$sql = "SELECT * FROM `link` WHERE id = '$id'";
$result4 = $conn->query($sql);
while($row = $result4->fetch_assoc()) {
$uid = $row['userid'];
}
so the best thing that instead of 13 I could use $uid
Related
I have a table of Data which is pulled via SQL into DataTables. I want to use AJAX to run an SQL query which deleted the row based on $id = $row["id"];.
Index.php:
$link = mysqli_connect("localhost", "bradlyspicer_root", "", "bradlyspicer_ResellerDB");
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
echo 'success';
echo $id;
} else {
echo 'fail!';
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
Functions.php:
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
echo 'success';
} else {
echo 'fail!';
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
Custom.js:
$( ".delbtn" ).click(function(){
var itemID = $(this).attr("itemID");
console.log(itemID)
$.ajax({
url:"functions.php", //the page containing php script
data: { id: itemID}, // itemID passed as id
type: "POST", //request type
success:function(result){
alert(result);
},
error: function() {
alert('Error occured');
}
});
});
I can't find where I pass the $id in the button from Index.php to Functions.php, any explanation would be appreciated.
Update: Since updating the script and trying to Debug, I'm not getting much of a response from the error which outputs:
fail!Error: .
Index.php:
Add a delete button identifier class delbtn and a data attribute that carries this row's id data-itemID
<?php
while($row = mysqli_fetch_array($dataTablesResult)){
$id = $row["id"];
echo '
<tr>
<td>
<button type="button" data-itemID="'.$id.'" class="delbtn btn btn-danger" >Remove</button>
</td>
</tr>
';
}
?>
Functions.php:
Capture $_POST['id'] sent by ajax
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
}
Custom.js:
Run the jQuery function when a button with .delbtn class is clicked. Capture and store the row id from data attribute as $(this).data("itemID"). Then send the data using data: { id: itemID} within ajax request
$(".delbtn").click(function(){
itemID = $(this).data("itemID");
$.ajax({
url:"functions.php", //the page containing php script
data: { id: itemID}, // itemID passed as id
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
i think if you change this line :
mysqli_stmt_bind_param($stmt, "s", $id);
to this is one:
mysqli_stmt_bind_param($stmt, "i", $id);
it may works
What is wrong here?
My PHP/HTML (The only part that matters):
if(isset($_POST['submit']))
{
$date = date('Y-m-d', strtotime(str_replace("-","/",$_POST['dateOfEntry'])));
$username = $_POST['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px"><input type="button" name="edit" value="Edit"></td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td>'.$row['Date'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['TypeOfDowntime'].'</td>';
echo '<td>'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
My Ajax/Javascript:
$(document).ready(function()
{
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id':'del_id'},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
My PHP (on an external script: machineEntryLogEdit.php):
include('connServer.php');
$deleteID = $_POST['del_id'];
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_connect($connection, $query);
if(isset($result))
{
echo "YES";
}
else
{
echo "NO";
}
?>
I have searched around and around for solutions but no avail. The only things it does is delete the record from the HTML table, but not from the database, causing the supposed-to-be-deleted row to reappear after refresh. I am still very new to AJAX (in fact I just learned it myself today) and still reading the documentations and forums. Thanks.
This should be data: {'del_id': del_id} remove quotes so it react as a variable, not just a single string. And one more thing, your delete query does not execute cause you're using :
$result = mysqli_connect($connection, $query);
Should be mysqli_query like the one you did on selecting data's part:
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_query($connection, $query);
It looks to me like you didn't pass the submit variable in your data. If you want to include a form you need to pass the data, right now the server is receiving only one parameter, del_id
I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}
I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.
I have a problem with my like system an user can give more than 1 like but the system register on the db just one, i think is a problem related to AJAX.
This is the button:
<a class="btn btn-xs btn-white" name="btn" onclick="usercountcomments(<?php echo $value['user_id'].",".$value['personal_closest_id'].",".$value['id']; ?>)"><i class="fa fa-star"></i><span id="countVal1_<?php echo $value['id']; ?>"><?php echo $value['countcomments']; ?></span> Cool </a>
And this one is the jscript AJAX script:
function usercountcomments(user_id,postId,id){
var a = $("#countVal1_"+id).text();
var display = document.getElementById("countVal1_"+id);
var count = a;
var user_comments="cool";
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/commentcool/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments},
success: function(data) {
count++;
display.innerHTML = count;
// alert(a++);
}
});
}
What can I do to prevent the user giving more than one like ?
you can use cookie
<?php
$id =$_GET['id'];
if(isset($_COOKIE['like'.$id])) {
echo "error";
exit;
}else {
$sql = "UPDATE post SET likecount=likecount+1 WHERE id=$id";
$conn->query($sql);
$sql = "SELECT likecount from post where id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row['likecount'];
setcookie('like'.$id,true, time() + (86400 * 30), "/");
}
}