I'm trying to pass some array values to php page using ajax.this is what i have tried.but it's pass only first value.not all the array values
<script>
function priceSub() {
var price = $("input[name='price[]']").val();
$.post('db_price.php', {prce:price});
return true;
}
</script>
<?php //this is come from another page
$itemCount = count($_POST["price"]);
for($i=0;$i<$itemCount;$i++) {
$op_name=$_POST['price'][$i];
?>
<input type="hidden" value="<?php echo $price;?>" name="price[]" id="price"/>
<?php
}
?>
<input type="submit" value="Submit" class="suboderbtn" onclick="return priceSub();"/>
Try using json_encode function :
$.post('db_price.php', <?php json_encode($_POST["price"]); ?>);
do like this for posting an array field
Javascript
<script>
function priceSub() {
var price = $('input#price').serialize();
console.log(price)
$.post('db_price.php', {price:price});
return true;
}
</script>
html
<input type="hidden" value="10" name="price[]" id="price"/>
<input type="hidden" value="20" name="price[]" id="price"/>
First thing you need to know is you have {prce:price}, and use $_POST['price'], so you need to use {price:price} instead.
However, you can send any number of data via ajax:
$.post('db_price.php', {price:price, data1: "value1", data2: "value2",...});
And you can access data with $_POST['price'] , $_POST['data1'], $_POST['data2'],... in the php script.
Edit:
You can't send array with one text field. For do this, you can separate values with , and explode the value in the php script. For example the text field value may be "value1, value2". Now you can use this code for getting array value :
$prices = explode(",", $_POST['price']);
Now $prices[0] will be "value1" and $prices[1] will be "value2".
Related
I'm using PDO, foreach and echo to generate some form inputs with data from a database, the output for this example will look slimier to this:
<input type="checkbox" value="1" checked>Google
<input type="checkbox" value="2">Amazon
<input type="checkbox" value="3" checked>Microsoft
This is being used in a form which is posted to the same page.
I want to grab this data and store it in a database using a PHP variable so when the checkbox is checked the value is assigned to it like this:
// output
$data = '1,3';
please note, the checkbox is checked by the users and the data used here is just an example, i want the form to be able to collect the right data by user input.
Give name to checkbox as an array, so when you submit form you will get an array of checkbox values in the array which checkboxes are checked then you can implode that array with , comma separated.
<input type="checkbox" name="checkboxname[]" value="1" checked>Google
<input type="checkbox" name="checkboxname[]" value="2">Amazon
<input type="checkbox" name="checkboxname[]" value="3" checked>Microsoft
After submitting form you have to get values like below code.
$data = implode(",", $_POST['checkboxname']);
echo $data;
you can use jquery:
for example:
HTML:
<input type="checkbox" value="1">Google
<input type="checkbox" value="2">Amazon
<input type="checkbox" value="3">Microsoft
<button type="submit" id="btn">Submit</button>
JQUERY:
$(document).ready(function(){
$('#btn').on('click',function(){
var cboxVal = [];
$('input[type="checkbox"]:checked').each(function(i){
cboxVal[i] = $(this).val();
});
$.ajax({
url : 'insert_data.php',
method : 'POST',
data : {cval:cboxVal},
dataType: 'text',
async : false,
success : function(){
alert('data inserted!');
}
});
});
PHP:
<?php
if(isset($_POST['cval'])){
$cval_raw = $_POST['cval'];
for($i =0; $i<count($cval_raw);$i++){
$cval = $cval_raw[$i];
$sql = "INSERT INTO db_name(table_name) VALUES('$cval')" or die('cannot insert');
$query = mysqli_query($connect,$sql);
}
}
?>
I have a html form, where more than one values are submitted by one parameter.
How can I handle it in php
The whole thing looks like this:
Single parameter:
shoppingcart = Item 1
shoppingcart = Item 2
shoppingcart = Item 3
shoppingcart = Item 3
Name = Max
Surname = Brown
Adress = New York
you have to assign name a array like
<input type="text" name="shoppingcart[]"/>
if you get submit an array you should use it as an array eg:
$my_item_array = $_GET['shoppingcart '];
foreach($my_item_array as $key => $value){
echo $value . <br />;
}
Use Parameter as array type in html form shoppingcart[] and you can hanle it php loop.
foreach($_GET['shoppingcart'] as $item){
echo $item;
}
You can use it like this,
form,
item1: <input type="text" name="shoppingcart[]"/>
item2: <input type="text" name="shoppingcart[]"/>
Then in your php code,
$items = $_GET["shoppingcart"];
$_GET is supper global varieble in php. It's array and you can use it in following form:
Imagine to have following html form:
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
and welcome_get.php look like this:
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
I am getting a value with php $_GET[], and I want to pass it as the value of a simple html input element. I know I can do it like this:
<?
$value = $_GET['value'];
echo '<input type="text" name="value" value="'.$value.'" />';
?>
But is there any way to separate the php from html, giving the value to the textbox without echoing it?
I would like to create the textbox as regular html element, and only use php in the part where I set its value.
The answer of Iaroel was more practical for my purposes, but I liked the way that the accepted answer covered many concerns - I think it will be more valuable to other users.
You don't want an error when the $_GET['value'] becomes undefined.
<?php
$value = isset($_GET['value'] ? $_GET['value'] : '');
?>
<input type="text" name="value" value="<?php echo $value; ?>">
But be mindful with malicious data that can be inserted in $_GET['value'] so you've got to apply proper sanitation to $value
With regards to "Getting $_GET['value'] without PHP"
You can get it without PHP script by creating a small javascript function:
<script type="text/javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
</script>
What the hell was that regular expression? It's just a matter of matching pattern from the URL.
Now, you can use this $_GET() method to assign the value to that textbox. In this example, I used jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('input[name="value"]').attr('value', $_GET('value'));
});
</script>
Now your HTML code will be as simple as this:
<input type="text" name="value">
Reference: http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
If you don't wish to echo anything inside HTML, use Ajax call to get values.
$.ajax({
url: 'getValues.php',
type: 'post',
dataType: 'json',
success: function (json) {
if (json) {
$.each(json, function (k, v) {
$(k).val(v);
});
}
}
});
[PHP]
echo json_encode(array('#first_input_id' => 'val1', '#second_input_id' => 'val2', '.some_classes' => 'val5'));
Or if values are static, you can use local json file.
Do you mean like this?
<?php
$value = $_GET['value'];
?>
<input type="text" name="value" value="<?php echo $value;?>" />
Or this (not advised):
<?php
$value = $_GET['value'];
?>
<input type="text" name="value" value="<?= $someVar ?>" />
But i would suggest looking into a template engine for example http://www.smarty.net/
If your php configuration allows short tags you can do this:
<input type="text" name="value" value="<?=$_GET['value'];?>" />
you can try without echo
<?php $value = $_GET['value'];?>
<input type = "text" name = "value" value="<?= $value; ?>" />
If its really important for your project, ideally you want to separate your php code from your html tags. this can achieve by using some template engine.
There are some well known options available, best if you check and see which one suites your use-case best.
Mustache
Smarty
and of course Twig
You can use PHP Heardoc option. find the link here.
http://www.hackingwithphp.com/2/6/3/heredoc
I am trying to save some values into db, on first page i am running some matches and on the the 2nd page i need to save values. on first page only click button is shown to user, when he clicks , the values are stored.
code
<form action="ms_insert.php" method="post">
<input type="submit" value="Claim your daily bonus" name="test">
</form>
How can i submit all the values that are outside the form and send them to the ms_insert.php and process the values.
What i need to achieve it like this.
some values shall be matched , on successful match it will save the enteries into the db.
Here is the exact code that i am using now :
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
?>
<form action="" method="post">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="claim">
</form>
I want this php code to excute when user click the submit button.
There are two ways that I can think of doing this:
Simply set the post variable to another value as described here:
$_POST['text'] = 'another value';
This will override the previous value corresponding to text key of the array. The $_POST is super global associative array and you can change the values like a normal php array.
Second would be to use _SESSION tags as described in this post:
In the first.php:
$_SESSION['favcolor'] = 'green';
In ms_insert.php:
echo $_SESSION['favcolor']; // green
P.S. You can also use cookies
Additional sources:
http://www.felixgers.de/teaching/php/hidden1.html
You can use Javascript with a XHR object for example or try to insert your values to store in hidden inputs.
Solution 1 : AJAX, for example :
Your JS (Here with Jquery):
function saveInDb(){
/* Retrieve your values in your page : */
var myValue1 = $('#value1Id').val();
var myValue2 = $('#value2Id').val();
/*Create a Jquery ajax object : */
$.ajax({
type: "POST",
url: "ms_insert.php",
data: { "value1": myValue1, "value2": myValue2 }
}).done(function( msg ) {
alert( "Data Saved");
});
}
Your HTML :
<span id="value1Id">My value 1</span>
<span id="value2Id">My value 2</span>
<button onclick=saveInDb()></button>
Solution 2 : the HTML with hidden inputs :
<form action="ms_insert.php" method="post">
<input type="hidden" value="My value 1" name="value1">
<input type="hidden" value="My value 2" name="value2">
<input type="submit" value="Claim your daily bonus" name="test">
</form>
I have a php variable "echo $id". Now I want to use the $_POST method to post the variable. I just want to know how to do this for a variable because $_POST[$id] does not work?
I think you are misunderstanding a basic concept here.
The $_POST super global is used to receive input (in the form of a POST request) from the user. While it is possible to set variables in it, you shouldn't.
Your question does not make sense. If you have an HTML form:
<form action="" method="post">
<input type="text" name="something" />
<input type="submit" value="Submit" />
</form>
Then you get the variable $_POST['something'] with whatever the user typed in the text box.
On its own, $_POST is just a variable like any other. You can assign to it $_POST['test'] = 123;, you can delete from it unset($_POST['test']);, you can even make it something other than an array $_POST = "Hello, world";, it just happens to be pre-populated with form data, if any.
With the method $_POST you must be posting to something.
My suggestion to you is to create a form, then have the form going to the file you wish to post to:
So something like this:
echo '<form action = "fileToPostTo.php" method = "post">
<input type = "text" hidden value = "'.$id.'" />
</form>';
And then submit the form when the document loads through jquery or javascript.
You can do it by $_POST['id'] = $id (then You will have it in $_POST['id'] variable (but You shouldn't do it :P).
Or You can send $id by form. Like example:
<form action="/pageToPOST.php" method="post">
<input type="text" value="<?=$id ?>" name="id" />
<input type="submit" name="" value="submit it!" />
</form>
And You'll have $_POST['id'] on http://yourdomainname.com/pageToPOST.php page
you can get and pass the value without page load and form.
<input type="text" name="something" id="something" />
<input type="button" value="ok" onclick="value();"/>
function value()
{
var something=$("#something").val();
var dataparam="oper=show&something="+something;
$.ajax({
type:"post",
url:"yourphpname.pnp",//this is very important.
data:dataparam,
success:function(data)
{
alert(data);
}
});
}
$oper =(isset( $_REQUEST['oper'])) ? $_REQUEST['oper'] : '';
if($oper == "show" and $oper != '')
{
$something=$_REQUEST['something']
echo $something;
}
what you want to do is assign a value submitted to your script using the POST method, to your $id variable. Something like:
$id = $_POST['id'];