Pass an array by ajax to php page - php

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

Related

Dynamically added form elements are posted to PHP but cannot access them

I'm posting dynamically added form elements to PHP via AJAX.
I can see that the serialised form data is posted to the php, but when I try to access the data within it, some of the fields come up NULL i.e. var_dump in the PHP below shows NULL.
this is the Jquery that adds the dynamic elements:
$(function(){
var count=0;
$('#more_edu').click(function(){
count ++;
$('#education_add').append('<br><br><label>University/Institution: </label><input type="text" class="searchbox" id="edu_inst'+count+'" name="edu_inst[]" maxlength="200" value="">);
event.preventDefault();
});
});
and the Jquery posting to php:
function profileSub(){
var myform;
event.preventDefault();
myform = $('form').serialize();
$.ajax({
type: 'POST',
url: 'tutorprofileinput.php',
data: {"form": myform},
success:function(data, response, xhr){
console.log(response);
console.log(data);
console.log(xhr);
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
This is the original form:
<form id="tutor_profile_input" onsubmit="return false;">
<label>University/Institution: </label>
<input type="text" class="searchbox" id="edu_inst" name="edu_inst[]" maxlength="200" value=""> </br></br>
<label>Subject:</label>
<input type="text" class="searchbox" id="edu_subj" name="edu_subject[]" maxlength="200" value=""></br></br>
<label> Level </label>
<select id="edu_level" name="edu_level[]">
and the PHP itself:
<?php
if (isset($_POST['form'])){
$form = $_POST['form'];
var_dump($_POST["edu_inst"]);?>
This is the var dump of the whole $_POST:
location=&price=&tutorname=&edu_inst%5B%5D=Uni1&edu_subject%5B%5D=subje1&edu_level%5B%5D=BA&edu_inst%5B%5D=uni2&edu_subject%5B%5D=subj2&edu_level%5B%5D=BA&bio=%09&exper
The form you've posted has an ID of #tutor_profile_input, where as the one you're appending to in the jQuery function is #education_add - Unless I've misunderstood?
Otherwise I'd look at specifying a more specific target in the AJAX request - You're just targetting $('form') at the moment which could be any form on the page..
Have discovered the answer so thought I would share - The Jquery serialize() function encodes the data into a string, which is then posted to PHP as an array with the key of "form".
In order to deal with this in php I had to first use the urldecode function in PHP to convert the string encoded elements (%5B%5D) from the name attributes. This was because there might be multiple values in these so they were declared in the form as an array ("name="edu_insts[]"). Then use parse_str to split the string into an array.
<?php
$querystring = $_POST['form'];
$querystring = urldecode($querystring);
parse_str($querystring, $params);
$insts = $params['edu_inst'];
echo $insts[0]."<br>";
echo $insts[1]."<br>";
?>
This will create an array named $params with keys corresponding to the form name attributes.
Note that if you have multiple values within the same name, then each one will be placed within an array itself, so with the above text you will have $insts[0] = University 1
and $insts[1] = University 2 etc.
Hope this helps anyone with the same problem.

Pass an array from PHP to javascript using PHP

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"]);
}
});
}

Adding Table Cell Contents to PHP $_POST

From my understanding, the only way to retrieve $_POST data is using the name attribute of the element, like so:
<INPUT type="text" name="txt">
and the PHP portion:
<?php $text = $_POST["txt"]; ?>
I've got a table with cells containing plain text, for example:
<td class="textField" id="txt1"> Some text </td>
Is there anyway to post the text in these table cells and retrieve them using either the class or id? Maybe there is a clever way to get around this? <td> doesn't have a name attribute thus the reason for my question.
Thanks!
You can use ajax, getting values from the table with javascript. JQuery is a good library for this:
http://api.jquery.com/category/ajax/
$_POST and $_GET come from the request. Meaning the browser sends them with the headers and PHP provides an interface to them with $_POST, $_GET, $_COOKIE, and $_REQUEST. The browser doesn't send contents of a table in the request.
If you're trying to make a field 'read-only' you're going about it the wrong way. If a field is read-only you should never trust the browser to re-send that same value.
To retrieve values from many form-fields who all have the same name (because you generate them with a loop in PHP), append brackets to the names of your fields.
Simple example:
<form method="post">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
</form>
If you add to your code:
<?php print_r($_POST); ?>
you'll notice that the $_POST variable is populated with an array named "myfield" having 4 values from $_POST['myfield'][0] to $_POST['myfield'][3]. You may then use a foreach loop in PHP to retrieve all values.
The solution that ended up working for me was to grab the data using jQuery, encode it in JSON, and add it to a serial array of the rest of the form data.
$("#orderForm").submit(function(e) {
e.preventDefault();
// Get NON-INPUT table cell data
var subtotal = new Array();
$('#priceTable td.subtotal').each(function() {
subtotal.push($(this).html());
});
// Get all INPUT form data and organize as array
var formData = $(this).serializeArray();
// Encode with JSON
var subArray = JSON.stringify(subtotal);
// Add to formData array
formData.push({name: 'sub', value: subArray});
// Submit with AJAX
$.ajax({
url: "submitOrder.php",
data: formData,
type: 'post',
success: function(data) {
alert(data);
}
});
});
And on the PHP side:
$subtotals = json_decode($_POST['sub']);

php parsing jQuery form serialize wrong way

I have one problem...
These are names of some my html form elements:
name="password"
name="meta[naziv_firme]"
This is my jQuery
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
console.log(data);
$.get('/index.php/admin-ajax', data,
function(response){
// Success
$('div#edit-klijent-div,.tipsy').hide();
$('div#klijent-edit-success').show();
});
Console.log gives me result:
action edit
form userID=12&password=&password-match=&email=test15%5Bmeta%5Bnaziv_firme%5D=test15&meta%5Bkontakt_osoba%5D=test156&meta%5Bkontakt_telefon%5D=test157&meta%5Bkontakt_email%5D=test158
So everything look OK!
Now in PHP I have var_dump($_GET); and the result is:
string(165) "userID=12&password;=&password;-match=&email=test15&meta;[naziv_firme]=test15&meta;[kontakt_osoba]=test156&meta;[kontakt_telefon]=test157&meta;[kontakt_email]=test158"
Why does PHP put ; after password, in &meta;[... ??
And ideas? What am I doing wrong?
Thank you!
In your HTML form element, add:
<input type="hidden" name="action" value="edit">
And change this line:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
Into this:
var data = $('input', 'form#edit-klijent-form').serialize();
Can't really test it since I don't have your HTML or server configuration, but I think it should work.
Update:
To clarify #AnthonyGrist's comment above, let's observe what serialize does:
<form>
<input type="text" name="input1" value="foo">
<input type="text" name="input2" value="bar">
</form>
<script>
var data = $('form input').serialize();
// data is now: 'input1=foo&input2=bar'
</script>
If you assign the value returned above to a query parameter (which PHP accesses using $_GET), you're basically telling PHP that $_GET['form'] equals the string above, which is not what you intended. PHP would not parse the contents of $_GET['form'] to give you $_GET['input1']... The value returned by serialize() should be used as the 2nd argument to $.get() directly.
Change your code from:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
To:
var data = "action=edit&" + $('input', 'form#edit-klijent-form').serialize();
I think it is what you're trying to achieve.

how to get values from generated text inputs?

i am creating a few input fields in a foreach loop:
<?php foreach($this->results as $value){?>
<td>View Detail
<input name="processor" id="processor" type="text" value="<?php echo $value['processor']; ?>">
<input name="auth_code" class="auth_code" type="hidden" value="<?php echo $value['auth_code']; ?>"></td>
<? } ?>
is will give me something like:
<td>
View Detail
<input name="processor" class="processor" type="text" value="19">
<input name="auth_code" class="auth_code" type="text" value="4">
</td>
<td>
View Detail
<input name="processor" class="processor" type="text" value="9">
<input name="auth_code" class="auth_code" type="text" value="11">
</td>
...
then i try to get the values:
$('.buttonDetails').live("click", function (){
var processor = $('.processor').val();
alert(processor);
$.ajax({
type: 'POST',
dataType: 'json',
url: '/decline/list',
async: false,
data: {
processor: processor,
processor: auth_code
},
success: function(json) {
$('#details').html(json.processor);
}
});
return false;
});
the problem i have is that my alert gets the same number (usually the first value from the first input) when i click on any link.
any ideas ho to fix this? i've tried replacin classes with id's and 'click' with 'live' but still nothing
edit:
i believe i need to differentiate the classes so he links will know what value to pull..??
edit: what if i want to get the 'auth_code ' also?
Try:
$('.buttonDetails').live("click", function (){
var processor = $(this).next(".processor").val();
alert(processor);
/* snip */
});
Use next to get the input next to the link that was clicked.
Update (due to comment).
You could find auth_code similarly using nextAll instead:
var auth_code = $(this).nextAll(".auth_code").val();
Also, are you sure you're supplying the correct values to your AJAX call? It looks like you're specifying processor twice. The first value specified for processor will be overwritten.
If you just want the next item you can use jquery next()
$('.buttonDetails').live("click", function (){
var processor = $(this).next().val();
alert(processor);
return false;
});
here is a fiddle
http://jsfiddle.net/znge4/1/
data: {
processor: processor,
processor: auth_code
},
the 'auth_code' line will overwrite the 'processor' line, effectively making it
data: {
processor: auth_code
},
only. You can't have a single key with two different values in a associate array/object. For submitting same-name fields to PHP, use its fieldname[] notation, which tells PHP to treat that particular form field as an array.
<input name="processor[]" ...>
<input name="processor[]" ...>
and pass the data to JQuery via
data : $(this).serialize()
use Jquery .next() which should give you the next element
You get the same value no matter which anchor tag was clicked because of this line:
var processor = $('.processor').val();
You're searching the entire DOM for all elements with class 'processor', which returns every input, and then .val() will return the value of the FIRST match (the first input).
Try this instead:
var processor = $(this).next('.processor').val();
All you need to do is get the value from the element they clicked. Using Jquery's 'this' keyword should solve your problem.
$('.buttonDetails').live("click", function (){
var processor = $(this).next().val();
alert(processor);
The 'this' will select the 'a' they clicked on, then next will iterate to the next sibling, in this case your input, and the val retrieves that value as before.

Categories