how to pass multiple values to a function in jquery to - php

I have this list of comments that i want to remove from database using AJAX, and fadeout from current view with Javascript.
I call this function removeComment() which sends ID of div to be removed to server ( ID is also row id in database )
The problem i have is, after i run the function first time, it stops working.
jquery code
function removeComment(PostId) {
var commentid = 'com' + PostId;
$(document).ready(function() {
$(commentid).fadeToggle('slow');
// send to php script
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function(done) {
alert(done);
}
});
}); // <-- Sorry, was missing a '}'
}
and below is the html of the comment list and how the functionis called
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
please i would like to know where i got it wrong
below is the php script
if($action == "removeComment"){
extract($_POST) ;
$query = "DELETE FROM comments WHERE id = '$cId'" ;
$result = mysql_query($query);
}

You should not wrap your behavior into a $(document).ready function. You should read more about what $(document).ready means. This code should work now:
function removeComment(PostId) {
var commentid = 'com' + cid;
var coms = document.getElementById(commentid);
$(coms).fadeToggle('slow');
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function (done) {
alert(done);
}
});
}

Related

problem to print result after ajax success

Please help to fix this issue with like counting.
i create a news feed like facebook using php mysql and ajax.
problem is that when i click on like button it prints like count from (this value) and showing to all, let say i have 5 posts and like current value for different posts are 100, 200 , 70 , 80 , 578. when I click on first post ajax success count 100+1 = 101 for first post and for all other post printting same 101 likes. now if i will go to 2nd post and its like value 200, ajax will show 200+1 =201 like. so after click on 2nd post all 5 posts like will show 201. its creating problem for me. I understand that after ajax success i mentioned to show the value to div class (.ajax_like_result), thats why its showing in every post, same result until i am not clicking on different post.
how to fix this so that when I click on any post it wil show only its real like value??
I try to change the DIV attribute id , instead of class then it only works for first post. other post totally not working. if i set div atribute to class then like is working but printing incorrectly as i mentioned above.
I have pasted below- html , php and ajax code . thanks for your help.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.ajax_like').on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(".ajax_like_result").html(data);
}
});
});
});
</script>
html :
<li class="ajax_like" type="submit" name="data-id" data-id="<?php echo $page;?>" value="<? echo $post_id;?>">
<div class= "ajax_like_result" ><?php print $likes;?></div>
</li>
like.php code :
<?php //user info start
session_start();
$conn=mysqli_connect("localhost", "u1068033_ab24", "ab#24", "u1068033_ab24");
mysqli_set_charset($conn,"utf8");
$id=$_SESSION['id'];
$get_post_id = $_POST['post_id'];
$page = $_POST['page'];
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
$likes=$row['likes'];
$sql="UPDATE $page SET `likes`=$likes+1 WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
echo $row['likes'];`enter code here`
?>
You should need some corrections on your jQuery
$(document).ready(function(){
$('.ajax_like').each( function(){
$(this).on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(this).find(".ajax_like_result").html(data);
}
});
});
})
});
you are writing the result to all HTML elements with the same class "ajax_like_result" when using this line:
$(".ajax_like_result").html(data);
you can use something such as:
$("li[data-id='"+page+"'] div.ajax_like_result").html(data);
Also better using native JavaScript and not jQuery, using document.querySelector
document.querySelector(`li[data-id='${page}'] div.ajax_like_result`).innerHTML = data;
and replace the jQuery AJAX with the native JavaScript fetch
example in one piece of code block with native JavaScript (no need for jQuery):
document.addEventListener("DOMContentLoaded", (event) => {
document.querySelectorAll('li[data-id]').forEach((elem)=>{
elem.addEventListener('click', event => {
const domElem = event.target;
const postId = domElem.getAttribute('value');
const page = domElem.getAttribute('data-id');
const data = {post_id:postId, page:page};
console.log({data});
fetch('like.php', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
const selector = `li[data-id='${page}'] div.ajax_like_result`;
document.querySelector(selector).innerHTML = data;
})
.catch((error) => {
console.error('Error:', error);
});
});
});
});
and better also to remove from the PHP code the '?>' as the PHP ends the script execution at the end and it will reduce some possible unwanted white spaces.

Fetch result in Jquery Lightbox using PHP/Ajax

I'm trying to fetch information (u_name and u_email) from database using AJAX into a JQuery lightbox. I'm having problems with the Ajax part.
My HTML structure is:
<div class="boxes">
Show it
</div>
<div class="boxes">
Show it
</div>
So, the user clicks on one of the id, which is matched in the database table, and the result is fetched.
The Javacript code is:
$(function() {
$('#id').ecko({ //ecko is a JQuery lightbox function which im using
height: 200,
holderClass: 'custom',
template: '<p>About</p>' +
'<div>' +
'u_name' +
'u_email' +
'More' +
'</div>'
});
});
The Ajax will be:
$.ajax({
url: 'functions/db.php',
data: "",
dataType: 'json',
success: function(data){
var name = data[0];
var email = data[1];
//What should be here??
} });
PHP code will be like:
$result = mysql_query("SELECT * FROM $tableName WHERE `id` = " what should be written here? ");
$array = mysql_fetch_row($result);
echo json_encode($array);
I've posted everything I tried. I don't know a way of connecting the id clicked to pass it to php's line of $result = mysql_query("SELECT * FROM $tableName WHEREid= "") and then connecting Ajax and the Jquery lightbox.
When someone clicks the button, pass the ID to the data option in ajax, and fetch it on the serverside:
$('.button').on('click', function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json'
}).done(function(data) {
$('#id').ecko({
height: 200,
holderClass: 'custom',
template: '<p>About</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
});
});
Then use the data in the markup, but you can only do that once the ajax call is completed.
PHP
$id = $_POST['id'];
$result = mysql_query("SELECT * FROM $tableName WHERE `id` = " $id);
consider moving onto PDO, as mysql is deprecated!

Selecting data Ajax

I would like to select streamitem_id from my insert.php and add it to my existing post div. I'm needing the id of the post made so I can add it into my div so later when I add my delete button it will delete the post and the div that holds it. Hope I've made sense and I can do this with what I have as I'm trying to learn but it is a difficult language like any when first starting out.
AJAX
<script>
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){
$("#homestatusid").prepend("<div id='divider-"+WHERE MY STREAMITEM_ID NEEDS TO BE+"'><div class='userinfo'>"+newmsg+"</div></div>");
}
});
});
});
</script>
INSERT.PHP
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_id=$user1_id";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
echo $check2;
In your javascript should be
$.ajax({
type: "POST",
url: "insert.php",
data: {toid:content, newmsg: newmsg}, # pay attention to this line
success: function(data){
$("#homestatusid").prepend("<div id='divider-"+data+"'><div class='userinfo'>"+newmsg+"</div></div>");
}
});
PHP
$toid = isset($_POST['toid']) ? $_POST['toid'] : null;
$newmsg = isset($_POST['newmsg']) ? $_POST['newmsg'] : null;
And do not use mysql_* since it deprecated
The first argument passed to the success callback is the responseText from the AJAX call. Modify your jQuery code to this:
success: function(responseText){
$("#homestatusid").prepend("<div id='divider-"+responseText+"'><div class='userinfo'>"+newmsg+"</div></div>");
// I'm assuming that insert.php returns just the ID you're interested in
}
success: function(response){
$("#homestatusid").prepend("<div id='divider-"+response+"'><div class='userinfo'>"+newmsg+"</div></div>");
}

When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database

I've been trying different options for over a week now and nothing seems to work. What makes this slightly more complicated is that I have multiple forms on the page that all need to be tied to this same submit function. They all have different IDs.
The following is a simplified version of my jQuery:
$('form').on('submit', function(form){
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
// The following fires on first AND second submit
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I have also tried using $('form').submit() with the same results.
Relevant sections of process.php:
$query = 'UPDATE pop_contents
SET ';
$id = $_POST['content_id'];
/* to avoid including in MySQL query later */
unset($_POST['content_id']);
$length = count($_POST);
$count = 0;
foreach($_POST as $col => $value){
$value = trim($value);
$query .= $col."='".escapeString($value);
// don't add comma after last value to update
if(++$count != $length){ $query .= "', "; }
// add space before WHERE clause
else{ $query .= "' "; }
}
$query .= 'WHERE id='.$id;
$update_result = $mysqli->query($query);
After much hair pulling and swearing, I've solved the problem.
TinyMCE editor instances do not directly edit textareas, so in order to submit the form, I needed to first call tinyMCE.triggerSave() from the TinyMCE API. So, the working code looks like this:
$('form').on('submit', function(form){
// save TinyMCE instances before serialize
tinyMCE.triggerSave();
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I was confused when i pass the Ajax String data via tinyMce ..but it is not save to database with php...then i use the
tinyMCE.triggerSave();
event.preventDefault();
then fine.........
$("#save").click(function() {
tinyMCE.triggerSave();
event.preventDefault();
var data = $(this).serialize();
var position = $("#position").val();
var location = $("#job_location").val();
|
|
|
|
var end_date = $("#end_date").val();
var dataString = '&position='+ position + '&job_location=' + location + '&job_category=' + category + '&job_des=' + job_des +'&job_res='+ job_res + '&job_requ='+ job_requ + '&start_date='+ start_date + '&end_date='+ end_date;
alert(dataString);
$.ajax({
type: "POST",
url: "regis.php",
data: dataString,
success: function(data){
}
});
return false;
});
i believe the problem is that you don't prevent the default action of the form. try this
$('form').bind( 'submit', function(event) {
event.preventDefault(); // added
console.log("Binding"); // changed to console.log
$.ajax({
type: "POST",
url: "inc/process.php",
data: $(this).serialize(),
success: function() {
console.log("Your updates have successfully been added."); // changed to console.log
}
});
});
Another neat trick to go along with this is setting the progress state on the tinymce editor, giving you a very simple way to add a loading icon. This article in the TinyMCE docs explains how to do that.
Also from that article, using ed.setContent() will allow you to set the text showing in the editor. I used it to blank the editor, but only after a successful post.

jQuery AJAX referencing $(this) within success function

I have a voting system which sends an id of the clicked item to a PHP script, the PHP updates the database and echos back the new vote counts via an JSON encoded array.
This is the jQuery:
$(".vote_up").click(function(){
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
$(".votes_up").find(id).html(data[x].vote_up);
$(".votes_down").find(id).html(data[x].vote_down);
}
}
});
});
So when i construct the item in the first place, i take the record ID in the database and set it as the items ID. So what i'm trying to do is reference the exact item that was clicked and set it's HTML to the data thats coming back from the PHP. I've checked in Firebug and I'm getting correct data back but the count of votes isnt changing. Any ideas?
This is the PHP for reference:
$query = "SELECT vote_up, vote_down FROM posts WHERE id = '".$id."'";
$result1 = mysql_query($query);
$output = Array();
while ($row = mysql_fetch_array($result1)){
$output[] = Array(
"vote_up" => $row['vote_up'],
"vote_down" => $row['vote_down'],
);
}
echo json_encode($output);
If you just want this in the success: callback to refer to the element that was clicked, just set the context: property for the AJAX request.
$.ajax({
context: this, // set the context of the callbacks
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data) {
// now "this" refers to the element that was clicked
}
You can test it by doing something a little more generic, like:
$(this).html("yep, it works");
... then if that works, consider that it doesn't really make sense to do .html() on the same element in a loop, because each time .html() overwrites the entire content.
Use .append() instead if you're appending data from the loop:
for(var x in data) {
$(this).append(data[x].vote_up);
$(this).append(data[x].vote_down);
}
Wouldn't:
$(".votes_up").find(id).html(...);
Really just need to be:
$('#' + id).html(..);
If you define a variable within the click() method callback, you'll be able to reference it within your ajax success callback. Something similar to this should do you:
$(".vote_up").click(function(){
// Assign the clicked element to a scoped variable...
var target = $(this);
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
// Then refer to it within your callback
target.html(data[x].vote_up);
target.html(data[x].vote_down);
}
}
});
});

Categories