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"]);
}
});
}
Related
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
I need to pass an array to a php page with AJAX. This array of input elements gets sent to the other page:
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith" size="117" >
This is how I prepare it for sending:
var txtCoursesNamewith = $.serialize($('#txtCoursesNamewith').val());
But I get this error when running the script:
TypeError: $.serialize is not a function
How can I send an array with AJAX?
I am facing same problem and, i am just using code like this.
but first of all please insert one hidden field and set textbox id like this:
<input type="hidden" name="txt_count" id="txt_count" value="3" />
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith1" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith2" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith3" size="117" >
<script type="text/javascript">
var txt_count= $('#txt_count').val();
for (i=1; i<=txt_count; i++){
queryString += "&txtCoursesNamewith%5B%5D=" + $('#txtCoursesNamewith'+i).val();
}
</script>
finally we can pass queryString variable to ajax, and you can print array.
<?php
echo "<pre>";
print_r($_GET); // or print_r($_POST);
?>
var textBoxes;
$('input[name="txtCoursesNamewith[]"]').each(function() {
textBoxes+=$(this).val()+"|||";
});
Now the textBoxes have all the values of text field with ||| separated and pass to php script and use explode() function to split each input value . may it helps u
You don't need to use .val() because .serialize() works on a the field itself, not on the value. (because it needs to get the name and the value from the field)
You can also call serialize() directly on a jQuery object, rather than using the jquery object as a parameter. Do it like this:
var txtCoursesNamewith = $('#txtCoursesNamewith').serialize();
Hope that helps.
Because $.serialize($('#txtCoursesNamewith').val()) is a string and not a jQuery object, it doesn't have the serialize function.
If you want to serialize the input (with its value), use $('#txtCoursesNamewith').serialize();
$.ajax({
type: 'POST',
url: your url,
data: $('#'+form_id).serialize(),
success: function(data) {
$('#debug').html(data);
}
});
Then in php
<?php
print_r($_POST);
?>
<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());
});
I HAVE modified my code, i used firebug console.log to detect weather the the php gets the array passed or not. and firebug displays this - rescheck[]=2&rescheck=1&rescheck=3
I think php gets the array if THATS what an array in php supposed to be like.
SO guys, if thats correct how to insert that array in database? or how to loop it? the foreach loop ive made didnt work.
JQUERY CODE:
$('#res-button').click(function (){
var room_id=$('[name=rescheck[]]:checked').serialize().replace(/%5B%5D/g,'[]');
alert(room_id);
$.ajax({
type: "POST",
url: "reservation-valid.php",
data: {name_r:name_r, email_r:email_r,contact_r:contact_r,prop_id:p_id,cvalue:room_id},
success: function(data) {
console.log(data);
}
});
});
<input type="checkbox" name="rescheck[]" value="<?php echo $roomid; ?>" />
PHP CODE:
$c_array=$_POST['cvalue'];
echo $c_array;
//foreach($c_array as $ch)
//{
//$sql=mysql_query("INSERT INTO reservation VALUES('','$prop_id','$ch','$name_r','$contact_r','$email_r','')");
//}
I think I managed my jquery code to be right, but I don't know how to fetch that with PHP.
room_id is an array, so if you want to get the value for each, you need to get all value together first.
var room_id_string = '';
for(i=0;i<room_id.length;i++){
room_id_string += room_id.eq(i).val() + ',';
}
your below code will only pass Array jquery object of [name=rescheck[]]:checked to room_id
Instead of this you will have to create a array and push values in it like this
var room_id = Array();
$('[name=rescheck[]]:checked').each(function(){
room_id.push($(this).val());
});
In jQuery it might be easier for you to just use the serialize function to get all the form data. jQuery passes the form to the server so you don't have to worry about getting all the values. If you use it in conjunction with the validate plugin you might find it a little easier!
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This is what I do ibn my site for saving to a db a list of checkboxes with jquery and ajax call. It make an array and pass it to the ajax call and the php script handle the array.
If you get any error here you should debug the js array with firebug for be sure that is formed correctly.
js script:
var $checkBox = $('[name=rescheck[]]:checked');
$checkBox.each(function() {
if ($(this).is(":checked")){
valuesCheck[this.value] = 1;
}else{
valuesCheck[this.value] = 0;
}
and the PHP script:
$checkTab = $_POST['cvalue'];
foreach ($checkTab as $idChkTab => $checkedOrNot){
if ($checkedOrNot== "0"){
//do something if isn't checked
}
I am trying to use this piece of code to serialize a form AND send an extra variable not found in the form, at the same time. The following line of code is what I expected, but sadly does not work.
var thePage = theFilename();
$.post("pagedetail.php", { $("#PageDetailForm").serialize(), thePage: thePage },
function(data) {
alert(data);
});
Any ideas?
var serialized = $('#PageDetailForm').serialize();
serialized.thePage = thePage;
$.post("pagedetail.php", serialized,
function(data) {
alert(data);
});
what you can do is to add the extra data to an hidden input and catch it in the
pagedetail.php page .
eg lats say your form
<form id='PageDetailForm'>
<input type="hidden" name="value" id="value" value="the value u wamnt to add goes here" />
....other inputs
</form>
after this just do your normal $.post
$.post("#pagedetail.php",$("#PageDetailForm").serialize(),function(data){
$("#ans").html(data);
// in the pagedetail.php
$echo $_POST['value'];
hope dis help if ur still confused hola me #dplumptre
Try this for the second parameter to $.post:
{ form: $("#PageDetailForm").serialize(), thePage: thePage }
Hopefully you still need this :).
Try the serializeArray() method and then push some additional data in the resulting array, so you don't have splitted arrays etc.:
var postData = $('#form-id').serializeArray();
var additionalData = $('#additionalDataID').val();
postData.push({name: 'additionalName', value: additionalData});
and finally:
$.post(URL, postData);
Try sortable('toArray'):
var thePage = theFilename();
$.post("pagedetail.php", { pageDetailForm: $("#PageDetailForm").sortable('toArray'), thePage: thePage },
function(data) {
alert(data);
});