Jquery split variable back from PHP json (checkbox:checked) - php

In this code jquery get the data back from php and i would like to get jquery explode one of the variable where multiple auto are stored and finally get the specific checkbox checked
json_reponse_from_PHP: "auto1; auto3; auto4".
$(document).on("click", "#update", function(e) {
e.preventDefault();
var datas = 'pg/post.php';
$.getJSON(datas, function(data) {
$.each(data, function( key, value ) {
$('input[name=' + key + '], select[name=' + key + '], textarea[name=' + key + ']').val(value);
});
});
});
<div>
<input type="text" name="name" value="" />
<input type="text" name="name" value="" />
</div>
See example:
<input type="checkbox" name="auto[]" checked="checked" value="auto1" />
<input type="checkbox" name="auto[]" value="auto2" />
<input type="checkbox" name="auto[]" checked="checked" value="auto3" />
<input type="checkbox" name="auto[]" checked="checked" value="auto4" />
<input type="checkbox" name="auto[]" value="auto5" />
<input type="checkbox" name="auto[]" value="auto6" />
Can you help me to find

If you want to check a checkbox you don't use val() you use prop('checked', true)
Since you have array naming on elements you can't match the specific name so you will need to use the returned value to help target the checkboxes.
Also what you are sending from server doesn't match the names anyway.
$.each(data.split(';'), function(_, val ) {
$(':input[value=' + val +']').prop('checked',true);
});
It makes no sense either not to send array from server instead of json_encoding a delimited string in your php

Related

getting data by jQuery ajax PHP and Database

my Code not working Exactly as I need, 2 pages php and 1 jquery file to get the data by jquery Ajax.
First Page name catfd.php :
<input type="checkbox" value="2" class="catcf"> catfd2 <br />
<input type="checkbox" value="35" class="catcf"> catfd35 <br />
<input type="checkbox" value="22" class="catcf"> catfd22 <br />
<input type="checkbox" value="133" class="catcf"> catfd133 <br />
<input type="checkbox" value="28" class="catcf"> catfd28 <br />
<input type="checkbox" value="33" class="catcf"> catfd33 <br />
<input type="checkbox" value="55" class="catcf"> catfd55 <br />
<input type="checkbox" value="44" class="catcf"> catfd44 <br />
and the second page name getvalue.php
this page it's given me the right answer if var '$catcfid' is Exactly one I choose from input filed in catfd.php ( i think my problem with Jquery ajax
if(isset($_POST['catcf'])){
$catcfid= $_POST['catcf'];
$sql = 'SELECT * FROM tablename where cat_id = '.$catcfid.' order by p_id asc';
$catandproid = $wpdb->get_results($sql);
foreach($catandproid as $key){
echo $key->title;
}
}
this is the jquery ajax file
$(document).ready(function(){
$(".catcf").on('click', function() {
if ($('input.catcf').is(':checked')) {
var catcf = Number($(this).val());
$(".catcf").val(catcf);
$.ajax({
url: 'getvalue.php',
type: 'post',
data: {catcf:catcf},
beforeSend:function(){
$(".main-area-courses-continer").html("Looding....");
},
success: function(response){
// Setting little delay while displaying new content
setTimeout(function() {
// appending posts after last post with class="post"
$(".main-area-courses-continer:last").after(response).show().fadeIn("slow");
}, 2000);
}
});
}
});
});
the code is working but the result gives to me is repeating the first checkbox value I choose its mean jquery didn't change the value of class="catcf" because there unic value for each class. and I will use multiple choices from the checkbox.
i want use this checkbox to get different result from database .
Your problem is the following line:
$(".catcf").val(catcf);
What's happening here is that you select all of your checkboxes ($(".catcf")) and then change their value attribute to the value of the clicked checkbox. Remove this line and it should work as expected.

Is there a better way to multiply input values then what I have?

I'm trying to add or multiply input values to come to two total, this was working without trying to use a for loop. My intention was to match the selectors with the various iterations of i that are at the end of each string. I have a fiddle example here : https://jsfiddle.net/shiataz12/Lo1yek2g/69/
I've tried to copy and paste the function while manually inputting names for each iteration, however it doesnt quite work either as only the first two and last two checkbox do anything if clicked.
HTML :
<--- HTML SECTION --->>
// obtained from $nosday = $_POST['nosday'];
<br>
// value is normally $nosday
<br>
<input type="text" value="5" id="nosday"><br><br>
// obtained from $count = mysqli_num_rows($result);
<br>
// value is normally $count;
<br>
<input type="text" value="2" id="countrows"><br><br>
<label for="checkbox1">Standard</label>
<<----Assume checkbox --> id --> is $qri and $qri = "qr"."$i";
<input type="checkbox" name="checkbox1" class="quip" value="125" id="qr1" checked><br><br>
<label for="checkbox1">Equipped</label>
<input type="checkbox" name="checkbox1" class="quip" value="225" id="qr1"><br><br>
<label for="checkbox3">GPS</label>
<input type="checkbox" name="checkbox3" value="20" id="qr1"><br><br>
<label for="checkbox4">booster</label>
<input type="checkbox" name="checkbox4" value="20" id="qr1"><br><br>
<label for="checkbox5">One tent</label>
<input type="checkbox" name="checkbox5" class="tents" value="60" id="qr1" checked><br><br>
<label for="checkbox6">Two tents :</label>
<input type="checkbox" name="checkbox6" class="tents" value="80" id="qr1"><br><br>
// assume id="#dailytotal" where dailytotal = "dailytotal"."$i";
<br>
Daily :<span id="dailytotal1"> </span><br><br>
// Assume id = "$lengthtotal" where $lengthtotal = "lengthtotal"."$i";
<br>
Total :<span id="lengthtotal1"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot1" name="pricef1" value="">
<br>
// Hidden element for length rate to use in $_POST, shown for now
<input tyep="text" id="lengthtot" name="pricef2" value="">
<input type="text" value="2" id="countrows"><br><br>
<label for="checkbox1">Standard</label>
<input type="checkbox" name="checkbox1" class="quip" value="125" id="qr2" checked><br><br>
<label for="checkbox1">Equipped</label>
<input type="checkbox" name="checkbox1" class="quip" value="225" id="qr2"><br><br>
<label for="checkbox3">GPS</label>
<input type="checkbox" name="checkbox3" value="20" id="qr2"><br><br>
<label for="checkbox4">booster</label>
<input type="checkbox" name="checkbox4" value="20" id="qr2"><br><br>
<label for="checkbox5">One tent</label>
<input type="checkbox" name="checkbox5" class="tents" value="60" id="qr2" checked><br><br>
<label for="checkbox6">Two tents :</label>
<input type="checkbox" name="checkbox6" class="tents" value="80" id="qr2"><br><br>
Daily :<span id="dailytotal2"> </span><br><br>
Total :<span id="lengthtotal2"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot2" name="pricef1" value="">
<br>
// Hidden element for length rate to use in $_POST, shown for now
<input tyep="text" id="lengthtot2" name="pricef2" value="">
$(function() {
$("input.quip").change(function() {
$("input.quip").not(this).prop("checked", false);
});
$("input.tent").change(function() {
$("input.tent").not(this).prop("checked", false);
});
$(function() {
//get the values of the selected options
var counter = ("#countrows").val();
var i = 0;
for (i = 1; i <= counter; i++){
let v = $.map($('#qr' + i).is("checked"), function(i) {
return parseFloat($(i).val());
});
let s = v.reduce((a, b) => a + b); //sum them up to a daily total
console.log(v);
$('#dailytotal' + i).text('R' + s + '/day');
$('#lengthtotal' + i).text('R' + s * parseFloat($("#nosday").val()) + '/day');
$('#dailytot' + i).val(s);
$('#lengthtot' + i).val(s * parseFloat($("#nosday").val()));
}
});
});
The example provided assumes that there are two rows of a database and so i = 2 so id's should change to qr2 for i=2. I expected this to work by using the number of rows as a base to use a for in Jquery, limited to the number of rows so that each section can act independently, however they continue to react to the function together and do not show any values.
I thought perhaps if i could get it working for now and copy/paste code with individual id's that'd give me time to work on a better solution however it doesn't work as i'd expected. with map would it be better to declare an array prior and can i use the same id across inputs as an array? It makes calculation easier, although i guess i could use the name selector.
Hopefully someone can guide me to the correct answer, this is driving me up the wall.
Trimmed it down a little. There are other issues. The "Labels for" are suppose to refer to the id of the labelled element. The "Standard" and "Equipped" options are really radio buttons, not checkboxes, since presumably you can have one of the others. I renamed some of the classes and id's, although you may not need all of those. I am presuming that maybe you are generating the HTML dynamically and just add the value of "i" for a suffix, depending upon how many row you have. I actually just made changes to the first row and rewrote the JS to give you a total for the items form the values in the input elements for that row. Not sure exactly how you are calculating those totals, since $("#multiplier") I do not think is even in your code. You will have to look that over and see what you want, but the totals look like it is working.
<--- HTML SECTION --->>
// obtained from $nosday = $_POST['nosday'];
<br>
// value is normally $nosday
<br>
<input type="hidden" value = "1.5" id = "multiplier">
<input type="text" value="5" id="nosday"><br><br>
// obtained from $count = mysqli_num_rows($result);
<br>
// value is normally $count;
<br>
<input type="hidden" value="2" id="countrows"><br><br>
// Assume checkbox is $qri and $qri = "qr"."$i";<br>
<label for="standard1">Standard</label>
<input type="radio" name="equipment" id ="standard1" class="quip qr1" value="125" checked><br><br>
<label for="equipped1">Equipped</label>
<input type="radio" name="equipment" id ="equipped1" class="quip qr1" value="225" ><br><br>
<label for="gps1">GPS</label>
<input type="checkbox" name="gps" id ="gps1" value="20" class ="qr1"><br><br>
<label for="booster1">booster</label>
<input type="checkbox" name="booster" id ="booster1" value="20" class ="qr1"><br><br>
<label for="tents1">One tent</label>
<input type="checkbox" name="tents" id ="tents1" class="tents qr1" value="60" checked><br><br>
<label for="twotents1">Two tents :</label>
<input type="checkbox" name="twotents" id ="twotents1" class="tent qr1" value="80"><br><br>
// assume id="#dailytotal" where dailytotal = "dailytotal"."$i";
<br>
Daily :<span id="dailytotal1"> </span><br><br>
// Assume id = "$lengthtotal" where $lengthtotal = "lengthtotal"."$i";
<br>
Total :<span id="lengthtotal1"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot1" name="pricef1" value="">
<br>
The JS probably needs to be tweaked since I do not know how you are generating the HTML. As it is, it should calculate the totals for all "i" rows on load, and it would not be hard to add something to have it calculate the total for the "ith" row. That should give you something to work with.
function Calc() {
//get the values of the selected options
var counter = $("#countrows").val();
let totals = [];
for (i = 1; i <= counter; i++) {
totals[i] = 0;
$.each($('.qr' + i + ':checked'), function() {
totals[i] += parseInt($(this).val());
});
console.log(totals[i]);
$('#dailytotal' + i).text('R' + totals[i] + '/day');
$('#lengthtotal' + i).text('R' + totals[i] * parseFloat($("#multiplier").val()) + '/day');
$('#dailytot' + i).val(totals[i]);
$('#lengthtot' + i).val(totals[i] * parseFloat($("#multiplier").val()));
}
}
Calc();
$("[class*=qr]").on("change", function(e) {
e.preventDefault();
Calc();
});
"[class*=qr]" isn't the best really because *=qr is not that specific really, depending upon your markup. Also, not clear that you are using form tags anywhere either.

Unique Name For Dynamically Created Form Element

A few questions on here touch on similar subjects, but none I could find addressed my specific case.
I have a script that dynamically creates an input[type="text"] field and an input[type="radio"] field. I would like the created fields to generate unique names up to the max of 6 added fields. How can I do this with jQuery? How can i reference these newly created unique names in the PHP for my form?
jQuery:
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('
<input type="text" name="name" id="name"/>
<input type="radio" name="attend" id="attendC" value="cere" />
<input type="radio" name="attend" id="attendR" value="rece" />
<input type="radio" name="attend" id="attendB" value="both" />
<input type="radio" name="attend" id="attendN" value="neit" />
');
}
});
Actually there is so many options for that. But the best thing you will do is :
Your unique id must be timestamp you can get it like this :
var uniqueId = Date.now() | 0;
So you should generate an array for all of these what i mean is :
var insertedIds = [];
That array will keep your inserted ids and should be passed to PHP in POST operation, so your code will be :
var x = 1;
var insertedIds = [];
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
uniqueId = Date.now() | 0;
$(wrapper).append('
<input type="text" name="name" id="name"/>
<input type="radio" name="'+uniqueId+'_col0" id="attendC" value="cere" />
<input type="radio" name="'+uniqueId+'_col1" id="attendR" value="rece" />
<input type="radio" name="'+uniqueId+'_col2" id="attendB" value="both" />
<input type="radio" name="'+uniqueId+'_col3" id="attendN" value="neit" />
');
insertedIds.push(uniqueId);
}
});
If you are not using AJAX for posting variables to PHP you can use it like this :
$("yourSubmitButton").click(function(){
$("yourForm").append("<input type='hidden' name='insertedIds' value='"+JSON.stringify(insertedIds)+"'/>");
});
If you are using AJAX you can use this like this :
$.ajax({
//url,type staff etc.
data:"insertedIds="+JSON.stringify(insertedIds) // and other data
});
So that means you can fetch id_col0,id_col1... in PHP safely.
You may use the same variable x or another global one:
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('\
<input type="text" name="name_0_"' + x + 'id="name"/>\
<input type="radio" name="attend_1_"' + x + 'id="attendC" value="cere" />\
<input type="radio" name="attend_2_"' + x + 'id="attendR" value="rece" />\
<input type="radio" name="attend_3_"' + x + 'id="attendB" value="both" />\
<input type="radio" name="attend_4_"' + x + 'id="attendN" value="neit" />\
');
}
});
In this way in PHP you have only to check the first part of the name while the last part (from _number_number) is for grouping.

PHP getting value immediately after clicking on checkbox

How to get value from checkbox or radio button immediately after clicking on it and write it in textfield without using reset or submit button?
<input type="checkbox" name="age" value="21-29">21-29 <input type="text" name="yourAge" value="">
You can do like this with jQuery click function More Detail Here
<input type="checkbox" name="age" value="21-29" id="age">21-29
<input type="text" name="yourAge" value="" id="yourAge">
JQuery
$("#age").click(function () {
$("#yourAge").val($("#age").val());
});
Fiddle
#Shehary is on point but there is always room for more.
JS
<script>
var changeInput = function (val){
var input = document.getElementById("age");
input.value = val;
}
</script>
HTML
<input type="checkbox" name="age" value="21-29" onclick='changeInput(this.value);' >21-29
<input type="text" name="yourAge" value="" id="age">
Pen
I know this is old, and my code may not be great, but I like to use this.
<?php
$get= "?checked";
$checked= "";
if(isset($_GET['checked'])){
$get= "";
$checked= "checked";
}
?>
<a href="waiting_in_db.php<?=$get?>">
<input type="checkbox" <?=$checked?> >
</a>
But I prefer using CSS and links without the checkbox.

AJAX not submiting checkbox values to PHP page

I previously had the form set up with just radio input so the value was only one or the other. The client now wants it to be a check box so you could search by multiple variables at once.
I setup a test jQuery method to making sure it was at least making the correct string to be submitted with the follow:
function showValues() {
var datastr = $(".formC").find("input[type='checkbox']").serialize();
$( "#bodyA" ).text( datastr );
}
$(".localSearch").on('click', showValues);
Here is the result:
expertise%5B%5D=Ancillary&expertise%5B%5D=LargeGroup&expertise%5B%5D=IndividualPlans
I am very new to AJAX, jQuery, and PHP but this seems like the correct string to be submitting.
Now I am using jQuery AJAX to submit the values over to my PHP page.
$('.localSearch').on('click', function() { //Pulls data based on radial input
var dataStr = $(".formC").find("input[type='checkbox']").serialize();
$.ajax({
type: "POST",
datatype: "html",
data: {
expertise: dataStr
},
url: "expertise.php",
success: function (data) {
$("#bodyA").html(data);
}
});
});
Here is what the form looks like: (The form contains more but these are the only elements for expertise.php)
<label for="agent">Agent Services:</label><br />
<label for="ancillary"><input type="checkbox" value="Ancillary" name="expertise[]" id="ancillary" />Ancillary</label><br />
<label for="smallgroup"><input type="checkbox" value="SmallGroup" name="expertise[]" id="smallgroup" />Small Group</label><br />
<label for="largegroup"><input type="checkbox" value="LargeGroup" name="expertise[]" id="largegroup" />Large Group</label><br />
<label for="medicare"><input type="checkbox" value="Medicare" name="expertise[]" id="medicare" />Medicare</label><br />
<label for="longterm"><input type="checkbox" value="LongTermCare" name="expertise[]" id="longterm" />Long Term Care</label><br />
<label for="individual"><input type="checkbox" value="IndividualPlans" name="expertise[]" id="individual" />Individual Plan</label><br />
<label for="tpa"><input type="checkbox" value="TPASelfInsured" name="expertise[]" id="tpa" />TPA Self Insured</label><br />
<label for="ppaca"><input type="checkbox" value="CertifiedForPPACA" name="expertise[]" id="ppaca" />Certified for PPACA</label><br />
<label for="acaind"><input type="checkbox" value="ACA_Ind" name="expertise[]" id="acaind" />Individual Marketplace Certified</label><br />
<label for="acashop"><input type="checkbox" value="ACA_Shop" name="expertise[]" id="acashop" />Shop Marketplace Certified <br />(small group)</label><br />
<span class="localSearch">Submit</span>
I had it working when it was only dealing with one value but the string it creates seems to be the correct string. Any ideas on this? If you need anymore code or anything then just let me know!
Live site if needed
You're serializing everything in the checkbox element set. I suspect you just need the value of a given attribute (id or value). And only items that are checked. Here's an example of dumping selected checkboxes into an array:
$(".formC input:checkbox:checked").each(function(){ myArray.push($(this).val()); })
jQuery get values of checked checkboxes into array
Once you have an array, you can loop through it to put together your sql WHERE predicates.

Categories