jquery serialize not working on checkboxes - php

I have a jquery on some checkboxes and I am trying to serialize the values so I can get multiple selections in a PHP.
Here is my jquery:
<script type="text/javascript">
jQuery(document).ready(function($) {
$("input:checkbox").change(function() {
if($(this).is(':checked'))
{
var color = $(this).val().serialize;
$(".itemMain").hide();
$(".indexMain").load('indexMain.php?color='+color);
}
});
});
</script>
And here my PHP:
$color = $_GET['color'];
Before applying th serialize, everything was working fine but I couldn't have multiple selections. Now it just doesn't work at all with the serialize().
Any suggestions? Thanks!

Another solution that worked for me.
Simply specified in the name attribute of your field that you want a multiple value in other terms : an array
<form action="" method="post" id="filters_form"">
<input id="fieldNameText" value="value0" name="fieldNameText" type="text">
<input type="checkbox" name="myFieldName[]" id="myFieldName" value="value1"/>
<input type="checkbox" name="myFieldName[]" id="myFieldName" value="value2"/>
</form>
The serialize() method var dataString = $("#filters_form").serialize(); will result in
fieldNameText=value0&myFieldName%5B%5D=value1&myFieldName%5B%5D=value2
If you send those data in post with AJAX you'll get this in php :
Ajax
$.ajax({
type: "POST",
url: "yourFormURL",
data: dataString,
success: function(response) {
//do something
}
});
PHP
print_r($_POST);
/* Output :
Array ( [fieldNameText] => value0 [myFieldName] => Array ( [0] => value1 [1] => value2 ))
*/

Rough solution can be, on click event of each checkbox you can store/append its value in a variable(or a hidden input field) in a comma separated form, and pass this variable to the color query string.

Related

Get different values of same string in PHP

I have checkboxes of categories in a form. When checkbox is changed, from is submitted through ajax and get the values in PHP.
//form
foreach($somethings and $something){
<input class="input_sale_category" type="checkbox" name="category" value="something->value" />`
}
I get the form data and submit through ajax
$('.input_sale_category').click(function() {
var formData = $('#filter_sale_form').serialize();
jQuery.ajax({
type: 'GET',
url: myurl,
data: formData
success: function(response) {
console.log(response);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
In PHP, I am getting input fields as a string
category=nexus-chair-offer&category=office-desks&category=office-storage
I tried to get the inputs values of category using explode, parse_str but could not get all the values of category
parse_str($str, $output);
var_dump($output);
How can I achieve this? Regex seems an option, but I not good at regex.
Issue is in you html code,
You are using same 'name' property in all of you input tag
What this will do is only sand 1 value to backend.
change you input tag like this
foreach($somethings and $something){
<input class="input_sale_category" type="checkbox" name="category[]" value="something->value" />`
}
check this answer as well, it might help,
Get checkbox values using checkbox name using jquery
You can also get values manually and pass it in ajax request's data
var checkboxes_value = [];
$('.input_sale_category').each(function(){
//if($(this).is(":checked")) {
if(this.checked) {
checkboxes_value.push($(this).val());
}
});
//checkboxes_value will be array of checked checkboxes

php+jquery get values from serialized form with input name array

I'm developing a PHP+jQuery application. I'm quite noob with PHP.
Anyway, I'm trying to send a serialized form to a PHP page that will store data to session, via jQuery.
This is a dynamic form, where I could have many input like this:
<input type="text" name="name[]" />
And this is an example of my serialized form:
name[]=name1&name[]=name2
I've tried to get the array with $_POST["name"] from the PHP page, but it did not work.
How can I get this array from the PHP page?
Are you doing something like this???
$(function() {
$('.submit').click(function() {
var names = $('input[name="name[]"]').map(function(){
return this.value;
}).get();
$.ajax({
type: 'POST',
url: url,//this should link to your page
data: {
'name[]': names,
// other data
},
success: function() {
}
});
});
});
</script>

Send multiply input field values to php by using ajax POST

I am trying to send some dynamically created input field values to PHP to validate them and make some checks in the database in the background. I don't want to use submit form but just check the fields after click a button.
Html:
<input name="clockpick" class="input-mini timeinputfrom" data-format="hh:mm" type="text"></input>
<input name="clockpick" class="input-mini timeinputfrom" data-format="hh:mm" type="text"></input>
<button id="check" class="btn btn-primary">check</button></div>
The input boxes can be dynamically created depending how many are necessary. I get the values into jquery but don't find any possibility to send them via post to php.
Jquery:
$('#submit').on('click', function() {
var inputfield = $('input[name="clockpick"]');
$('input[name="clockpick1"]').each(function( index, element ) {
console.log( "Wert" + index + ": " + $( element ).val() );
});
$.ajax({
type: "POST",
url: "productiontimevalidate.php",
data: ????
});
How can I send the values / array to PHP?
Another way would be to add the values to an array, and convert it to json for sending.
var allClockPicks = [];
$('input[name="clockpick1"]').each(function( index, element ) {
allClockPicks.push($(element).val());
});
Then, the ajax can send data as
data: {cp: JSON.stringify(allClockPicks)}
On the php side, you can json_decode them as below:
$cpArray = json_decode($_POST['cp'], true);
If your elements are inside <form class="my-form"> [elements...] </form>
You can use this short version:
<script>
$.post('/my/path/app.php', $('.my-form').serialize(), function(r) {
console.log(r);
},'json'); // parse response as JSON
</script>
app.php
<?php
echo json_encode(array('success' => true, 'post', $_POST));
?>

post associative array using jquery ajax

I am creating form using cakephp form. It is creating form something like this:
<form name='license' action='/some/action' action='POST'>
<input type="text" id="license0Number" name="data[license][0][number]">
<input type="text" id="license0Year" name="data[license][0][year]">
<input type="text" id="license1Number" name="data[license][1][number]">
<input type="text" id="license1Year" name="data[license][1][year]">
</form>
It is working fine when submitting form in normal form and getting data something like this:
$data = array( 'license' => array( '0' => array( 'number'=>'123', 'year'=>'2000' ),
'1' => array( 'number'=>'321', 'year'=>'2003' )
);
But when I submit same form using jQuery $.ajax() function and posting data with serialize() function. I am getting data something like this on server side.
Array
(
[data%5Blicense%5D%5B0%5D%5Bnumber%5D] => 123
[data%5Blicense%5D%5B0%5D%5Byear%5D] => 2000
[data%5Blicense%5D%5B1%5D%5Bnumber%5D] => 321
[data%5Blicense%5D%5B1%5D%5Byear%5D] => 2003
)
How can I get form data in form of associate arrays when usign jQuery $.ajax() function ?
EDIT:
$('#license_form').live( 'submit', function( event ) {
var action = '/some/action';
var data = $(this).serialize();
$.ajax({
type: "POST",
url: action,
data: data, // form data
success: function( result ) { alert( result ); },
error: function() { alert('error'); }
});
event.preventDefault();
});
Thanks
No need to user Low-Level ajax, use $.post shorthand instead.
Try this:
$(function(){
$("#submit").click(function(){
//Since you're talking about POST
$.post('path_to_php_script.php', {
"license0Number" : $("#license0Number").val(),
"license0Year" : $("#license0Year").val(),
"license1Number" : $("#license1Number").val(),
"license1Year" : $("#license1Year").val()
}, function(respond){
//Respond from PHP
//Maybe replace some div with the server respond?
$("#some_div").html(respond); //optional
});
});
});
You asked for POST ASSOC ARRAY Using jquery,
so you'll get that,
In your php script:
<?php
print_r($_POST); //will print what you want
You can use .serializeArray() and then manually encode the values:
var values = form.serializeArray();
for (var i = 0; i < values.length; i++)
values[i] = encodeURIComponent(values[i].value);
values = values.join('&');
One of possible solutions is to parse key strings on server side and build associated array in PHP...
I think jQuery.param is what you're looking for.
serializeArray(); is what you are looking for

Fetch input value from certain class and send with jquery

<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});

Categories