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']);
Related
assuming that i have an HTML textbox with a name with an array:
<input type="hidden" id="text_array" name="text_array[]" class="test">
and i have a jquery code that gets the data on the textbox:
$('.test').each(function(){
arr = $(this).val();
});
how can i get the array content and transfer it into another laravel view and then print it? i tried to get it by using echo my controller but i have recieved comments about printing outputs in a controller is a bad practice.
Hmm i would recommend to use a Database or Session storage. But one idea is to save the value via JavaScript into a cookie.
Disclaimer: Untested ;)
Save the Value:
$('.test').each(function(){
arr = $(this).val();
document.cookie = 'mycookie=' + arr +'expires=DateHere;path=/'
});
Get it (somewhere):
$value = $request->cookie('mycookie');
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.
I'm very new to ajax and I'm trying to pass an array that I have created in javascript called markers over to a PHP page when the user clicks the submit button. At the time of submission the array exists and is within scope. The code below is what is trying to do that. When I click the submit button I get sent to the php page and "failed" is printed (part of my code) meaning the array was not passed. I believe the error occurs in the ajax code and I'm not sure where it is coming from, any help is greatly appreciated!
The javascript/ajax stuff:
function submit_tour(){
var input = JSON.stringify(markers);
//var input = $(this).serialize();
var sent = $.ajax({
type: "POST",
data: input,
dataType: 'JSON',
url: "test_portal2.php"
}).done(function() {window.alert("done");})
.fail(function() {window.alert("failed");});
window.alert("" + input);
}
The HTML button that is supposed to send the array:
<form name="toursubmit" action="test_portal2.php" onsubmit="submit_tour()">
<input type="submit" value="Submit">
</form>
The PHP that catches it (in the test_portal.php file):
$ans = json_decode($sent);
echo $ans;
if ($ans != NULL){
echo "works";
echo $ans;
}
else {
echo 'failed';
}
A couple of things to point out.
First, you need to prevent the default POST action within your submit_tour() function, otherwise the synchronous POST will happen.
Second, you need to specify the contentType value in your AJAX call as application/json.
Third, if you are actually POSTing JSON to PHP and using application/json as the ContentType, then you will need to get the JSON data in PHP by accessing the raw input like this:
$json = file_get_contents('php://input');
$obj = json_decode($json);
This is because $_POST is only auto-generated for form-encoded content types.
When you send
var input = JSON.stringify(markers);
And markers has no value
<input type="hidden" id="markers" name="markers"> // No value anywhere
Then it will surely be Null :)
Also do you populate your $sent variable from a value in $_POST ? don't see that happening
You don't need this in a form tag. The code is submitting the form and not running the JS.
Remove the form tag, or put this: submit_tour(); in onsubmit on the form instead, and return false.
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());
});