Pass multiple values to jQuery - php

I built a for each loop that pulls back several rows from the database. Each row it pulls has a link, and a hidden input box with a value of posting_id. This link will work similar to a like button on facebook in a way. The hidden input box just stores the posting_id. When you click the "like" link, it sends over the posting_id to a jQuery page and pings back a page called community to tell it the user has "liked" the post.
Here's the problem
I'm pulling several rows, and it seems that only the top row being pulled is actually sending the data to the jQuery page when you click the "like" button. If I click on any other "like" button other than the top one it will not work at all.
Jquery Page
$('.bump_link').click(function(){
var posting_id = $('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
Foreach Loop
foreach ($result as $value) {
$group_postings .= '
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
<div id="bump_icon" class="bump_link"></div>
<span id="counter"></span>
';
}
I hope I've made the issue clear, it was and is difficult to explain.

The problem is you are using a class to get the posting_id, since all the hidden fields have the same class only the first elements value is passed no matter what button you click.
i recommend using this html, without the hidden input, pass the value as a data attribute
<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">
and in this js, get the posting id from the data attribute
$('.bump_link').click(function(){
var posting_id = $(this).data('postid'); // get the posting id from data attribute
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});

You are calling val() on selector you might return more then one elements, but val() will give you the value of one (first) element only. You can use map() to get all values of input having class posting_id
var posting_id_values = $('.posting_id').map(function(){
return this.value;
}).get().join(',');

Your problem is this line:
var posting_id = $('.posting_id').val();
This will return the first posting_id value every time, not the one associated with the bump_link you are clicking on.
There are lots of ways to solve this. One way is to use .prev() to select the previous element:
var posting_id = $(this).prev('.posting_id').val();
this selects the previous posting_id element from the current div. This relies on the fact that the posting_id element is before the associated bump_link div.

If you want to send just the posting_id of the clicked button, you could change your PHP/HTML code like this:
foreach ($result as $value) {
$group_postings .= '
<div id="bump_icon" class="bump_link">
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
</div>
<span id="counter"></span>
';
}
And your JS code like this:
$('.bump_link').click(function(){
var posting_id = $(this).find('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});

use on delegated event since you are adding the content dynamically and
$(this).prev('.posting_id') // to get the posting data value
$(document).on('click','.bump_link',function(){
var posting_id = $(this).prev('.posting_id').val(); //<-- use $(this) reference
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});

Related

Grab checkbox values before form submission

I have the following loop, which shows a checkbox along with an answer (which is grabbed from Wordpress):
$counter = 1;
foreach ($rows as $row){ ?>
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo $row['answer'];
} ?>
This is part of a bigger loop that loops through a set of questions and for each question it loops through the answers (code above).
How can I grab the checkboxes that the user has checked and display the values within a div before the form is submitted?
I know I can use the following to check if the checkbox is checked:
$('form #mycheckbox').is(':checked');
I'm not sure where to start with all the looping!
You can use the selector :checked
$.each("#mycheckbox:checked", function() {
$("div").append(this.val());
});
You may do something like below:
var divContent = "";
$("form input[type=checkbox]:checked").each(function() {
divContent += this.value + "<br/>";
});
$("div").html(divContent);
Not completely clear to me when this should be executed. From your question it looks to me like that should happen when user clicks on submit button, in such case you just need to place that code into $("form").submit(function(){...});
var boxes = $('input[type="checkbox"][name^="answer"]');
$('#myDiv').empty();
boxes.on('change', function() {
boxes.filter(':checked').each(function(i, box) {
$('#myDiv').append(box.value);
});
});
Get all the matching checkboxes, and whenever one of the checkboxes changes update a div with the values of the checked boxes.
The loop you provide is happening server side, as it is php code. When you wan't to validate the form before submission you must do it on the client, ie using javascript.
So, you will not use the same loop, but rather create a new one that is run when any checkbox is changed.
I suggest you to add a class name to the checkboxes (like class='cb_answer') in the php loop. This will help you to safely select the specific checkboxes when doing the validation.
Here is a script snippet that will add the value of selected checkboxes to a div each time any checkbox is changed. Add this just before </body>. May need to modify it to fit your needs.
<script>
// make sure jQuery is loaded...
$(documet).ready( {
// when checkboxes are changed...
$('.cb_answer').on('change', function() {
// clear preview div...
$('#answers_preview').html('');
// loop - all checked checkboxes...
$('.cb_answer:checked').each(function() {
// add checkbox value to preview div...
$('#answers_preview').append(this.val());
});
});
});
</script>
assuming id='answers_preview' for the div to preview the answers and class='cb_answer' for the checkboxes.

Javascript multiple values on the same ID

I have a loop in php that echos out a <input type="hidden" id="lol" value=$id />
Every time the loops go through i get a new value in the hidden input field as you can understand.
Now, im trying to grab the value from each of these items and get grab it with Javascript and SAJAX.
The javascript im using now works, But! It only grabs the first value (because the ID is the same on each input)
Javscript:
function Showbooking() {
id = document.getElementById('lol').value;
x_showBookingForm(id, do_showBookingForm);
}
function do_showBookingForm(html) {
openPopup(600, 550, html);
}
As you can see im opening a POPUP with javascript aswell and exports the value into that popup window.
So on every popup I get the same value (the value from the first input).
How Do I get around this problem?
Change ID to name
Use document.getElementsByName and loop
var lols = document.getElementsByName("lol");
var vals=[];
for (var i=0, n=lols.length;i<n;i++) {
vals.push(lols[i].value);
}
alert(vals.join(","));
getElementById says element rather than elements because it returns only one item. id is supposed to be unique. You could do something to the effect of:
var inputs = document.getElementsByTagName("input");
var values = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].type === "hidden"){
values.push(inputs[i].value;
}
}

Loading Ajax for each node in Drupal view with nid argument

I have a view of teasers in Drupal. Each teaser has a click() handler which is supposed to send its node id as an argument to load a view via ajax. I've tried 2 different jquery approaches, but am having no luck.
The first example sends the nid for only the last node in the view. So that no matter what teaser I click only the nid for the last teaser gets sent.
Drupal.behaviors.ajaxview = function(context) {
$(".ajaxclick").click(function(){
$(".container").load(Drupal.settings.basePath + "myajax/" + <?php echo $node->nid;?>;);
});
}
In the second approach, a click on a button of class "ajaxview" will send the correct nid but but instead of sending for just the one clicked button to it's corresponding div, it will send a nid for EACH button with a class of "ajaxview" into EACH div with a class of "container". So I end up with the contents of every single view generated from every single teaser into every single div. WAAAAY too much!
$(document).ready(function() {
$(".ajaxclick").click(function(){
$(".container").load(Drupal.settings.basePath + "myajax/" + <?php echo $node->nid; ?>);
});
});
Here is the button;
<button class="ajaxclick">click</button>
And the div:
<div class="container"></div>
Any idea how I can get each click to send the nid of that teaser clicked upon as the argument and load only that view?
Your code is javascript.
You can't use:
<?php echo $node->nid; ?>
You will have to use jQuery approach to get the nid you want.
For example, if you have the nid in a hidden filed like:
<input type="hidden" id="ID" value="100" />
You can use the following jQuery to get the nid:
var nid = $("#ID").val();
Turns out I was able to get it working using a revision of Ionut.A's suggestion;
Drupal.behaviors.ajaxview = function(context) {
$(".ajaxclick").click(function(){
var nid = $(".mynid").eq($('.ajaxclick').index( $(this) )).val();
$('.container').eq($('.ajaxclick').index( $(this) )).load(Drupal.settings.basePath + 'myajax/' + nid);
return false;
});
}
and for the html;
<input type="hidden" class="mynid" value=<?php echo $node->nid;?> />
I had to use class instead of id as the id would only return the id from the first node.

jQuery get values from selected checkboxes

First problem is that I do not know how to get the values of SPECIFC checkboxes when they are checked.
I need a function that will get the value of the selected checkboxes by checkbox ID or Name.
This is the code I have so far:
$("#doStatus").click(function(){
var Tuitting = $('textarea#tuitting').val();
var F = $('input#Fb').val(); //checkboxes with ID Fb
var T = $('input#Tw').val(); //checkboxes with ID Tw
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", { tuitting: Tuitting, f: F, t: T });
window.setTimeout('location.reload()', 1000);
return false;
});
Now the second problem is that both var F and var T may contain MORE than one values in an array..
Obviously when I use the ajax get functions the multiple values for both var F and var T are not
passed at all. What is the problem..?
How do I pass multiple values in an array that will be then runed by the foreach on the doStatusBox.php page?
Please help me.
$("#doStatus").click(function() {
var Tuitting = $('textarea#tuitting').val();
var F = $('input[name="fb"] :selected').val();
//You can give the name of checkbox and get the values of selected checkbox
return false;
});
I'm answering based on an assumption: you need checked checkboxes to pass them via GET method to your doStatusBox.php script.
However, why would you go trough the trouble of finding which checkbox is checked if you can simply use the serialize() method and let jQuery do the job for you?
$("#doStatus").click(function()
{
var serialized = $("#someFormHere").serialize()
// or, if you have your form elements within a div or another element
var serialized = $("#elementID :input").serialize();
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
However, is "#doStatus" a submit button submitting the form or something else? If it submits the form, bind the submit event to the form, not click event to the button submitting it.

How to pass multiple selected (through checkboxes) row ids to a php script in jQuery?

I'm generating an html file which looks like:
<tr id="ID001" property1="PROPERTY001"><td><input type="checkbox"
name="row_checkbox_ID001"></td><td>...</td><td>...</td></tr>
<tr id="ID002" property1="PROPERTY002"><td><input type="checkbox"
name="row_checkbox_ID002"></td><td>...</td><td>...</td></tr>
When the user selects individual rows for deletion, how can I (through jQuery), pass this to a php script?
I will need to build something like this:
$(document).ready(function () {
$('#contact-form input.contact-delete').click(function (e) {
e.preventDefault();
$.get("deleterecord.php", ...);
});
});
There can be 0, 1 or multiple rows... The HTML being generated is under my control and can be modified.
Clarification:
I want to have a button above all these rows which the user can click on AFTER he has selected the rows from the table.
<div id='contact-form'><h2>Contacts</h2>
<input type='button' name='contact-delete' value='Delete Record(s)'
class='contact-delete'/>
The TRs need to be deleted, but BEFORE that, the deleterecord.php script needs to be called with the TR ids.
Use HTML arrays
<input type="checkbox" name="chk[]" value="01234">
<input type="checkbox" name="chk[]" value="98765">
You could create a JSON object containing details of any rows selected (ID's or whatever you need) and send that to your php script. Check out this article on json, php + jquery.
I believe, you are looking for similar behavior:
$('#contact-form input.contact-delete').click(function (e) {
var $this = $(this);
// find the table row, in which are elements contained
var $tr = $this.closest('tr');
// take id
var id = $tr.attr('id');
// ajax with id
$.get("deleterecord.php?id="+id, function (data) {
// remove table row on success
$tr.remove();
});
e.preventDefault();
});
Sorry for answering my own question, but the SO post at: Getting all selected checkboxes in an array neatly solves my problem!
For future visitors to this page, pay attention to variable names in your HTML and how you're accessing the input checkboxes in jQuery!

Categories