i am capturing the value of changed fields via JS Event and capturing that data into temp1 array, say, if u change field name "name", then it will get the field name "id" and will store it into temp1. but the main problem is how can i pass this array to a php form processing page, where i can get the value of this temp1.
i tried using JSON but it's not helping me out.
the code which i tried was: $.post('/somepage.php', temp1); but it didnt work.
please help me out with this.
and i included jquery.js lib in the page.
<script type="text/javascript">
var temp1 = new Array();
function onChangeTest(changeVal)
{
//alert("Field u changed was: " + changeVal.id)
temp1.push(changeVal.id);
tmsg = "Fields u changed so far are:"
for(var i=0;i<temp1.length;i++)
{
//document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>");
tmsg = tmsg + " " + temp1[i];
}
alert(tmsg);
}
//$.post('/somepage.php', temp1);
</script>
The problem looks quite simple to me , try below code and let me know the outcome..
function onChangeTest(changeVal)
{
//alert("Field u changed was: " + changeVal.id)
var temp1 = new Array();
temp1.push(changeVal);
tmsg = "Fields u changed so far are:"
for(var i=0;i<temp1.length;i++){
//document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>");
//tmsg = tmsg + " " + temp1[i];
var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'outArray[]';
newHidInp.value = temp1[i];
document.frm.appendChild(newHidInp);
}
return false;
}
HTML:
<form name="frm" action="" method="POST" >
<tr>
<td><font color="red">*</font>Name:<input type="text" name="name" id="name" size="25" onkeyup="onChangeTest('name')" /></td>
<td><font color="red">*</font>Age<input type="text" name="age" id="age" size="25" onkeyup="onChangeTest('age')" />
<input type="submit" name="submit" value="SUBMIT">
</td>
</form>
</body>
</html>
PHP:
<?php
print("<pre>");
print_r(array_unique($_POST['outArray']));
?>
What you need is:
$.post("/somepage.php", { 'temp1[]': temp1 });
See here in the official documentation as well, there are examples with all kinds of data.
Change the way you store the changes. If you store the Field IDs as Object Keys (e.g. temp1["username"] = true) you can easily use $.post("/somepage.php", temp1) and read the values via $_POST["username"] etc. in PHP.
Related
I have below pre-set data inside the input field. I want to get the 20 from the "validate-item-blank-quantity" -> "minAllowed".
Is it possible to use Php to get value from there?
Thanks
<input type="number" name="qty_custom" id="qty_custom" value="" title="Quantity" class="input-text qty mage-error" data-validate="{"required-number":true,"validate-item-quantity":{"minAllowed":1,"maxAllowed":1000000,"qtyIncrements":1},"validate-item-blank-quantity":{"minAllowed":20,"maxAllowed":1000000,"qtyIncrements":10}}" aria-invalid="true" aria-describedby="qty_custom-error">
As lewis4 pointed in the comment you can send only name and value attributes. Anyway, you can use simple JS to create new hidden field and send with data from other attributes.
Assuming, that value of data-validate is always valid JSON, that should work:
HTML
<form action="yourscript.php" id="myform" method="post">
<input type="number" name="qty_custom" id="qty_custom" value="" title="Quantity" class="input-text qty mage-error" data-validate='{"required-number":true,"validate-item-quantity":{"minAllowed":1,"maxAllowed":1000000,"qtyIncrements":1},"validate-item-blank-quantity":{"minAllowed":20,"maxAllowed":1000000,"qtyIncrements":10}}' aria-invalid="true" aria-describedby="qty_custom-error">
<input type="submit" value="Send">
</form>
<script>
$('[data-validate]').each(function () {
let $el = $(this);
$('#myform').append("<input type='hidden' name='" + $el.attr('name') + '[data-validate]' + "' value='" + $el.attr('data-validate') + "' />");
});
</script>
PHP yourscript.php
<?php
if (!is_null($_POST) && !is_null($_POST['qty_custom']['data-validate'])) {
$arr = json_decode($_POST['qty_custom']['data-validate'], true);
echo "Minimal value is: " . $arr['validate-item-quantity']['minAllowed'], '<br>';
echo "Maximal value is: " . $arr['validate-item-quantity']['maxAllowed'], '<br>';
}
Don't forget to include jQuery in your head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
WARNING:
Remember that if you want to make some server-side validation you should not to send it via your request as it can be easily manipulated, so validation can be changed or even skipped.
i have a database Included 3 columns " name " , " barcode " , " price " and have a form like blow :
http://i.stack.imgur.com/MwHIw.jpg
i want when user fill the barcode input and press " Enter " key
do form like below pic :
http://i.stack.imgur.com/KPuXv.jpg
and the input names have be like blow :
<HTML>
<form action="do.php" method="Post">
name : <input name="name[]" type="text" />
barcode: <input name="barcode[]" type="text" />
price : <input name="price[]" type="text" />
</form>
</HTML>
--- Update 1 ---
Jquery Source
<script type="text/javascript">
$(document).ready(function(){
$("#text").keyup(function(){
var key = $("#text").val();
var active = true;
$.post("search.php",{key:key,active:active},function(data){
$("#result").html(data);
});
});
});
</script>
<?php
include "config/connect.php";
if(isset($_post["active"]) && $_post["key"])
{
$key = $_post["key"];
$sql = "SELECT * FROM `product_list` WHERE `barcode` LIKE :title ";
$result = $connect->prepare($sql);
$k = "%".$key."%";
$result->bindParam(":title",$k); // ----> i have a error here ! <----
if($result->execute())
{
if($result->rowCount()>0)
{
while($rows=$result->fetch(PDO::FETCH_ASSOC))
{
echo $rows["name"]."<hr />";
echo $rows["barcode"]."<hr />";
echo $rows["price"]."<hr />";
}
}
else
{
echo "i can't fount anything . please try another barcode";
}
}
}
?>
How echo result in a new inputs ?!
how Fix error ?!
what is problem ?!
Add more information here. Show what you have already written in PHP.. You tagged php and such, but what you are asking for is lots of basic info on the web..
Show us how far you are with coding, then we can help. Without you doing anything except html code, people here aren't going to help u.. no offense.
I've got multiple forms like this on one page:
<form method="post" action="#">
<input type="hidden" name="product_id" value="'.$item['articlenumber'].'" />
<input type="text" name="update_quantity" value="'.$pg->quantity.'" />
<input type="hidden" name="packing" value="'.$item['packing'].'" />
<input type="hidden" name="unit" value="'.$item['unit'].'" />
<input type="submit" name="addtocart" value="Update" />
</form>
And I've got one submit button at the bottom:
<input name='placeorder' type='submit' value='Place order' />
How can I check all forms when I press the submit button? I need to validate that the input that was given is the correct quantity.
UPDATE
I now got all the values from the forms in JavaScript and the validation is correct. Now I want to store the variables into PHP SESSIONS. I saw the answer from Ben and that would work if the values where in PHP, they are now in JavaScript. I need them on other pages so I thought Sessions would be the best thing here (if not, other suggestions are welcome).
I saw this answer and there they say it is not possible on one page. I understand that because PHP is server side and Javascript client side. Is this the only possible way to send Javascript variables to PHP?
Alright, first you should remove the type='submit' on the input. So change it to :
<input name='placeorder' value='Place order' />
Then you just need to add a javascript function to validate.
$(document).ready(function() {
$("input [name='placeorder']").click(function() {
var formOK = true;
$("form input").each(function(index, element) {
var value = $(element).val();
if (value != "OK") {
formOK = false;
}
});
if (formOK) {
submitForms();
} else {
alert("Form Input Inccorect");
}
});
});
function submitForms() {
$("#form1").add("#form2").submit();
}
With regards to your question about storing form data in a session variable Try something along these lines:
session_start();
if (isset($_POST['placeorder'])) {
$_session['ProductID'] = $_POST['product_id'];
$_session['UpdateQuantity'] = $_POST['update_quantity'];
$_session['Packing'] = $_POST['packing'];
$_session['Unit'] = $_POST['unit'];
}
Hope that helps
Both answers helped me a little bit but I needed to combine them so I ended up with a solution like the following. I got the values from the inputs by their unique name like this:
var sizeS25 = parseInt($("input[name='size-s25']").val(), 10) || 0;
var sizeM25 = parseInt($("input[name='size-m25']").val(), 10) || 0;
Then I send the variables to a PHP file:
window.location.href = "phpsessions.php?sizeS25=" + sizeS25 + "&sizeM25=" + sizeM25;
In the PHP file I set the variables as sessions:
$_SESSION['sizeS25'] = $_GET['sizeS25'];
$_SESSION['sizeM25'] = $_GET['sizeM25'];
I have code that will automatically add a new similar row defined in form by clicking add button.
<html>
<body>
<form>
<input type="text" name="quantity[]" class="input_text" id="pro"/>
</form>
</body>
</html>
Now I want to access different values of quantity[] in javascript function .
How to access this different values of quantity[] in javascript using it's ID or Name Attribute.
<script>
function abc() {
var id = document.getElementById("pro").value;
}
</script>
You can do something like this.
html:
<form>
<input name="p_id[]" value="0"/>
<input name="p_id[]" value="1"/>
<input name="p_id[]" value="2"/>
</form>
javascript:
var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
alert(p_ids[i].value);
}
The way to do that with plain JavaScript is to get all the elements with an specific name, as following:
var fields = document.getElementsByName('quantity[]');
Should you want to access an specific value, you could do that as well:
console.log(fields[0].value); // foo
Here's a jsfiddle with a code sample.
HTML:
<form name="order">
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
</form>
JS:
var elements = document.forms['order'].elements['quantity[]'];
console.log(elements[1].value); // outputs the value of the 2nd element.
demo: http://jsfiddle.net/NDbwt/
$('input[name=quantity]').each(function(){
alert($(this).val())
});
First: id must be unique on page. Otherwise document.getElementById will always return first spotted element with requested id.
In your case, you may do next:
var id = document.getElementsByName("quantity[]")[0].value;
But more safely (I'm not sure if order of items in returned array will always be the same as order in which elements are added) would be to generate ids like pro_0, pro_1, pro_2 etc
You're probably confused by the fact that PHP reads form fields as arrays when you use square brackets on their name. That's only a PHP trickāfor JavaScript, [] does not have any special meaning and you can read the items in the usual way:
var values = [];
var fields = document.getElementsByName("quantity[]");
for (var i = 0, len = fields.length; i < len; i++) {
values.push(fields[i].value);
}
alert("Values:\n" + values.join("\n"));
See it in action.
I'm attempting to make it so that when you click a button, it'll add new fields to the page. I know that onclick can only take JS functions so I decided to try my luck making a JS script. At first I had tried to do
<html>
<head><title>multiple line test</title><head>
<body>
<script type="text/javascript">
var texters='';
var num=0;
function newInput(nomnom)
{
texters='';
num=nomnom+1;
for (var i=0; i<nomnom; i++)
{
texters+='<p>\
Please specify a file, or a set of files:<br>\
<input type="file" size="40">\
</p>\
<p>\
Caption : <br> \
<input type="text" size="30">\
</p>';\
}
document.write(texters+'<div>\
<input type="submit" value="Send">\
</div>\
</form>\
<br>' + '<input type="button" value="new entry" onclick="newInput(num)">' . '</body></html>');
}
newInput(num);
</script>
</body>
</html>
but that didn't work. So I tried instead to add a little bit of php being that I know it better. I tried this :
<html>
<head><title>multiple line test</title><head>
<body>
<script type="text/javascript">
var texters='';
var num=0;
function newInput(nomnom)
{
document.write(<?php
tex='';
for (var i=0; i<=(nomnom); i++)
{
tex.='<p>
Please specify a file, or a set of files:<br>
<input type="file" size="40">
</p>
<p>
Caption : <br>
<input type="text" size="30">
</p>';
}
echo tex . '<div>
<input type="submit" value="Send">
</div>
</form>
<br>' . '<input type="button" value="new entry" onclick="newInput(num)">' . '</body></html>';
?>);
}
newInput(num);
</script>
</body>
</html>
But I know that won't work because I can't get the variable I'm using for the number of fields to use out of the JS and into the PHP. Is there any way I could force JS to put that number in $_POST so I can retrieve it without having to make another form? Or is there a better way to do what I'm trying to do?
You can set a hidden input field on the form, and have the Javascript populate that.
You should try using jquery http://jquery.com/ or a simialr scripting library as it will make manipulating the DOM much easier. Using jquery you can create an onClick function that will do what you want in a few lines of code:
var onClickAddInput = function()
{
$('div#your_div_id').append('<input type="text" size="30" />');
}
If you need to add more input boxes you could loop the append statement and give the individual input boxes ids that equal the loop number.
As commented PHP is for serverside, javascript for clientside. html is the ui elements which either can create. If you need something done on the server, do it in PHP, if it needs to be done on the client, do it in javascript. Here is a sample of javascript for you.
function newInput(nomnom)
{
var tex='';
for (var i=0; i<=(nomnom); i++)
{
tex+='<p>Please specify a file, or a set of files:';
tex+='<br/><input type="file" size="40"></p>';
tex+='<p>Caption :';
tex+='<br/><input type="text" size="30"></p>';
}
document.getElementById('form_id').innerHTML += tex;
}
when this function is called, it will create a number of new inputs and add them to the form with the id "form_id".