I'm trying to get post id and insert it into database after user click on add to favorite button.
The problem that all the post are return id 30 which is the last id in the database.
My php/html code
while($row = mysqli_fetch_array($get_posts)) {
<i style="float:right;" class="fa fa-pinterest-square">
<form id="pin_post" method="post"> ';
if (isset($_SESSION['user_id'])){
<input type="hidden" value="'. $_SESSION['user_id'].'" name="user_id" />
}
<input type="hidden" value="'.$row['post_id'].'" name="post_id[]" />
</form>
</i>
The jQuery / Ajax code
<script>
$(document).on("click",".fa-pinterest-square",function(e) {
$.ajax({
url: "includes/test.php",
type: "POST",
data: $('#pin_post').serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
I'm getting last id in the database when I click any post.
Please help me to get the id of each post when I click on the
Since you are using #pin_post when serializing it you will get the last hit when jQuery is looking for #pin_post. Either you should use a unique id or something like this
$(document).on("click",".fa-pinterest-square",function(e) {
var form = $(this).find('form'); //Since the form is child to <i>
$.ajax({
url: "includes/test.php",
type: "POST",
data: form.serialize(),
success: function(data) {
alert(data);
}
});
});
Related
I want to comment on a post with a popup form including 4-5 fields. I the popup form I want to provide the post id of the post to comment on, but when posting this id through a hidden field, it always results in the last post id. How can I generate a dynamically different id which gives me the exact post id?
<form id="forms">
<label for="email">Facility :</label>
<input type="text" class="form-control" id="facility" name="facility" maxlength="50">
//printing{{$customerpost->id}} this value gives correct post id
<input type="hidden" name="hidden" value="{{$customerpost->id}}" id="hidden">
<button type="submit" class="btn btn-lg btn-primary btn-block" id ="submit">Post It! </button>
</form>
$( 'form' ).submit(function ( e ) {
var data;
data = new FormData();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
authorization: $('meta[name="csrf-token"]').attr('content'),
}
});
data.append('facility', $("#facility").val());
data.append('hidden', $("#hidden").val());
console.log(data);
alert(data);
$.ajax({
url: 'api/bidon/',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function ( data ) {
alert("sucess");
alert( data );
}
});
e.preventDefault();
});
When I log to the console, it always gives me the last post id. How can I solve this using the Laravel framework?
Simple do this on click
<!-- Add post id in attribute -->
<div data-id="12345" class="btn"> add comment </a>
<script type="text/javascript">
$('body').on('click','.btn',function(){
// get id from
var id = $(this).attr('data-id');
// set id to hidden attribute
// $('#hidden').attr('data-id', id);
// or set id to hidden input
$('#hidden').val(id);
// Show form
$('#forms').slideUp();
});
</script>
I have two links, Delete and View. Delete is working perfectly. I am getting the issue on view link. I have to display specific records after clicked on view link.If you notice that delete anchor tag I wrote href='delete.php?function=delete&del_id=$id'. It's calling the delete.php file and deleting a specific record. I want to know about how to write in view anchor tag to display records? Please check below image.I want to clicked on view and display the records in text fields.PHP file added. Please check my ajax code. It is also not working. Ajax code is not working here. I have to display the output in the text field.If i write directly $id=2 then it is display records in alert. Hope you guys can understand now.Would you help me in this?
//delete.php
function view($conn) {
$id=$_GET['view_id'];
$admin_view="SELECT * from view_table WHERE Id=$id";
$result = $conn->query($admin_view);
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$parent_name=$row['Name'];
$parent_email=$row['Email'];
$admin_mobile=$row['Mobile_no'];
}
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href='delete.php?function=delete&del_id=$id' >Delete</a>
<a href='#Popup' onClick='a_onClick(<?php $id?>)' class='btn-view'>View</a>
<form action="#" method="post">
<input type="text" name="Name" placeholder="username" value="<?php echo $parent_name;?>" >
<input type="email" name="email" placeholder="email" value="<?php echo $parent_email;?>" >
<input type="text" name="Mobile_no" placeholder="Mobile no" value="<?php echo $admin_mobile;?>" >
Cancel <span class="close"></div>
</form>
<script>
function a_onClick(id) {
var id = id;
var Name=$('#name').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "delete.php?function=view&view_id=id",
data:'Name='+Name,
dataType: "html", //expect html to be returned
success: function(response) {
// $("#responsecontainer").html(response);
alert(response);
}
});
}
</script>
you need to change some changes
<a href='#Popup' onClick='a_onClick(<?= $id ?>)' class='btn-view'>View</a>
<script>
function a_onClick(id) {
var id = id;
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "delete.php?function=view&view_id=id",
data:'Name='+Name,
dataType: "html", //expect html to be returned
success: function(response) {
// $("#responsecontainer").html(response);
alert(response);
}
});
}
</script>
hope its help you
I am adding a "like" feature to my screenshot gallery. I have successfully worked it out to change color to red when someone likes... and go back to gray when unlike... and then a php script handles all the DB magic.
But I can't wrap my head around how to change the actual text value shown; i.e. if someone likes, change the text from 10 to 11. If they unlike, change from 2 to 1, etc.
Can anyone suggest an approach to look into?
These are my javascript & html snippets if they help. The text in the HTML I want to change here is represented by "$row['Likes']"
$(".ajax-unlike").submit(function(){
var refid = $(this).find('input[name="refid"]').val();
var data = {
"action": "unlike"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "galleryajax.php", //Relative or absolute path to response.php file
context: document.getElementById(refid), //!! ADD THIS
data: data,
success: function(data) { //!! REMOVE refid FROM HERE
$(this).removeClass("thumb-comment-red", 1000);
}
});
return false;
});
<span class="thumb-comment" id="like'.$row['GalleryID'].'">
<form class="ajax-like" method="post" accept-charset="utf-8">
<input type="hidden" name="mcname" value="'.$user->profile_fields['pf_minecraftname'].'" />
<input type="hidden" name="galleryid" value="'.$row['GalleryID'].'" />
<input type="hidden" name="refid" value="like'.$row['GalleryID'].'" />
<input type="hidden" name="likerswithoutthisuser" value="'.str_replace($user->profile_fields['pf_minecraftname'],"",$row['Likers']).'" />
<button type="submit" style="border: 0; background: none;">
<i class="fa fa-heart"></i>
'.$row['Likes'].'
</button>
</form>
</span>
new code for comment down below
//Look for forms with "like" class
$(".ajax-like").submit(function(){
var refid = $(this).find('input[name="refid"]').val();
var btnrefid = "button#" + refid;
var formrefid = "form#" + refid;
var data = {
"action": "like"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "galleryajax.php", //Relative or absolute path to response.php file
context: document.getElementById(refid),
data: data,
success: function(data) {
$(this).addClass("thumb-comment-red", 1000);
$(btnrefid).html("<i class='fa fa-heart'></i> " + data["newlikes"]);
//Now stop further changes from recording based on submissions from this specific form
$(formrefid).submit(function(){
alert("You have already liked or unliked this screenshot. Please reload the page if you want to change your mind.");
});
}
});
return false;
});
Have a look at innerHTML like:
document.getElementById("demo").innerHTML = "value";
Or JQ way
$(selector).html("value");
success: function(data) { //!! REMOVE refid FROM HERE
$(this).removeClass("thumb-comment-red", 1000).innerHTML="UR New TEXT HERE";
//can even use $(element).text("text") or $(element).html("<span>TEXT</span>") like any html elements can be added according to requirement if you plan to use jquery//
}
On my site i am loading shopping products with the "add to cart"-button dynamically with a jquery ajax call. For the shopping cart itself, I use jcart, jquery plugin.
When I then add an item to the cart, jcart calls a php-file with ajax and POST. All works fine, the products are correctly added to the cart, but the page reloads every time I add an item to the cart.
When I don't use the ajax call to load the products (e.g. load them directly in the page), all works fine, so there must be a conflict somewhere.
Any clues?
This is my products-function and the html.
...
<script>
function loadProducts(str) {
$.ajax({
type: 'GET',
async: true,
url: 'ajax/load.php',
data: {'max-id' : str},
cache: false,
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
});
}
</script>
<script>
$(document).ready(function() {
var n = '';
loadProducts(n);
});
</script>
<script src="jcart/js/jcart.js"></script>
</body>
</html>
The jcart-Plugin with its ajax-call can befound here:
http://conceptlogic.com/jcart/standalone-demo/jcart/js/jcart.js
Here are the functions from jcart.js.
$.ajaxSetup({
type: 'POST',
url: path + '/relay.php',
cache: false,
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
error: function(x, e) {
...
}
});
...
function add(form) {
// Input values for use in Ajax post
var itemQty = form.find('[name=' + config.item.qty + ']'),
itemAdd = form.find('[name=' + config.item.add + ']');
// Add the item and refresh cart display
$.ajax({
data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
success: function(response) {
// Momentarily display tooltip over the add-to-cart button
if (itemQty.val() > 0 && tip.css('display') === 'none') {
tip.fadeIn('100').delay('400').fadeOut('100');
}
container.html(response);
$('#jcart-buttons').remove();
}
});
}
...
// Add an item to the cart
// is called from the submit-buttons within each product picture
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
The "loadProducts()" function puts this into #products container for each item:
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="SDK12345" />
<input type="hidden" name="my-item-name" value="Product Name" />
<input type="hidden" name="my-item-price" value="1.00" />
<input type="hidden" name="my-item-qty" value="1" />
<ul>
<li><img src="product-image.jpg"/></li>
<li>1.00 Dollar</li>
</ul>
<input type="submit" name="my-add-button" value="Add to cart" class="button" />
</fieldset>
</form>
I'm guessing you are calling the loadProducts() function in a binded click action on your add to cart button. If you are using an element with a default click behavior. You might want to prevent that with a 'return false;' on the last line of your binded click function.
like this:
$('a.addtocart').bind('click', function(){
//logic here (ajax)
return false;
});
After your success function there's also a comma that might get messy in IE:
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
Remove the comma
I think there's an error in your ajax call, try to work it out... i cant see the logic of your php file that adds products to your basket. but if you want to send the data of your form (quantity, itemid), serializing your form data should be enough. No need to pass extra get variables.
function add(form) {
$.ajax({
data: form.serializeArray(),
url: 'yourfile.php',
success: function(response) {
// logic
}
});
}
Ok, I found the solution.
As the forms are loaded via ajax, they were no correctly interpreted by jcart.js (though the functions all worked fine for themselves).
"bind" didn't work, but "live" fixed it:
$('.jcart').live('submit',function(e) {
add($(this));
e.preventDefault();
});
$(document).ready(function(){
/* fetch elements and stop form event */
var submitData = $("form.follow-form").submit(function (e) {
/* stop event */
e.preventDefault();
/* "on request" */
$(this).find('i').addClass('active');
/* send ajax request */
$.ajax({
type: "POST",
url: "recycle.php",
data: submitData,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
/* find and hide button, create element */
$(e.currentTarget)
.find('button').hide()
.after('<span class="following"><span></span>Recycled!</span>');
}
}
});
});
});
I think there is an error in this jquery syntax and or it could be my php code, I cant seem to find it!!
this is the recycle.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$tweet =$_POST['tweet'];
mysql_query("INSERT INTO notes SET user_note='".$_POST['tweet']."',dt=NOW(),recycle_id='".$id."', user_id = '".$_SESSION['user_id']."' ");
?>
and this is the html code
<form class="follow-form" method="post" action="recycle.php">
<input name="id" value="$id" type="hidden">
<input name="tweet" value="$tweet" type="hidden">
<button type="submit" value="Actions" class="btn follow" title="123456">
<i></i><span>recyle</span>
</button>
</form>
Your use of submitData looks strange to me. You don't have to declare that variable and it will not contain the data of the form (I think submit() returns nothing, so submitData would be undefined).
I think you have to do:
$("form.follow-form").submit(function (e) {
//...
$.ajax({
type: "POST",
url: "recycle.php",
data: $(this).serialize(), // gets form data
dataType: "html",
success: function(msg){/*...*/}
});
});
Reference: .serialize()
If you're using jQuery you probably already know this, but if you use Firebug it should show you any syntax errors. Just a thought.