I've a form with data repeated:
<form action="" method="post" id="myForm">
<?php foreach ($array as $value) { ?>
<input type="text" name="myInput[]" id="myInput" value="<?php $value->data1 ?>"/>
<textarea name="myTextArea[]" id="myTextArea"><?php $value->data2 ?></textarea>
<?php } ?>
save
</form>
I try to save values with ajax with this script:
jQuery(function(){
jQuery("#submit").click(function(e){
e.preventDefault();
var formData = {
'myInput' : jQuery('input[name=myInput]').val(),
'myTextArea' : jQuery("textarea#myTextArea").val()
};
jQuery.ajax({
url : 'someUrl',
type : 'POST',
data : formData,
dataType: 'json',
encode : true,
success: function(response){
if (response.success==true) {
}
else {
}
}
});
});
});
When data is not repeated (no array values) i've no problem, but in this case something goes wrong. Anyone could help me?
As suggested, use
data: $(this).serialize()
in your jQuery submit function. Leave the square brackets in the input names intact. In your PHP, you will be able to access your data like this:
$myInputs = $_POST['myInput'];
$myTextAreas = $_POST['myTextArea'];
Both variables will be arrays of values retrieved from the form. More info on PHP arrays is available here.
EDIT: If you need the value of $myInputs as a string separated by commas (e.g., "value1, value2, value3..." instead of array with "value1" etc.), you could do the following right after:
$myInputs = implode(', ', $myInputs); // this will convert the array to a string
Try this jQuery code :
jQuery(function(){
jQuery("#submit").click(function(e){
e.preventDefault();
var formData = $("#myForm").serialize();
jQuery.ajax({
url : 'someUrl',
type : 'POST',
data : formData,
dataType: 'json',
encode : true,
success: function(response){
if (response.success==true) {
}
else {
}
}
});
});
});
Please refer this answer to add multiple textbox values in database : Adding multiple textbox entry to a mysql database
Related
I'm pretty new to Jquery and PHP and I'm trying to get the values of checkboxes in a filter form and sending to php. I'd like to figure out how to store the PHP variable as an array of all the boxes checked.
My form:
<input type="checkbox" name="applications[]" <?php echo $selected['applications/food-applications/sugar-reduction/'] ?> id="sugar-reduction" value="applications/food-applications/sugar-reduction/" onchange="$('#app_filter').submit();" >
<input type="checkbox" name="applications[]" <?php echo $selected['applications/food-applications/binding-systems/'] ?> id="binding-systems" value="applications/food-applications/binding-systems/" onchange="$('#app_filter').submit();" >
<input type="checkbox" name="applications[]" <?php echo $selected['applications/food-applications/shelf-life-extension/'] ?> id="shelf-life-extension" value="applications/food-applications/shelf-life-extension/" onchange="$('#app_filter').submit();" >
Script:
$("#app_filter").submit(function() {
event.preventDefault();
var checkbox_value = "";
$(":checked").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
checkbox_value += $(this).val() + ", ";
}
});
console.log(checkbox_value);
return false;
});
With all three boxes checked it is successfully showing the values in the console like this:
applications/food-applications/sugar-reduction/, applications/food-applications/binding-systems/, applications/food-applications/shelf-life-extension/,
I'd like to store the values in an array and in a PHP variable. Ideally like this...
array(applications/food-applications/sugar-reduction/, applications/food-applications/binding-systems/, applications/food-applications/shelf-life-extension/,)
Is that possible? Any guidance would be greatly appreciated!
Use $(this).serialize() to encode all the form inputs. You can then access them in PHP just as you would with normal form submission.
$("#app_filter").submit(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "post",
data: $(this).serialize(),
success: function(response) {
console.log(response);
}
}
});
});
In PHP, $_POST['applications'] will be an array of all the selected values.
I am trying to pass an input field which has its values to be in an array with some other input fields into PHP using jquery-Ajax formData, everything seems to work fine except that I am having problems with successfully passing the array values and I have tried a whole lot which without evident success.
firstly i tried SerialiseArray() method. Here is my code below
<form>
//other input field below...
.
.
.
//this is the code to include my array which is in _categories-list.php
<div class="form-group">
<label for="artist">Select Categories </label>
<?php include('../_categories-list.php') ?>
</div> </form>
var Category = $('#categoriesList').serializeArray();
$.each( Category,function(i,field){
formData.append('categoriesList', field.value + "");
});
$('.msg').text('Uploading in progress...');
ajaxcall = $.ajax({
url: 'page-videoFunc.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',});
This particular method I used only sends one value of the chosen options in the array. example:
//output: let's say the person chooses blues, hip-hop
hip-hop //will be the only value sent
I also tried another method similar
<form>
//other input field below...
.
.
.
//this is the code to include my array which is in _categories-list.php
<div class="form-group">
<label for="artist">Select Categories </label>
<?php include('../_categories-list.php') ?>
</div> </form>
var Category = $('#categoriesList').serializeArray();
formData.append('categoriesList', Category);//note that code changes here from the above method used
$('.msg').text('Uploading in progress...');
ajaxcall = $.ajax({
url: 'page-videoFunc.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',});
This one sends all the values of the array that is chosen but sends but as an object example:
//output
[object object] [object object]
And lastly, I tried this: serialize();
<form>
//other input field below...
.
.
.
//this is the code to include my array which is in _categories-list.php
<div class="form-group">
<label for="artist">Select Categories </label>
<?php include('../_categories-list.php') ?>
</div> </form>
var Category = $('#categoriesList').serialize(); //Note i used just serialize() here
formData.append('categoriesList', Category);
$('.msg').text('Uploading in progress...');
ajaxcall = $.ajax({
url: 'page-videoFunc.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',});
Which partially works and sends all the values but in a format i seem not to get a way to get the values out, example:
//output
categoriesList%5B%5D=blues&categoriesList%5B%5D=hip-hop
I don't know how to get only the values from the query strings in this method so I could put it into the database
Please help me provide a solution to any of the above method I am using, I have worked on this nearly 42 hours and its slowing down my project
call the ajax like.
var Category = $('#categoriesList').serialize();
$.ajax({
url: 'page-videoFunc.php',
type: 'post',
data:{
action:'update_data',
form_data:Category
},
});
In page-videoFunc.php file, parse the form_data using parse_str.
if($_POST['action'] =='update_data'){
parse_str($_POST['form_data'], $my_form_data);
echo "<pre>";
print_r($my_form_data);
}
After using parse_str to cut off added URL to serialized data, to get all values of the array, you should do this:
parse_str($_POST['name'], $output);
$x = $output["name"];
foreach ($x as $key => $value) {
echo $value;
}
I am trying to use checkbox with Ajax. Without Ajax I have handle it.
Here is my Jquery code
$("#skillcat").click(function(e) {
var submit_val = new Array();
e.preventDefault();
var ids = $('check_subjects input:checked')
.map(function(){
return this.value;
}).get();
$.ajax( {
type : "POST",
dataType : "json",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'each_category',
check_subjects : ids
},
success : function(data) {
alert(data);
$('#accordion').html(data);
}
});
});
Here is my php code where button and checkbox is generated in serverside
foreach($subjects as $key=> $data){
echo '<input type="checkbox" id="'. $data->id .'" value="'. $data->id .'" name="check_subjects[]"> '. $data->subject .'<br>';
}
Serverside I used to catch data from Post array
if(isset($_POST['check_subjects'])){
//var_dump(check_subjects);
$check_subjects = implode(',', $_POST['check_subjects']);
//echo '$check_subjects '. $check_subjects;
}
however when I run above codes, I notice that some data is sent to the server(via chrom developer tool). But I get null in alert box. I guess response is null becase data is not sent to server properly. I am not sure about the javasript code I use to passe the request to Ajax.
Can anybody explain where I have done the mistake?
It is expecting JSON and you are returning html. So make the dataType HTML or json encode your return...
Try this:
$("#skillcat").on('click', function (e) {
e.preventDefault();
var ids = [];
var $el = $('[name*=check_subjects]:checked'); //Get all checked Checkboxes
$el.each(function () {
ids.push($(this).attr('id')); //get the Id from each checkbox
});
$.ajax({
type: "POST",
dataType: "html",
url : "./wp-admin/admin-ajax.php",
data: {
action: 'each_category',
check_subjects: ids
},
success: function (data) {
alert(data);
$('#accordion').html(data);
}
});
});
currently I have following code:
home.php
<form name='myformname' id='myformid'>
<input type='text' name='mytext1' value='abc'>
<input type='text' name='mytext2' value='123'>
<input type='submit' value='Submit'>
</form>
<div id='textone'></div><div id='texttwo'></div>
_home.php
$arr = array( 'textone' => $_POST['mytext1'], 'texttwo' => $_POST['mytext2'] );
echo json_encode( $arr );
ajax.js
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
data: $('#myformid').serialize(),
success: function( data ) {
// TODO: write code here to get json data and load DIVs instead of alert
alert(data);
}
});
return false;
});
Output on submit:
{"textone":"abc","texttwo":"123"}
Question
I want to load mytext1 value in textone DIV and mytext2 value in texttwo DIV using json data in _home.php
Hint: I am using this answer to do the same task on link click event. But how to do this on form submission ?
Thanks
You just wanna parse that JSON and set the divs to the values it contains right?
var divs = JSON.parse(data);
for (var div in divs) {
document.getElementById(div).innerHTML = divs[div];
}
(Previous poster's syntax is probably more like what you're after, and maybe is more cross-browser compatible, but doesn't include the JSON parsing.)
Since JSON is just a subset of JavaScript, you can just eval() it. JSON.parse() basically does that, but gives you assurances that if 'data' contains some nasty code instead of a simple object, it won't be evaluated.
In the success function
for (prop in data){
$('#' + prop).html(data[prop]);
}
Here is my complete JS solution:
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
dataType: 'json',
data: $('#myformid').serialize(),
success: function( data ) {
for(var id in data) {
//jQuery('#' + id).html(data[id]); // This will also work
document.getElementById(id).innerHTML = data[id];
}
}
});
return false;
});
Currently my AJAX is working like this:
index.php
<a href='one.php' class='ajax'>One</a>
<div id="workspace">workspace</div>
one.php
$arr = array ( "workspace" => "One" );
echo json_encode( $arr );
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
jQuery('#' + id).html(snippets[id]);
}
});
});
});
Above code is working perfectly. When I click link 'One' then one.php is executed and String "One" is loaded into workspace DIV.
Question:
Now I want to submit a form with AJAX. For example I have a form in index.php like this.
<form id='myForm' action='one.php' method='post'>
<input type='text' name='myText'>
<input type='submit' name='myButton' value='Submit'>
</form>
When I submit the form then one.php should print the textbox value in workspace DIV.
$arr = array ( "workspace" => $_POST['myText'] );
echo json_encode( $arr );
How to code js to submit the form with AJAX/JSON.
Thanks
Here is my complete solution:
jQuery('#myForm').live('submit',function(event) {
$.ajax({
url: 'one.php',
type: 'POST',
dataType: 'json',
data: $('#myForm').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
Submitting the form is easy:
$j('#myForm').submit();
However that will post back the entire page.
A post via an Ajax call is easy too:
$j.ajax({
type: 'POST',
url: 'one.php',
data: {
myText: $j('#myText').val(),
myButton: $j('#myButton').val()
},
success: function(response, textStatus, XMLHttpRequest) {
$j('div.ajax').html(response);
}
});
If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:
$j('div.ajax').load('one.php', data);
Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.
However it should be a fairly simple loop.
Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as
$('#myForm').ajaxSubmit();
You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.
You can submit the form with jQuery's $.ajax method like this:
$.ajax({
url: 'one.php',
type: 'POST',
data: $('#myForm').serialize(),
success:function(data){
alert(data);
}
});