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;
}
Related
I have a ajax page which will contain form function and also dynamic html code. please check the below example have to jsonencode the results but the forms is in dynamic format cant get it worked.
//getting_result.php
require_once('include/form.class.php');
$rowid = $_POST['rowid']; // database row id to retrieve the content
$getjson_form = getJsonForm($rowid); // will get the jsonform name
$form = new Form(['file'=>$getjson_form[0]['json_form_name']]);
// will show the form
ouput <div class="form-row" id="form_output_row"><div class="form-group col-md-6">//
$pagecontents = file_get_contents("llor.html");
$get_form = $form->show();
$total_output = array("json_form_name"=>$get_form);
echo json_encode($total_output,JSON_FORCE_OBJECT);
mypage for ajax jquery
$.ajax({
type: "POST",
url : "getting_result.php",
data : {rowid:id },
dataType: "json",
cache: false,
success: function(data){
console.log(data.json_form_name);
//$("#jsonformname").html(data.json_form_name);
var find_form = $(data).filter('#form_output_row');
console.log(find_form);
$("#jsonformname").html(data.json_form_name);
// $("#terms_cond").html(data.terms_condi);
}
});
You can use:
JSON.stringify(data);
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
<?php foreach ($types_show as $size): ?>
<td class='size_rdo'><?php echo Form::radio('radio_size', $value)?></td>
<?php endforeach;?>
This will display some radio buttons,I want to send the $value to the php. if there is the value in DB, the radio button is able, otherwise set it to disable.
I write some Pseudocode below,thanks for answering.
$(':radio[name=radio_size]').each(function(){
$.ajax({
type: "GET",
url: "/management/order/get_size",
data: {radio_size:radio_size},
cache: false,
dataType: 'json',
success: function(data) {
if (data) {
$(this).attr("disabled",true);
}
},
});
});
I think that FuelPhp allow you to do it in PHP with adding attributes on the Form helper (I don't know this framework, but it seems to work like another framework I know, see the documentation).
<?php foreach ($types_show as $size): ?>
<td class='size_rdo'>
<?php if($value) // Here I don't understand what you want to test on your
// condition, you must correct it depending of your needs
// If the value is not good, then add the disabled attribut
echo Form::radio('radio_size', $value, array('disabled'))?>
else // If the value is the good one, just continue like you did
echo Form::radio('radio_size', $value)?>
</td>
<?php endforeach;?>
Then you don't need Javascript
Im not sure if you really want an ajax call for every radio button. It would be better to do one call, and then loop and check for every radio...
anyway, you have to pass the $(this)
$(':radio[name=radio_size]').each(function(){
var $this = $(this);
$.ajax({
type: "GET",
url: "/management/order/get_size",
data: {radio_size:radio_size},
cache: false,
dataType: 'json',
success: function(data) {
if (data) {
$this.attr("disabled",true);
}
},
});
});
I think I am getting close on this, but for some reason the json data doesn't print out when it gets to the php page.
Here is my form with some dummy data:
<form id="add_form" action="javascript:void(0);">
<fieldset>
<input type="text" value="5" name="dogs" id="dogs" />
<input type="text" value="10" name="cats" id="cats" />
</fieldset>
</form>
Here is the related function (runs from a button, not shown above):
function add()
{
$.ajax({
type: 'POST',
cache: false,
url: 'add.php',
data: { json: $('#add_form').serialize() },
success: success
});
}
Finally the php that I can't seem to make work:
$json_object = json_decode($_POST['json']);
echo $json_object;
What I am really after is being able to get at the values for each element in the form (no matter how many form elements there are). As always, appreciate any advice you are willing to give.
Instead of,
function add()
{
$.ajax({
type: 'POST',
cache: false,
url: 'add.php',
data: { json: $('#add_form').serialize() },
success: success
});
}
You have to use,
function add()
{
var data = $('#add_form').serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'add.php',
data: data,
success: success
});
}
Then access like,
$_POST['dogs'];
there is no need to decode json because your form data passed to php page as "POST" type. so just do as follow.
$json = $_POST['json'];
print_r($json);
If you want to send JSON, you have to create JSON first. .serialize does not return JSON, it returns a query string, as you can read in the documentation:
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>.
Maybe you want:
data: { json: JSON.stringify($('#add_form').serializeArray()) },
but that seems to be overly complicated. Just use
data: $('#add_form').serialize(),
and access the data on the PHP side via $_POST['form_field_1'], etc.
On my page I have a form that inserts a new record in to the database. On the same page there is a DIV that contains the current resultset.
What I am trying to do is refresh just that DIV (not the whole page) when the form is submitted. The DIV will then contain the latest records (including the one just added).
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
});
return false;
});
<div id="current-rows">
<?php while($variant=mysql_fetch_array($variants)) { ?>
<div class="row">
// resultset
</div>
<?php } ?>
</div>
I set $variants from within my controller (beforehand):
$variants=Catalog::getProductVariants($product['id']);
Ideally I don't want to be returning a whole load of HTML to be injected in to that DIV.
Set the new content in the success handler of ajax request. Try this
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(newContent){
$('#current-rows').html(newContent);
}
});
return false;
});
I think it is easier to use .load method, which injects the response from the server to the given div, something like:
$('#idOfYourDiv').load('/your/url', {params: params});
alternatively you can still use $.ajax, like:
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(data) {
$('#yourDiv').html(data); // html will insert response, response is stored in "data" variable
}
});
return false;
});
on php site just echo what you want to be displayed, for example
foreach($results as $result){
echo $result."<br />";
}
hope that helps
I have put the contents of the "current-rows" div into it's own seperate view file:
<div id="current-rows">
<?php include("_current-rows.php"); ?>
</div>
And in my controller 'addvariants' action I just do this:
$variants=Catalog::getProductVariants($_POST['product_id']);
include('application/view/admin/catalog/_current-rows.php');
That is the response that is passed back to my jQuery success function.