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
Related
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>
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));
?>
Could someone help me with how to pass an array of values from PHP and retrieve it using AJAX. What i have found is only to pass a single value from PHP. When i try passing the value of an array i dont know how to receive it at the AJAX side
This is my PHP code:
$success[];
$timeout[];
$fail[];
while($row1 = mysql_fetch_array($masterresult))
{
$success[]=$row1[1];
$timeout[]=$row1[2];
$fail[]=$row1[3];
}
echo json_encode(array("a"=>$success,"b"=>$timeout,"c"=>$fail));
And below is by AJAX call:
var channel;
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
window['channel']="overall";
$.ajax({
type:"GET",
url:"dash2.php",
data:{channel:channel},
dataType:'json',
success:function(data){
console.log(data.a);
console.log(data.b);
console.log(data.c);
}
});
}
How should i pass those php array values onto this ajax call? could someone help me with the code
What you want to do is encode it as JSON.
$yourArray = array('asdf', 'qwer', 'zxcv');
echo 'var yourJavaScriptArray = ' . json_encode($yourArray) . ';';
This makes all of your arbitrary data safe for use in JavaScript as well.
If you are only doing this with AJAX, no need for the var part. Just output from json_encode() directly.
Whether it is one value or multiple values in an array for example, you should always use:
json_encode($your_php_var)
json_encode your array on PHP end.
Use that JSON object in JavaScript without any additional effort, its part of JavaScript.
When you send it back to PHP just json_decode it in PHP.
Reference: PHP Manual
Hope this example will help you. Imagine if you have some input data on html form and need to send them by AJAX, do something with them on server side and recive the result on client side and do some stuff with it.
<form id="my_form" method="post" action="<?=$ServerSideUrl?>">
<input type="text" name="field_1" value="">
<input type="text" name="field_2" value="">
<input type="text" name="field_3" value="">
</form>
Here is you AJAX script, i used in this example JQuery
$('#my_form').ajaxSubmit({
dataType: 'html',
error: function() {
alert('some error text');
},
complete: function(data) {
//data this is the result object which returned from server side
//for example you shpold alert the sum of thouse 3 field
alert(data.sum);
}
});
Here is your server side code
<?
$data = array();
$data["sum"] = $_POST["field_1"] + $_POST["field_2"] + $_POST["field_3"];
echo my_json_encode($data);
return true;
?>
So when your AJAX will be complete it alert the sum of three field on your form,
You can use JSON in combination with jQuery for that.
<?php
$myArray = array('a', 'b');
echo json_encode($myArray);
?>
Ajax
$.get('http://localhost/index.php',
function(data) {
var response = jQuery.parseJSON(data);
console.log(response);
}
);
In your code:
var channel;
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
window['channel']="overall";
$.ajax({
type:"GET",
url:"dash2.php",
data:{channel:channel},
dataType:'json',
success:function(data){
console.log(data["a"]);
console.log(data["b"]);
console.log(data["c"]);
}
});
}
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.
<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());
});