Reading serialized jquery data in PHP (multiple checkboxes) - php

JQUERY:
$(document).ready(function(){
$('form').submit(function(){
var content = $(this).serialize();
//alert(content);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/test/generate',
timeout: 15000,
data:{ content: content },
success: function(data){
$('.box').html(data).fadeIn(1000);
},
error: function(){
$('.box').html('error').fadeIn(1000);
}
});
return false;
});
});
HTML:
<form>
<input type="checkbox" value="first" name="opts[]">
<input type="checkbox" value="second" name="opts[]">
<input type="checkbox" value="third" name="opts[]">
<input type="submit">
</form>
How do i process (or read) multiple checked checkbox's value in PHP? I tried doing $_POST['content'] to grab the serialized data but no luck.

Replace:
data:{ content: content } // <!-- you are prefixing with content which is wrong
with:
data: content
Now in your PHP script you can use $_POST['opts'] which normally should return an array.

Try
echo $_POST['opts'][0]. "<br />";
echo $_POST['opts'][1]. "<br />";
echo $_POST['opts'][2]. "<br />";
You post an array to the Server and it is available in the post variable 'opts'. Remember: Unchecked boxes dont get posted.

The chosen answer still didn't work for me, but here is what did:
var checkedBoxesArr = new Array();
$("input[name='checkedBoxes']:checked").each(function() {
checkedBoxesArr.push($(this).val());
});
var checkedBoxesStr = checkedBoxesArr.toString();
var dataString = $("#" + formID).serialize() +
'&checkedBoxesStr=' + checkedBoxesStr;
[The above code goes in your javascript, before serializing the form data]
First, cycle through the checked boxes and put them into an array.
Next, convert the array to a string.
Last, append them to the serialized form data manually - this way you can reference the string in your PHP alongside the rest of the serialized data.
This answer came partly from this post: Send multiple checkbox data to PHP via jQuery ajax()

there are an Error in your code :
The url should be url: 'http://localhost/test/generate.php' with the extension name

Related

How to pass ajax sucess result to another php page

In my code below I want display $("#searchresults").html(data) this result to other page.
$.ajax({
type: "POST",
url: base_url + 'front/searchresult',
data: data,
success: function(data) {
alert("test");
var val = $("#searchresults").html(data);
window.location.assign("<?php echo base_url()?>front/search/" + val);
}
});
what exactly is in the data variable you receive from your post? is it a json object? is it plain text?
if it is html, I think you should consider placing the result in a div on the current page, and hide items you don't want to see after searching
relocating after ajax requests is not the way to go. Is it an option in your case, to use a form and change the action attribute of the form to your new location?
<form action="front/search/">
<input type="text" name="data">
</form>

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));
?>

How do I get jquery variable value to be read by PHP $_POST?

I'm able to successfully get all the values from a multi-select form into one nice delimited variable, but I can't figure out how to get the value to my PHP script? How do I get the 'output' value read by PHP's $_POST array? Any help would. Be. Awesome. :D
<script type="text/javascript">
function ValidatePageForm() {
var result = new Array();
$("#select-to option").each(function() {
result.push($(this).val());
});
var output = result.join("-");
alert(output);
}
</script>
suppose you have a form
<form>
<input type="hidden" name="output" id="output">
....
</form>
send javascript variable to HTML
var output = result.join("-");
$('#output').val(output);
and when you submit the form
you wil get data in $_POST['output']
I believe your looking for something like echo $_POST['value']; ??
You can use Jquery serialize to post all the data of the form including multi select
var submit_data = $('#output').serialize();
var post_data = submit_data ;
$.ajax({
type: "POST",
url: 'submitform.php',
data: post_data,
success: function(data)
{
}
});
You will get all the value in $_POST on submitform.php
Let me know it works for you

Serializing form in jquery and passing it into php

I have been trying for the last couple of days to serialize a form in jquery and pass it to php. For some reason it just doesn't work... Question, What steps do you take to serialize a form in Jquery... I get the id of the form pass it into $('#fomrID').serialize()...
And it still doesn't work. When I debugg with firebug All I get is an empty string... Do you use the name or the Id of the form. Do you use e.disableDefalut or whatever that is? I can't figure out why I can't serialize my form please help
$('#profilepicbutton').change(function(){
alert("Boy I hate PHP");
var formElement = $('#profilepicinput').attr('value');
dataString = $("#registerpt3").serialize();
$.ajax({
type: "POST",
url: "register3.php",
data: dataString, //"profilePic="+formElement,
success: function(data){
alert( "Data Saved: " + data );
$.ajax({
type: "POST",
url: "retrievePic.php",
data: "",
success: function(data){
alert(data);
var image = new Image();
$(image).load(function(){
console.log("we have uploaded this image");
}).attr('src', 'images/');
alert("");
},
error: function(msg){
alert("");
}
});
},
error:function(msq){
alert("" + msg);
}
}
);
});
<form id="registerpt3" name="registerpt3" enctype="multipart/form-data" action="register3.php" onSubmit="" method="post">
<input name="profilepicinput" type="file" id="profilepicbutton" />
</form>
According to http://api.jquery.com/serialize
For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Also, simply calling serialize won't actually upload the picture for you. If you want to do an asynchronous picture upload (or any file for that matter) I'd suggest looking into something like Uploadify: http://www.uploadify.com/

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