I've got a like button, which holds an ID from a database. I'm trying click the like button, update a database and then it'll switch to unlike without reloading the page.
I'll paste the code below, so you have an understanding:
**index.php:
**
<script type="text/javascript">
// Like Button Function
$(document).ready(function(){
$(".likeBtn").on("click", function(){
var threadID = $(this).attr("id");
console.log(threadID);
$.ajax({
type: "POST",
url: "like_function.php",
data: threadID,
success:function(html)
{
}
});
});
});
</script>
<form action='javascript:void(0);' method='POST' enctype='multipart/form-data'>
<input type='submit' name='likeBtn' class='likeBtn' id='52' value='Like'>
</form>
So the var threadID = retrieving an ID from database (I used 52 as example)
From here, I want to be able to run a php script (like_function.php) to update database using the ID stored as a variable.
Lastly, I want that button to change to unlike. Sorry for being a noob at this. I'm new to Ajax
You need to use a preventDefault() to cancel the event submit and now you can update your data. Example below:
$(document).ready(function(){
$(".likeBtn").on("click", function(e){ // set e in arguments
e.preventDefault(); // use this
var threadID = $(this).attr("id"); // [...]
Related
Thanks for reading. I have tried the answers in other similar questions but none have worked so far. I'm trying to UPDATE values inside a Table that is inside a form, so in the first part of the file is the isset "saveImport" which is the name of the a tag that I'm using to send the id thru the URL:
if (isset($_POST['saveImport'])) {
$id = $_POST['id'];
}
a tag:
<a name="saveImport" href="./?id=<?= $row['id']; ?>" class="saveImport btn btn-success col-xs">Save</a>
I do get the ID value in the URL but since is been updated in the same file I'm assuming it refreshes the page before the variable gets post thru AJAX:
<script type="text/javascript">
$(document).ready(function() {
$('.saveImport').click(function() {
var imp_id = id.id;
var imp_href = $(id).attr('href');
alert(imp_href);
$.ajax({
url: "./",
data: {id : imp_id},
type: "POST",
success: function(data){
alert(id);//send this ID to the PHP variable without
//refreshing the file
}
});
});
});
I'm getting the class .saveImport because it's inside a Table which is displaying values from a Database so it's inside a while loop and if I use an ID it will cause conflict as the ID will repeat itself.
I already created the PHP function to UPDATE the Values which executes if the ISSET is true, so my real problem will be to execute the ISSET and inside grab the ID that was posted with AJAX so I can use the ID in the UPDATE function. Right now, if I click on the a tag, it sends the ID thru URL, the page refreshes but the value of the ID is not getting in the $id = $_POST['id];
I appreciate your time.
This should work.
Change the ajax url to your php file name (mine was t.php).
Replace 99 with your data from php. (id is used. href is not used)
<?php
if (isset($_POST['saveImport'])) {
print_r( $_POST );
exit;
}
?>
<a name="saveImport" id='99' href="./?id=99" class="saveImport btn btn-success col-xs"'>Save</a>
<script type="text/javascript">
$('.saveImport').click(function(event) {
var imp_id = this.id;
$.ajax({
url: "t.php",
data: {id : imp_id, saveImport: 1},
type: "POST",
success: function(data){
alert( data );//send this ID to the PHP variable without
//refreshing the file
}
});
event.preventDefault();
});
</script>
.preventDefault() will prevent the link from loading the target page... And then, ajax will proceed.
$('.saveImport').click(function(event) {
event.preventDefault();
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I created a table with radio button using ajax request. I want to get value from radio button by click event. But jquery event doesn't work on radio button.
my created table by ajax below
I have called this ajax result by bellow code
<code>
<script type="text/javascript">
$(document).ready(function(){
$(".todayTask").click(function(){
var employee = '<?php echo trim($userID);?>';
$.ajax({
url: "ajax_call.php",
type:"POST",
data:{userID:employee},
success: function(result){
$('#taskList').html(result);
}});
});
});
</script>
</code>
Now I want to get value from radio button which stay in ajax result...
by below code but does not work...
<code>
<script type="text/javascript">
$(document).ready(function(){
$("#s").click(function(){
var status_val = $(this).val();
alert(status_val);
});
});
</script>
</code>
Since your radio buttons are loaded via jquery, you need to use on event:
$(document).ready(function(){
$('#taskList').on("click","#s", function(){
var status_val = $(this).val();
alert(status_val);
});
});
You need to also use a class ".s" instead of an ID "#s", because an ID needs to be unique, here is an example:
$('#taskList').on("click",".s", function(){
Bind your click event using on:
$("table").on("click","#s" ,function(){
var status_val = $(this).val();
alert(status_val);
});
Note: ID must me unique. So, either use classes or make sure you have unique id
I am trying to write a code that 'stores items for later' - a button that has url of the item as hidden input, on submit it calls a php script that does the storage in a db. I am more into php, very little knowledge of anything object-oriented, but I need to use jquery to call the php script without moving over there
The problem is how to assign the x and y variables when I have multiple forms on one page
I was only able to write the following
$("form").bind('submit',function(e){
e.preventDefault();
var x = $("input[type=hidden][name=hidden_url]").val();
var y = $("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php?url='+x+'&tit='+y,
success: function() {
alert( "Stored!");
location.reload();
}
});
});
It works fine if you have something like...
<form method="post" action="#">
<input type="hidden" id="hidden_url" name="hidden_url" value="<?php echo $sch_link; ?>"/>
<input type="hidden" id="hidden_title" name="hidden_title" value="<?php echo $sch_tit; ?>"/>
<input type="submit" id="send-btn" class="store" value="Store" />
</form>
..once on the page, I've got about 50 of them.
These are generated via for-loop I suppose I could use $i as an identifier then but how do I tell jquery to assign the vars only of the form/submit that was actually clicked?
You'll have to scope finding the hidden fields to look within the current form only. In an event handler, this will refer to the form that was being submitted. This will only find inputs matching the given selector within that form.
$("form").bind('submit',function(e){
e.preventDefault();
var x = $(this).find("input[type=hidden][name=hidden_url]").val();
var y = $(this).find("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php',
data: {
url: x,
tit: y
},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
As #Musa said, it's also better to supply a data key to the $.ajax call to pass your field values.
Inside your form submit handler, you have access to the form element through the this variable. You can use this to give your selector some context when searching for the appropriate inputs to pass through to your AJAX data.
This is how:
$("form").bind('submit',function(e) {
e.preventDefault();
// good practice to store your $(this) object
var $this = $(this);
// you don't need to make your selector any more specific than it needs to be
var x = $this.find('input[name=hidden_url]').val();
var y = $this.find('input[name=hidden_title]').val();
$.ajax({
url: 'save_storage.php',
data: {url:x, tit: y},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
Also, IDs need to be unique per page so remove your id attribute from your inputs.
I am trying to implement a small chat application where user can text chat with any one of the online users.
My logic behind this is some thing like the following:
Login first.
Fetch the users who are online from DB and show them as list of online users.
Click on the users, then another small window is opening for text chatting.
Create a form(two hidden fields- one is for sender id and another is for receiver id, one textarea and a button for submitting) for this chatting.
Through jQuery, fill the value of receiver id.
By session id, fill the value of sender id.
After submitting the button, I call a page through ajax jquery which is responsible to insert and show the current data from DB.
My code for the ajaxJquery is like :
$(document).ready(function(){
$('#send_btn').click(function(){
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
$.ajax({
type:"POST",
url:"chat_history.php?receiver_id="+receiver_id+"&sender_id="+sender_id+"&message="+messagebox,
success:function(result){
$('#history').html(result);
}
});
$('#messagebox').val('');
});
});
</script>
Up to this, its working fine. But I need to autoload the <div id="history"></div> portion. For that also I am thinking to do by using setInterval() in jQuery. My code is like :
<script type="text/javascript">
var auto_refresh = setInterval(
function (){
$('#history').load("chat_history.php?receiver_id=''&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
</script>
But in this scenario, how to pass the value of receiever_id in load() which is necessary to find out the respective data from DB?
Please let me know whether the requirement is cleared to you or not.
Thanks in advance.
<script>
$(function () {
// function wide variables
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
// button click
$('#send_btn').click(function () {
receiver_id = $('#hide_receiver_id').val();
sender_id = $('#hide_sender_id').val();
messagebox = $('#messagebox').val();
$.ajax({
type : "POST",
url : "chat_history.php?receiver_id=" + receiver_id + "&sender_id=" + sender_id + "&message=" + messagebox,
success : function (result) {
$('#history').html(result);
}
});
$('#messagebox').val('');
});
var auto_refresh = setInterval(function(){
$('#history').load("chat_history.php?receiver_id="+receiver_id+"&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
});
</script>
This is a very simple form that I have found on the web (as I am a jQuery beginner).
<!-- this is my jquery -->
<script>
$(document).ready(function(){
$("form#submit_wall").submit(function() {
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
</script>
<!-- this is my HTML+PHP -->
some PHP ...
while($row_pilt = mysql_fetch_assoc($select_pilt)){
print
<form id="submit_wall">
<label for="message_wall">Share your message on the Wall</label>
<input type="text" id="message_wall" />
<input type="hidden" id="id" value="'.(int)$row_pilt['id'].'">
<button type="submit">Post to wall</button>
</form>
and down below is my PHP script that
writes to mySQL.
It is a pretty straight forward script. However, it is getting little complicated when I submit it. Since I have more than one form on my page (per WHILE PHP LOOP), thus when I submit - only the FIRST form gets submitted. Furthermore, any other subsequent forms that I submit - data is being copied from the first form.
Is there any jQuery functions that clear the data? - or is there a better solution.
Thanks,
Nick
It's because you're giving each form the same id, and thus it is submitting the first element it finds with that id, i.e. the first form. What you should do is assign a unique id to each form, and then give each form an AJAX submit function that submits the form-specific data. You can use jQuery's $.each() function to loop through all the forms and $(this).attr('id') within the submit function to retrieve the form-specific id.
UPDATE: As revealed by the comment on this answer, you actually don't need the each() function because jQuery applies it to every form element anyway.
Here would be an example script:
$(document).ready(function(){
$("form").submit(function() {
var message_wall = $(this).children('input[type="text"]').attr('value');
var id = $(this).children('input[type="hidden"]').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
Because we can't see all of your forms, I'm not entirely sure, but given your question I'm going to assume that the other forms all share the same id (form#submit_wall), which is invalid an id must be unique within the document.
Given that you're going to change the id of the other forms (I'd suggest using a class name of, probably, 'submit_wall', but the specifics are up to you), the jQuery needs to be changed, too. From:
$("form#submit_wall").submit(function() {
To:
$("form.submit_wall").submit(function() { // using the class-name instead of the id.
Now, of course, you run into the same problems of duplicate ids.
So I'd suggest, again, changing the id to a class and changing:
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
to:
var message_wall = $(this).find('.#message_wall').attr('value');
var id = $(this).find('.id').attr('value');
Given the mess that you've posted, above, I find it hard to believe that this is all you need. It would definitely be worth posting the full page (or a demo at JS Fiddle or JS Bin) that fully reproduces your code.