I'm working on a project where I have retrieved the name and values from selected checkboxes using jquery/ajax. I have set the names and values of the checkboxes using php on the main page. I would like to extract the names using $_POST in a seperate php script so that I can use these names to delete projects out of MySQL.
$("#deleteproject").click(function () {
var names = [];
$('#projectcheckbox input:checked').each(function() {
//all checkbox names are put in array
names.push({name: $(this).attr('name'), value: $(this).val()});
});
alert($.param(names));
return false;
});
The above alert($.param) returns the selected checkbox in a val1.name and val1.value format.
//run delete_project.php to erase projects from database
$.ajax({
type: "post",
url:"delete_project.php",
data: names,
cache: false,
success:function() {
alert(names + ' deleted')
}
});
I have searched for an answer the last couples days and I would appreciate some help figuring this out.
I would prefer using html part in this way first, cos it's more flexible and easy in your case;
<input type="checkbox" name="projectcheckbox[]" value="foo_project" />
<input type="checkbox" name="projectcheckbox[]" value="bar_project" />
...
Or printing out the db results at first;
foreach ($projects as $project) {
print '<input type="checkbox" name="projectcheckbox[]" value="'.$project.'" />';
}
Then calling jQuery.serialize will give you a data stuff like;
projectcheckbox[]=foo_project&projectcheckbox[]=bar_project ...
PHP part (after post);
foreach ((array) $_POST['projectcheckbox'] as $pro) {
// do something with $pro = foo_project or bar_project etc...
// THIS PART FOR SECURITY GUYS :)
// BUT! DO NOT FORGET TO SECURE YOUR DATA ($pro) HERE!!!!!
}
Related
Pretty comfortable with PHP but fighting with jQuery.
I have a bootstrap modal that is used for editing a project and I'm using AJAX to populate the fields when an edit button is clicked. This works great but a project can be in multiple departments (checkboxes in the modal)
This is how I'm populating the modal:
$.ajax({
url: 'project_tasks.php?task=select_project&pjct_id=' + id,
method: 'GET',
dataType: 'json'
}).success(function(response) {
// Populate the form fields with the data returned from server
$('#edit_project')
.find('[name="project_id"]').val(response.project_id).end()
.find('[name="project_title"]').val(response.project_title).end()
.find('[name="project_bgcolor"]').val(response.project_bgcolor).end()
.find('[name="project_desc"]').val(response.project_desc).end()
.find(':checkbox[name^="department"]').each(function () {
if($(this).val() == response.dpmt_id) {
console.log("depart: " + response.dpmt_id);
$(this).prop('checked', true);
}
});
});
And the PHP is (not escaping yet but will do):
$pjct_id = $_GET['pjct_id'];
$pjct = Projects::find_by_id($pjct_id);
$dpmts = Projects_departments::find_all_by_pjct_id($pjct_id);
foreach ($dpmts as $dpmt) {
$response_array['dpmt'] = $dpmt->department_id;
}
$response_array['project_id'] .= $pjct->id;
$response_array['project_title'] .= $pjct->project_title;
$response_array['project_bgcolor'] .= $pjct->project_bgcolor;
$response_array['project_desc'] .= $pjct->project_desc;
echo json_encode($response_array);
Obviously I know that 'dpmt' is being overwritten each time so I only get the json dpmt : 1 rather than each departments ID but I would like to achieve something like dpmt: 1, dpmt: 2, dpmt: 3 and then loop through that to tick the checkbox.
Hopefully I've explained myself well enough (The wife is rushing me out)
Thanks in advance.
The PHP: return an array of ids instead of an integer/string.
...
foreach ($dpmts as $dpmt) {
$response_array['dpmt'][] = $dpmt->department_id;
}
...
The Javascript: use a combined selector, so you don't have to loop every checkbox. Use the loop only on the dpmt_ids returned by the PHP.
$('#edit_project')
.find('[name="project_id"]').val(response.project_id).end()
.find('[name="project_title"]').val(response.project_title).end()
.find('[name="project_bgcolor"]').val(response.project_bgcolor).end()
.find('[name="project_desc"]').val(response.project_desc).end()
;
for (i=0; i< response.dpmt_id.length; ++i) {
$('#edit_project').find(':checkbox[name="department[]"][value="'+response.dpmt_id[i]+'"]').prop('checked',true);
}
I am doing a project where I need to make sure that my form instantly autofills 2 textboxes based on input from the first textbox. Right now I am just testing. I can't use database entries to populate my form, only PHP variables. My logic needs to be like this: user types in a specific 10 digit number into a textbox on my form (specified in a PHP file), then the other two textboxes get autofilled with specific entries after an AJAX call to that PHP file. This is definitely one of the more complex tasks that I've encountered so far (noob). My code doesn't work, so I would really appreciate any help with getting it to function properly.
HTML is like this:
<!--load scripts, libraries, etc.-->
<form method="GET">
Number: <input type="text" name="num" id="num">
First Name: <input type="text" name="first" id="first">
Last Name: <input tupe="text" name"last" id="last">
</form>
PHP:
<?php
$num=$_GET["num"];
$first=$_GET["first"];
$last=$_GET["last"];
if ($num=="0123456789")
{
$fill = array(
'firstname' => $first["John"],
'lastname' => $last["Smith"],
);
echo json_encode($fill);
}
else
{
echo "Bad input.";
}
?>
jQuery:
$(document).ready(function () {
$("#num").keyup(function () {
var el = $(this);
if (el.val().length === 10) {
$.ajax({
url: "http://localhost/test.php",
cache: false,
dataType: "json",
type: "GET",
data: "npi=" + el.val(),
success: function (result) {
$("#first").val(result.firstname);
$("#last").val(result.lastname);
}
});
}
});
});
in ajax change like this it'll be easy to understand
type: "GET",
data:{num: el.val()},//if multiple then like this->data:{attr:val1,attr2:val2,...},
in php
<?php
$first["John"]="john";//i hope you have these two values defined
$last["Smith"]="smith";
$num=$_GET["num"];
if ($num=="0123456789")
{
$fill = array(
'firstname' => $first["John"],
'lastname' => $last["Smith"],
);
echo json_encode($fill);
}
else
{
echo "Bad input.";
}
?>
explanation
see the process is like
first the number will go to php with the help of ajax(through the
ajax request)
type: "GET",,
data: {num: el.val()},
so as we are sending the number as GET request to php, in php we get this number with $_GET['num'] so now this value will have 0123456789 value in it.
now we are checking with if condition in php
if ($num=="0123456789")
{
//here we need to send the firstname and lastname values BACK TO THE AJAX REQUEST
so we need to have these first and last names here in php defined somewhere manually or get it from database(if you have these first,last names in DB)
echo json_encode($fill);
}
I am experiencing some issues with a form I am making. I have the code to post a form to my PHP script that is meant to handle the data with this code:
<script type="text/javascript">
$(document).ready(function()
{
$("#submit").click(function()
{
var q1 = $("#q1").val();
var q2 = $("#q2").val();
var answers = "page=1&q1="+q1+"&q2="+q2;
$.ajax({
type:'POST',
url:'add.php',
data:answers,
success:function(response)
{
$("#answers").html(response);
}
});
});
});
</script>
This form is then received in my PHP script like this:
$page = $_POST['page'];
$q1 = $_POST['q1'];
$q2 = $_POST['q2'];
echo "Page: " .$page . "<br/>Question 1: " . $q1 . "<br/>Question 2: " . $q2;
The issue of it all is that I want this form to be able to handle X amount of inputs and also handle input I do not know the name of. Like I can get 5 textboxes, or 2 textboxes + a string of radiobuttons and so on. Is there a way to collect ALL $_POST data and then explode it or something similar so I can get it ready for the database? I wish to recover all question id's(values) and all answer values(could be a string or an int representing a radiobutton id).
You can iterate through all POST and GET request parameters by simply treating POST and GET as an array. For an example:
print_r($_POST);
Alternatively:
foreach ($_POST as $key => $value) {
echo $key." = ".$value."<br>";
}
If you want to handle a variating amount of input fields, you can define an incrementing naming convention and use loops to gather them all to an array.
with print_r($_POST); you can look at all values.
or something like this:
foreach ( $_POST AS $key => $value) {
echo $key." => ".$value."<br>";
}
First: Let jQuery build your data string, your current method requires you to know each field in advance and can't handle data with special characters in it.
url:'add.php',
data: $('#myForm').serialize(),
success:function(response)
Second: Name your fields using the PHP multiple fields with the same name convention:
<input type="radio" name="answer[1]" value="foo">
<input type="radio" name="answer[1]" value="bar">
You can then access them as:
$_POST['answer'][]
It is an array, so you can get the '1' and the 'foo' or the 'bar' in a loop.
I am working on a check box based filter operation for a website.This has multiple checkboxes which filter a list of records on different parameters.Similar to what is done here.Now I have managed to achieve some success,and I have filtered the records based on first set of checkboxes.Here is the js function for it.
HTML:
<input type="checkbox" id="checkbox1" class="checkbox1" value="<?php echo $suburb['suburb_name']?>" name="Suburb_check[]" onClick="changeResults();" onChange="" >
Javascript:
function changeResults(){
var data = { 'venue[]' : []};
$("input[name=Suburb_check[]]:checked").each(function() { var chck1 = $(this).val();
data['venue[]'].push($(this).val());
dataString =data['venue[]'.toString()].toString();
});
$.ajax({
type : 'POST',
url : 'process.php',
data : "dataString="+dataString,
success : function(data){
$('#project_section').html(data);
}
});
}
What this does is filters the records + loads the second set of check boxes.1st set check box)=>for Regions and 2nd is =>for Localities
I have created an array to pass the check box values and then converted it to a string(.toString) and passed to the .php file.
Similarly I created a function for 2nd set of checkboxes.
HTML
<input type="checkbox" onClick="changeLocality();" id="localityCheck" value="<?php echo $locality['locality_name'];?>" name="Locality_check[]">
JS
function changeLocality(){
var dataLocality = {'locality[]' : []};
$("input[name=Locality_check[]]:checked").each(function() {
var chcklocal = $(this).val();
dataLocality['locality[]'].push($(this).val());
localityString =dataLocality['locality[]'.toString()].toString();
});
$.ajax({
type : 'POST',
url : 'processLocality.php',
data : "localityString="+localityString,
success : function(dataLocality){
$('#project_section').html(dataLocality); // replace the contents coming from php file
}
});
}
Pass the values to a php file but when I try to get them using $_POST,the strings I get mixed into each other i.e the region values go into locality string and vice-versa(Tried this using array with same result so switched to strings).
I am not able to fix this.Why is this happening
This are the php files i post values to.
processLocality.php
<?php session_start();
include_once("includes/classes/db_connect.php");
include_once("pagination/paginator.class.php");
$pages = new Paginator();
$regions = "'".$_POST['dataString']."'";
echo $regions;
$arr = explode(",",$regions);
$getFormatedSuburb = implode("','",$arr);
$locality = "'".$_POST['localityString']."'";
echo $locality;
$arrLocal = explode(",",$locality);
$getFormatedLocality = implode("','",$arrLocal);
//Here I get the strings mixed with each other!!
?>
I have added some expression to the string for passing it to the IN clause of SQL query in the needed format.
Now the strings I get contains values from both regions and localities.I want both separately as they are two different parameters for filtering records
Pune East,
Pune West, //1 and 2 are regions
Aundh,
Kalyaninagar //3 and 4 are localities
Also,I would like to know is my approach correct.Any better way of achieving this?
Any help appreciated.
Thanks
Try changing your selectors. Instead of this:
$("input[name=Suburb_check[]]:checked")
....
$("input[name=Locality_check[]]:checked")
Do this:
$("input[name=Suburb_check]:checked")
....
$("input[name=Locality_check]:checked")
Also the markup has to be in the form:
<input type="checkbox" name="Suburb_check">
With the same name for each checkbox group. The name can not contain "[]"
I HAVE modified my code, i used firebug console.log to detect weather the the php gets the array passed or not. and firebug displays this - rescheck[]=2&rescheck=1&rescheck=3
I think php gets the array if THATS what an array in php supposed to be like.
SO guys, if thats correct how to insert that array in database? or how to loop it? the foreach loop ive made didnt work.
JQUERY CODE:
$('#res-button').click(function (){
var room_id=$('[name=rescheck[]]:checked').serialize().replace(/%5B%5D/g,'[]');
alert(room_id);
$.ajax({
type: "POST",
url: "reservation-valid.php",
data: {name_r:name_r, email_r:email_r,contact_r:contact_r,prop_id:p_id,cvalue:room_id},
success: function(data) {
console.log(data);
}
});
});
<input type="checkbox" name="rescheck[]" value="<?php echo $roomid; ?>" />
PHP CODE:
$c_array=$_POST['cvalue'];
echo $c_array;
//foreach($c_array as $ch)
//{
//$sql=mysql_query("INSERT INTO reservation VALUES('','$prop_id','$ch','$name_r','$contact_r','$email_r','')");
//}
I think I managed my jquery code to be right, but I don't know how to fetch that with PHP.
room_id is an array, so if you want to get the value for each, you need to get all value together first.
var room_id_string = '';
for(i=0;i<room_id.length;i++){
room_id_string += room_id.eq(i).val() + ',';
}
your below code will only pass Array jquery object of [name=rescheck[]]:checked to room_id
Instead of this you will have to create a array and push values in it like this
var room_id = Array();
$('[name=rescheck[]]:checked').each(function(){
room_id.push($(this).val());
});
In jQuery it might be easier for you to just use the serialize function to get all the form data. jQuery passes the form to the server so you don't have to worry about getting all the values. If you use it in conjunction with the validate plugin you might find it a little easier!
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This is what I do ibn my site for saving to a db a list of checkboxes with jquery and ajax call. It make an array and pass it to the ajax call and the php script handle the array.
If you get any error here you should debug the js array with firebug for be sure that is formed correctly.
js script:
var $checkBox = $('[name=rescheck[]]:checked');
$checkBox.each(function() {
if ($(this).is(":checked")){
valuesCheck[this.value] = 1;
}else{
valuesCheck[this.value] = 0;
}
and the PHP script:
$checkTab = $_POST['cvalue'];
foreach ($checkTab as $idChkTab => $checkedOrNot){
if ($checkedOrNot== "0"){
//do something if isn't checked
}