Send multiply input field values to php by using ajax POST - php

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

Related

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>

Multiple submit buttons on one page but distinguishable (jquery)

I am trying to write a code that 'stores items for later' - a button that has url of the item as hidden input, on submit it calls a php script that does the storage in a db. I am more into php, very little knowledge of anything object-oriented, but I need to use jquery to call the php script without moving over there
The problem is how to assign the x and y variables when I have multiple forms on one page
I was only able to write the following
$("form").bind('submit',function(e){
e.preventDefault();
var x = $("input[type=hidden][name=hidden_url]").val();
var y = $("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php?url='+x+'&tit='+y,
success: function() {
alert( "Stored!");
location.reload();
}
});
});
It works fine if you have something like...
<form method="post" action="#">
<input type="hidden" id="hidden_url" name="hidden_url" value="<?php echo $sch_link; ?>"/>
<input type="hidden" id="hidden_title" name="hidden_title" value="<?php echo $sch_tit; ?>"/>
<input type="submit" id="send-btn" class="store" value="Store" />
</form>
..once on the page, I've got about 50 of them.
These are generated via for-loop I suppose I could use $i as an identifier then but how do I tell jquery to assign the vars only of the form/submit that was actually clicked?
You'll have to scope finding the hidden fields to look within the current form only. In an event handler, this will refer to the form that was being submitted. This will only find inputs matching the given selector within that form.
$("form").bind('submit',function(e){
e.preventDefault();
var x = $(this).find("input[type=hidden][name=hidden_url]").val();
var y = $(this).find("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php',
data: {
url: x,
tit: y
},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
As #Musa said, it's also better to supply a data key to the $.ajax call to pass your field values.
Inside your form submit handler, you have access to the form element through the this variable. You can use this to give your selector some context when searching for the appropriate inputs to pass through to your AJAX data.
This is how:
$("form").bind('submit',function(e) {
e.preventDefault();
// good practice to store your $(this) object
var $this = $(this);
// you don't need to make your selector any more specific than it needs to be
var x = $this.find('input[name=hidden_url]').val();
var y = $this.find('input[name=hidden_title]').val();
$.ajax({
url: 'save_storage.php',
data: {url:x, tit: y},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
Also, IDs need to be unique per page so remove your id attribute from your inputs.

jquery serialize not working on checkboxes

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.

Reading serialized jquery data in PHP (multiple checkboxes)

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

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