getting data by jQuery ajax PHP and Database - php

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.

Related

Placing data in MySQL database from form fields created on the fly

I have a form that allows members to click a (+) sign, and it will put another form field there. They can do this to basically without limit.
The problem I have is if they do it, let's say, 3 times and fill out all 3, when I get the data to save it, it's placing the first field in the database and not the others.
Here is my code:
Here is the JavaScript that makes the div show as they push the (+) sign.
<script type="text/javascript">
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
document.getElementById('newlink').appendChild(div1);
}
</script>
<style>
.feed {padding: 5px 0}
</style>
This is part of the form that does the above...
<td width="50%" valign="top">
<div id="newlink">
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
<hr>
<p id="addnew">
+ Click Here To Add Another Biz/Traffic/Tools Site
</p>
<div id="newlinktpl" style="display:none">
<hr>
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
This is the part of the PHP code that would save it...
$i=0;
$linkname = $_POST["recname"][0];
while($linkname != ""){
$linkname = $_POST["recname"][$i];
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
$linkname = $res->real_escape_string($linkname);
$linkurl = $res->real_escape_string($linkurl);
$linktype = $res->real_escape_string($linktype);
$result299 = mysqli_query($res, "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')");
$i++;
}
It's all working except that is does not store all the data in the database (only the first one saves). That's the part I need help with please.
Please explain what I have done wrong and how to get it to store all the fields in the database, no matter how many the user creates and fills out.
I tested your code and it works fine so far if I use it like this:
$i=0;
$linkname = $_POST[recname][0];
while($linkname != ""){
$linkname = $_POST[recname][$i];
$linkurl = $_POST[reclink][$i];
$linktype = $_POST[rectype][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
There's no information about the $res object you're calling real_escape_string() on, so I'll just skip that for now. There are a couple of weaknesses in the code though:
You are referencing the post keys with barenames instead of strings.
PHP will gracefully assume you meant it as a string, but it will trigger a notice like Use of undefined constant recname - assumed 'recname'. Enclose them in quotes to make it clean.
Your use of the loop will result in an empty element inserted in the database every time.
You set the new linkname AFTER checking if $linkname is empty, but the variable contains the name of the last iteration. Instead, do something like this:
$i=0;
while($linkname = $_POST["recname"][$i]){
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
Your code only allows for one radio button to be checked at a time
You cannot use rectype[] as a name for radio buttons, as an equal name forms a group of radio buttons out of all the elements. You need to name them like this:
<input type="radio" name="rectype[0]" value="1"> Business Opp<br />
<input type="radio" name="rectype[0]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[0]" value="3"> Tools Site<br />
<input type="radio" name="rectype[1]" value="1"> Business Opp<br />
<input type="radio" name="rectype[1]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[1]" value="3"> Tools Site<br />
and so on. You can do that programatically in your javascript code like this:
<script type="text/javascript">
var counter = 1;
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
var inputs = div1.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
if (inputs[i].type == "radio") {
inputs[i].name="rectype[" + counter + "]";
}
}
counter++;
document.getElementById('newlink').appendChild(div1);
}
</script>
That said, I don't see why it should only save one item, unless you have a key constraint hitting or something else we cannot assume from the piece of code you shared.

How to add checkbox id and insert in textarea?

I'm Prasath and I'm new to AJAX. I am working on seat layout project, I find difficult to get seat fare and seat number at same time. Kindly some one help me to solve my problem. Here is my code
<div id="mydiv">
<input type="checkbox" name="seat1" id="A1" value="250" />
<br />
<input type="checkbox" name="seat2" id="A2" value="250" />
<br />
<input type="checkbox" name="seat3" id="A3" value="300" />
<br />
<input type="checkbox" name="seat4" id="SL1" value="250" />
<br />
<input type="checkbox" name="seat5 " id="SL2"
value="250" />
<br />
<input type="checkbox" name="seat6" id="SL3" value="300" />
<br />
<input type="checkbox" name="seat7 " id="SL4" value="300" />
<textarea id="seats"></textarea>
<textarea id="total_amount"></textarea>
</div>
I want result as
if checkbox "Seatl, seat3 and seat7" are checked I want result as
<textarea id="seats">A1,A3,SL4</textarea>
<textarea id="total_amount">750</textarea>
Kindly help me to solve this.
Thanks in advance.
You can do it just with plain javascript (no need of jQuery):
function myAudis(){
var inputs = document.getElementById("mydiv").getElementsByTagName("input");
var seats=[], total_amount=0, c=0;
for(var i=0;i<inputs.length;i++){
if(inputs[i].type!="checkbox"){continue;}
if(inputs[i].checked){seats[c++]=inputs[i].id; total_amount+=parseInt(inputs[i].value);}
}
document.getElementById("seats").value=seats;
document.getElementById("total_amount").value=total_amount;
}
You can call it like this:
<button type="button" onclick="myAudis()">Calculate</button>
Hope it helps..
$(document).ready(function(e) {
var ids = "";
$(':checkbox').bind('change',function(){
var th = $(this), id = th.attr('id');
//alert(th);
if(th.is(':checked')){
ids = ids+id+",";
$('#seats').val(ids);
}
else
{
ids = ids.replace(id+",","");
$('#seats').val(ids);
}
});
});
First add a common class for the checkbox like seatsNos
Add this in your on submit function or if event want it in every checkbox click add add check checked event
var total = 0;
var textarea = '';
$('.seatsNos:checked').each(function () {
var e = $(this);
var textarea = ',' + e.attr('id');
total = total + e.val();
});
$('#seats').val(textarea );
Note : Jquery needed

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

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

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.

Checkbox onclick uncheck other checkboxes

I have 6 checkboxes, one for each business day and one that says 'all'.
What i want to be able to do is uncheck all the other boxes if someone clicks the 'all' checkbox if that makes sense.
For example, if someone has clicked monday and wednesday ... then they come in and click the 'all' checkbox, then the monday and wednesday checkbox should uncheck.
Cheers,
This is not you want, but seems to be more sensible.
HTML
<input type="checkbox" id="chkAll" />
<br />
<input type="checkbox" id="chkMonday" class="child" />
<input type="checkbox" id="chkTuesday" class="child" />
<input type="checkbox" id="chkWednesday" class="child" />
<input type="checkbox" id="chkThursday" class="child" />
<input type="checkbox" id="chkFriday" class="child" />
<input type="checkbox" id="chkSaturday" class="child" />
<input type="checkbox" id="chkSunday" class="child" />
jQUery
$(function(){
$("#chkAll").change(function(){
if (this.checked) {
$("input:checkbox.child").attr("checked", "checked");
}
else {
$("input:checkbox.child").removeAttr("checked");
}
});
});
See a working demo
See an updated version which handles change in the child checkboxes also.
jquery and some code like this should do it.
$('#all-id').change(function(){
if($('#all-id').is(':checked')){
if($('#monday-id').is(':checked')){
$('#monday-id').attr('checked', false);
} else {
$('#monday-id').attr('checked', true);
}
// etc
}
});
After you might want to put all the ids in an array and setup a loop or play with the structure of your document to be able to easily loop on all of those checkboxes

Categories