pass values to another script through ajax - javascript

Below is a piece of code that is placed inside for loop
for( some condition will go here )
{
echo "<td>
<a href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
}
On clicking over it the user gets directed to event.php page and along with it, event_id and action parameters are also carried forward,
but instead of this
i wish to call event.php page to the first page through ajax for this i tried this
<script>
function chk()
{
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
}) ;
return false;
}
</script>
echo
"<td>
<a onclick='return chk()'>". ($i - $startday + 1) . "</a>
</td>";
but its not working, and i also wish yo carry forward event_id and action parameters through ajax to event.php page on every click, can anyone tell how this can be done

Here is what you can do
<a href="#" class="myclass" data-id="'.$someID.'" data-action="'.$someAction.'">
and js will be
$(".myclass").on("click", function(){
var id = $(this).data("id");
var action = $(this).data("action");
$.ajax({
type : "post",
url : "event.php",
data : {
"id":id,
"action":action
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});
});

It should be like this
$.ajax({
type : "post",
url : "event.php",
data : {
"event_id":"-id of the event-",
"action":"-0action paramter-"
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});

Build your loop adding a class:
echo "<td>
<a class='anEvent' href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
Then use:
<script type="text/javascript">
$('.anEvent').on('click',function(e){
e.preventDefault();
$('#msg').load($(this).attr('href'));
})
</script>

You can use data attributes and $.post request, and better if you can avoid the inline-events and give your link an identifier (class ajax-link in my example because your code will be created from a loop so we don't have to use id since id should be unique in same document) then you can use it to attach click event to the a tag, check the following example :
PHP :
"<td>
<a class='ajax-link' data-event-id=".$datee2." data-action='Details'>". ($i - $startday + 1) . "</a>
</td>";
JS :
$('body').on('click', '.ajax-link', function(e){
e.preventDefault();
var url = $(this).data('action');
var event_id = $(this).data('event-id');
$.post(url, {event_id: event_id, action: action},
function(html)
{
$('#msg').html(html);
}
});
})
Hope this helps.

The problem is you are clicking the link which starts loading event.php.
You should use event.preventDefault() to avoid default action in chk() function.
function chk()
{
event.preventDefault();
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
});
return false;
}

Related

JQuery .on('Click') only working once, not multiple times

Currently I'm trying to make a Like Button with counter for my website. The issue I'm having, is that I'm not quite versed in javascript and AJAX, and do not know how to correctly write the AJAX Request.
The Ajax request does work, and does add the like (also removal works too) but I have to refresh the page, if I want to click that same like or dislike again. I can't keep clicking to like and unlike. (Hopefully that makes sense).
Here is my Jquery
$(document).ready(function(){
$('.post-add-icon').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/addlike.php',
type: 'post',
data: {
'likes': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});
</script>
<script>
$(document).ready(function(){
// when the user clicks on unlike
$('.post-add-icon-active').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/removelike.php',
type: 'post',
data: {
'unliked': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});
Here is addlike.php
require_once("../../config/db.php");
include_once("../classes/user.php");
include_once('../classes/posts/likes.php');
include_once('../classes/posts/comments.php');
include_once('../classes/posts/shares.php');
if(isset($_POST['likes'])) {
$id_post = $_POST['id_post'];
$id_user = $_SESSION['id_user'];
$likeTotal = mysqli_query($conn, "SELECT * FROM likes where id_post='$id_post'");
$likeTotalResult = mysqli_num_rows($likeTotal);
$likeTotalPerUser = mysqli_query($conn, "SELECT * FROM likes WHERE id_user='$id_user' AND id_post='$id_post'");
$likeTotalPerUserResult = mysqli_num_rows($likeTotalPerUser);
if($likeTotalPerUserResult > 0) {
$likes = new Likes($conn, $id_user);
$likes->loadLikes($id_post, $id_user);
$likesPictures = new Likes($conn, $id_user);
$likesPictures->loadLikerPictureArray($id_post, $id_user);
$staticCommentCountDisplay = New Comments($conn, $_SESSION[id_user]);
$staticCommentCountDisplay->DisplayCommentsTotal($id_post);
$staticShareCountDisplay = New Shares($conn, $_SESSION[id_user]);
$staticShareCountDisplay->DisplayShares($id_post);
exit();
} else {
mysqli_query($conn, "INSERT INTO likes (id_user, id_post, liked) VALUES ('$id_user', '$id_post', '1')");
$likes = new Likes($conn, $id_user);
$likes->loadLikes($id_post, $id_user);
$likesPictures = new Likes($conn, $id_user);
$likesPictures->loadLikerPictureArray($id_post, $id_user);
$staticCommentCountDisplay = New Comments($conn, $_SESSION[id_user]);
$staticCommentCountDisplay->DisplayCommentsTotal($id_post);
$staticShareCountDisplay = New Shares($conn, $_SESSION[id_user]);
$staticShareCountDisplay->DisplayShares($id_post);
exit();
}
}
This is the response of booth addlike and remove like.
if(mysqli_num_rows($hasUserLiked) > 0){
echo $likeEcho = '<div class="post-additional-info inline-items" id="likeUpdate-'. $id_post .'">
<span id="likeUpdate'. $id_post .'"><a style="cursor:pointer" class="post-add-icon-active inline-items" id="' .$id_post. '" data-id="' .$id_post. '">
<svg class="olymp-heart-icon">
<use xlink:href="svg-icons/sprites/icons.svg#olymp-heart-icon"></use>
</svg>
<span class="likes_count" id="' .$id_post. '">' .$totalLikes. '</span>
</a>
</span>';
} else {
echo $likeEcho = '<div class="post-additional-info inline-items" id="likeUpdate-' . $id_post . '">
<span id="likeUpdate'. $id_post .'"><a style="cursor:pointer" class="post-add-icon inline-items" id="' .$id_post. '" data-id="' .$id_post. '">
<svg class="olymp-heart-icon">
<use xlink:href="svg-icons/sprites/icons.svg#olymp-heart-icon"></use>
</svg>
<span class="likes_count" id="' .$id_post. '">' .$totalLikes. '</span>
</a>
</span>';
}
}
And lastly, here is my script toggle that is at the beginning of my post loop.
<script>
function toggle<?php echo $row['id_post']; ?>() {
var element = document.getElementById("toggleComment<?php echo $row['id_post'];?>");
if (element.style.display == "block")
element.style.display = "none";
else
element.style.display = "block";
}
</script>
Hopefully that is enough information. Like I was originally saying, if the user clicks the like button once, it displays the correct corresponding response. But if the user then decides to click that same button again(it's displayed new because of the response), it does nothing. Does the jquery toggle need to reload with the response?
I believe lies in fact that you send this:
'likes':'1'
this means that you always set likes to +1.
You should not send the number of likes at all. You should just send something like 'like', and your backend should do something like
previousNumberOfLikes++ // increment by 1.
You should never accept this kind of value from frontend, because it can be easily manipulated.
Best,
Edit:
I might be mistaken. You are returning totalLikes. This might be the issue. If you always send totalLikes without incrementing it, it will never change. Maybe look into this.
You're generating fresh post-add-iconso its not here on $(document).ready(), try it without replacing like icon
I think you need to unbind the event, follow the offical jquery website :
https://api.jquery.com/die/
You have to write document.ready function only once , not multiple time .
put all functions inside document.ready like below :
<script>
$(document).ready(function(){
$('.post-add-icon').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/addlike.php',
type: 'post',
data: {
'likes': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
// when the user clicks on unlike
$('.post-add-icon-active').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/removelike.php',
type: 'post',
data: {
'unliked': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});
</script>
Try this!
<script>
$(document).ready(function(){
$('body').on('click','.post-add-icon', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/addlike.php',
type: 'post',
data: {
'likes': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
// when the user clicks on unlike
$('body').on('click','.post-add-icon-active', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/removelike.php',
type: 'post',
data: {
'unliked': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});

Form/button stop work after ajax partly reload page after form success

(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});

Getting a post variable inside a function

I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>

append(add) a text in url using jQuery

below code working fine but I need to append option1 in href,
$(document).ready(function () {
$("#head_drop .dd-option").click(function () {
var option = $('.dd-option-value',this).attr('value');
var option1 = $('.dd-option-text',this).text();
// alert(option1);
$.ajax({
type: 'get',
url: '<?php echo $this->getBaseUrl();?>categories/index/city/',
data: {option: option},
success: function(data) {
$(location).attr('href',"<?php echo $this->getBaseUrl()?>");
}
});
});
});
now its return
http://example.com/
I want like http://example.com/option1
I tried $(location).attr('href',"<?php echo $this->getBaseUrl()?>"option1); but failed to get, Thanks...
If option1 is a variable all you need is to concatenate with a + -
$(location).attr('href',"<?php echo $this->getBaseUrl()?>" + option1)
You have your " at the wrong place, it should read:
$(location).attr('href',"<?php echo $this->getBaseUrl()?>option1");

Jquery ajax addClass issue

First sorry im a big beginner and just experimenting, and I made a similar wall like facebook with oembed.
And would like to add a like, and dislike button too.
I started with the like button, it works, likes, and unlikes too, and the cookie saves the class value perfectly.
My problems is the ajax call, so actually when I click on the like button it overwrites all anchors href val and adds a class to all not on what click.
here is my code
jquery
var cookieLike = "like_"
$('a.like').each(function(){
var id = $(this).attr('href'), cookieLiked = cookieLike + id;
switch($.cookies.get(cookieLiked) ) {
case "unliked":
$(this).removeClass('btn-success');
break;
case "liked":
$(this).addClass('btn-success');
break;
}
}).on('click', function(e){
e.preventDefault()
var likeId = $(this).attr('href');
$.ajax({
url: "<?php echo base_url(); ?>stream/like/" + likeId ,
type: "post",
data: likeId,
dataType: "json",
success: function(like)
{
if(like.likeStatus == "unliked") {
$('a.like').attr('href', likeId).removeClass('btn-success');
$.cookies.set(cookieLike + likeId, 'unliked');
}else if(like.likeStatus == "liked") {
$('a.like').attr('href', likeId).addClass('btn-success');
$.cookies.set(cookieLike + likeId, 'liked');
}
}
});
});
html
<div class="stream-bottom">
Komment
<div class="pull-right like-options">
<i class="icon-thumbs-up" title="tetszik"></i>
<i class="icon-thumbs-down" title="nem tetszik"></i>
</div>
</div>
could please someone point out what i am missing?
Maybe:
.on('click', function (e) {
e.preventDefault();
var button = $(this);
var likeId = button.attr('href');
$.ajax({
url: "<?php echo base_url(); ?>stream/like/" + likeId,
type: "post",
data: likeId,
dataType: "json",
success: function (like) {
if (like.likeStatus == "unliked") {
button.removeClass('btn-success');
$.cookies.set(cookieLike + likeId, 'unliked');
} else if (like.likeStatus == "liked") {
button.addClass('btn-success');
$.cookies.set(cookieLike + likeId, 'liked');
}
}
});
});
Bind the target element (the clicked link) and reference it in the success callback
In the .on('click') callback
var $link = $(this);
In the success callback use
$(this).attr('href', likeId)
instead of
$('a.like').attr('href', likeId)
When you use $("a") or $("a.like") you are referring to the entire set of anchor tags or anchor tags with 'like' as the class name. To specifically use the anchor tag on which you have clicked use $(this) variable.
That will give you the element on which the event got generated and in this case the anchor tag on which you clicked.

Categories

Resources