How to get values from a php generated form - php

I have some code for a PHP shopping cart which is as follow
if($cart->itemcount > 0) {
foreach($cart->get_contents() as $item) {
echo "Code/ID :".$item['id']."<br/>";
echo 'Quantity:<form method="post" action="cart.php"><input type="hidden" name="qtyid" id="qtyid" value="'.$item['id'].'"/><input type="submit" name="minus" id="minus" value="-"/>'.$item['qty'].'<input type="submit" name="plus" id="plus" value="+"/><br/></form>';
echo "Price :$".number_format($item['price'],2)."<br/>";
echo "Info :".$item['infos']."<br />";
echo "Shipping :".$item['shipping']."<br />";
echo "Subtotal :$".number_format($item['subtotal'],2)."<br />";
echo '<form method="post" action="cart.php"><input type="hidden" name="removeid" id="removeid" value="'.$item['id'].'"/><input type="submit" name="remove" id="remove" value="Remove"/></form>';
}
echo "---------------------<br>";
echo "total: $".number_format($cart->total,2);
} else {
echo "No items in cart";
}
I've been using jQuery Ajax to post the data to my php script and everything works fine when I've got one item:
/********************************/
/* Plus Item */
/********************************/
$('#plus').click(function()
{
var qtyid = $(this).val();
var plus = 'plus';
$.ajax({
url: 'cart.php',
type: 'post',
data: 'qtyid=' + qtyid + '&plus=' + plus,
sucess: function (result) {
console.log('it worked');
}
})
return false;
})
/********************************/
/* Minus Item */
/********************************/
$('#minus').click(function()
{
var qtyid = $(this)).val();
var minus = 'minus';
$.ajax({
url: 'cart.php',
type: 'post',
data: 'qtyid=' + qtyid + '&minus=' + minus,
sucess: function (result) {
console.log('it worked');
}
})
return false;
})
However, I'm having troubles when there are more than one product in the cart as, I guess, my code does not allow jQuery ajax to find where it should get the id from as the HTML generated does contain elements with the same ID.
</div>
<form method="post" action="cart.php">
<input type="hidden" name="imgid" id="imgid" value="YWNoZZeXk2htZmJjaWds">
<input type="hidden" name="imgalb" id="imgalb" value="YWNoZZeVnGdtZmJjamlj">
<input type="hidden" name="qty" id="qty" value="1">
<input type="submit" value="Add to cart" name="addtocart" id="addtocart">
</form>Code/ID :126264027457298<br/>
Quantity:
<form method="post" action="cart.php">
<input type="hidden" name="qtyid" id="qtyid" value="126264027457298"/>
<input type="submit" name="minus" id="minus" value="-"/>
9
<input type="submit" name="plus" id="plus" value="+"/>
<br/>
</form>
Price :$55.85
<br/>
Info :
Titre<br />
Shipping :6.00<br />
Subtotal :$556.65<br />
<form method="post" action="cart.php">
<input type="hidden" name="removeid" id="removeid" value="126264027457298"/>
<input type="submit" name="remove" id="remove" value="Remove"/>
</form>Code/ID :126265084123859<br/>
Quantity:
<form method="post" action="cart.php">
<input type="hidden" name="qtyid" id="qtyid" value="126265084123859"/>
<input type="submit" name="minus" id="minus" value="-"/>
2
<input type="submit" name="plus" id="plus" value="+"/>
<br/>
</form>
Price :$25.85
<br/>
Info :Boucles d'oreilles courtes «Conic»<br />
Shipping :6.00<br />
Subtotal :$63.70<br />
<form method="post" action="cart.php">
<input type="hidden" name="removeid" id="removeid" value="126265084123859"/>
<input type="submit" name="remove" id="remove" value="Remove"/>
</form>
---------------------<br>total: $620.35
</div>
I have been spending hours trying to find a solution. But I feel it's time to ask for help.
What should I do? How should I alter my HTML to generate unique IDs and find a way to get the ids from jQuery and PHP?

It seems that you just need to get the qtyid value associated with the plus/minus buttons you click. If that's the case, you should be able to get it using the following line:
var qtyid = $('#qtyid', $(this).parent('form')).val();
So an example of one of your click events would be:
$('#plus').click(function()
{
var qtyid = $('#qtyid', $(this).parent('form')).val();
var plus = 'plus';
$.ajax({
url: 'cart.php',
type: 'post',
data: 'qtyid=' + qtyid + '&plus=' + plus,
success: function (result) {
console.log('it worked');
}
});
return false;
});

Related

how to send data with ajax from input fields to php

I have currently this html:
<td>
<input type="hidden" class="old_name" name="old_name" value="folder1/image.jpg" />
<input type="text" class="new_name" name="new_name" value="" />
<button type="submit" class="rename">Rename</button>
</td>
<td>
<input type="hidden" class="old_name" name="old_name" value="folder2/image.jpg" />
<input type="text" class="new_name" name="new_name" value="" />
<button type="submit" class="rename">Rename</button>
</td>
<td>
<input type="hidden" class="old_name" name="old_name" value="folder3/image.jpg" />
<input type="text" class="new_name" name="new_name" value="" />
<button type="submit" class="rename">Rename</button>
</td>
My jquery ajax looks like this:
// AJAX for rename files
$(document).on('click' , '.rename' , function() {
var old_name = $(".old_name").val(); // getting old value from input
var new_name = $(".new_name").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
My php:
if( isset($_POST["old_name"]) && isset($_POST["new_name"]) ) {
echo $_POST["old_name"];
echo $_POST["new_name"];
First problem: when click on Rename second button, it echos the old_name from first button. So how can i catch the second value old_name when click on second Rename button?
Second problem: php does not echo the $_POST["new_name"]
How can i achieve this without using a form?
First problem solution
use different name (in your specific case different class name ) for different input
<td>
<input type="hidden" class="old_name1" name="old_name" value="folder1/image.jpg" />
<input type="text" class="new_name1" name="new_name" value="" />
<button type="submit" class="rename1">Rename</button>
</td>
<td>
<input type="hidden" class="old_name2" name="old_name" value="folder2/image.jpg" />
<input type="text" class="new_name2" name="new_name" value="" />
<button type="submit" class="rename2">Rename</button>
</td>
<td>
<input type="hidden" class="old_name3" name="old_name" value="folder3/image.jpg" />
<input type="text" class="new_name3" name="new_name" value="" />
<button type="submit" class="rename3">Rename</button>
</td>
new js function will be
$(document).on('click' , '.rename1' , function() {
var old_name = $(".old_name1").val(); // getting old value from input
var new_name = $(".new_name1").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
$(document).on('click' , '.rename2' , function() {
var old_name = $(".old_name2").val(); // getting old value from input
var new_name = $(".new_name2").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
$(document).on('click' , '.rename3' , function() {
var old_name = $(".old_name3").val(); // getting old value from input
var new_name = $(".new_name3").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
Second problem solution
you probably leave the field empty

Syntax to get PHP variables into jQuery Ajax

I have a php function:
<?php
function send_message($userid, $projectid, $message) {
//some code
}
$userid = '1';
$projectid = '2';
$message = 'hello';
?>
<form id="myform" method="post" action="">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
</form>
I want the submit button to do jQuery Ajax so my page won't refresh:
js:
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: //my valid url,
type: 'post',
dataType : 'json',
data: {
action: 'send_message', //this is the PHP function
projectid: projectid //how do I write this?,
userid: userid //how do I write this?,
message: message//how do I write this?'
},
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
On my error.log, I get NULL for the 3 parameters because I'm not sure how to access them from my PHP. How do you access the PHP variables from jQuery?
Put your PHP variables into hidden inputs so they'll be automatically sent when it is submitted.
For example : <input type="hidden" name="userid" value="1">
Serialize the form data : var formData = $(form).serialize();
On submit attach your form data :
$.ajax({
url: admin_ajax.ajax_url,
type: 'POST',
data: formData
})
Access it from PHP with a classic way : $_POST['userid']
<form id="insert_form">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" id="send" value="send message">
<input type="hidden" name="userid" id="userid" value="<?php echo $userid= '1'; ?>">
<input type="hidden" name="projectid" id="projectid" value="<?php echo $projectid='2'; ?>">
<input type="hidden" name="message" id="message" value="<?php echo $message=
'hello'; ?>">
</form>
var project-message=document.getElementById('project-message').value;
var send=document.getElementById('send').value;
var userid=document.getElementById('userid').value;
var projectid=document.getElementById('projectid').value;
var message=document.getElementById('message').value;
$.ajax({
url:"your_url.php",
type:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
}
})
You can get all the values of the form, and submit it.
Also you can set other the values in the form as hidden.
<form id="myform" method="post" action="" id='form1'>
<textarea name="projectMessage" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
<?php print "<input type='hidden' value='$userid' > "; name='userid' ?>
<?php print "<input type='hidden' value='$projectid' > "; name='projectid' ?>
<?php print "<input type='hidden' value='$message' > "; name='message' ?>
</form>
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
dataType:'json',
data: $("#form1").serialize(),
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
I like this approach because I can reuse the ajax multiple times or even create a generic function to submit the form on the background with ajax. Also I can fill the form using a for each loop in php, having all the values in an array (like a database result)
ex.
<?php
foreach($values as $k=>$v}{
print "<input name='$key' value='$v'>\n";
}
?>

get an id of a specific form within several form on the same page (jquery)

I have a problem, and i don't know how to get an id of a specific form when in the same page there is several form. Each form has a different id :
HTML :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
And this is the ajax
Jquery :
$('[id^=acheter]').submit(function() {
var CurrenID = $(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: $('#'+CurrenID).serialize(),
success: function(data) {
Method();
}
});
return false;
});
$('[id^=acheter]').submit(function() {
var data = $(this).serialize()+"&form_id="+$(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: data,
success: function(data) {
Method();
}
});
return false;
});
That will add your ID to the form post data?
in this line:
$('[id^=acheter]').submit(function() {
change to
$('#acheter').submit(function() {
Note that the id must be unique if you want to get more than one value from diferent tags use name or class.
to check the forms using the id just make a input button instead input submit, each one with a diferent variable to the jquery and submit .
example :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="button" id="addToCart1" name="addToCart" onclick="submitF('1')">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="button" id="addToCart2" name="addToCart" onclick="submitF('2')">Add</button>
</form>
Then use jquery/javascript to check what button was clicked
function submitF(var)
{
if (var == 1)
{
...
/*do what you want knowing that the first form was clicked,
submit form with jquery if you want*/
...
}
if (var == 2)
{
...
/*do what you want knowing that the second form was clicked,
submit form with jquery if you want*/
...
}
}

Submiting form with jquery

I have a form and I need to add some data from database before submiting it.
My html code is:
<form action="https://91.199.226.106/services/authorize.php" id="arca" method="POST">
<input type="hidden" name="hostID" id="hostID"/>
<input type="hidden" name="mid" id="mid" />
<input type="hidden" name="tid" id="tid" />
<input type="hidden" name="additionalURL" id="additionalURL" />
<input type="hidden" name="orderID" id="orderID" />
<input type="hidden" name="currency" id="currency" />
<input type="hidden" name="opaque" />
amount<input type="text" name="amount" id="amount" value="" /><br>
<input type="submit" value="submit" />
</form>
<div id="script_area"></div>
<div id="error_area"></div>
And I have an event handler for form submit. Here is the code:
$("#arca").submit(function(e){
e.preventDefault();
var data="amount="+$("#amount").val()+"&&lang=eng";
$.ajax({
url: "ajax/get_arca_submit_params.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
var splited=html.split("|",2);
if(splited[0]=="0")
{
$("#error_area").html(splited[1]);
}
else
{
$("#script_area").html(splited[1]);
$("#arca").submit();
//alert("aaaaa");
}
}
});
});
The PHP returns
"0|error message" or "1|script that sets fields values" that I place
in the div with id="script_area"
. The problem is that $("#arca").submit(); line ceeps on submiting the form on and on. How can I solve this problem? Thanks for help.
Replace $("#arca").submit(); with $("#arca")[0].submit();. This way you are calling the submit event on the underlying DOM element which won't trigger your callback and avoid the infinite loop.
You could change to bind a click event to submit button instead.
$("#arca").find('input[type="submit"]').click(function (e) {
e.preventDefault();
var data = "amount=" + $("#amount").val() + "&&lang=eng";
$.ajax({
url: "ajax/get_arca_submit_params.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
var splited = html.split("|", 2);
if (splited[0] == "0") {
$("#error_area").html(splited[1]);
} else {
$("#script_area").html(splited[1]);
$("#arca").submit();
//alert("aaaaa");
}
}
});
});

submitting two forms via javascript without click

i am using the following code to auto-submit a form
<script type="text/javascript">
$(function () {
$('#submit').click();
});
</script>
<div style="display:none">
<form method="post" action="http://mydomain/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form>
</div>
i want to submit the same data to two urls ...
http://mydomain/texting/register.php?list_id=15
http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>
how can edit my code to submit same form data automatically?
i tried this code
<script type="text/javascript">
function submitTwice(f){
f.action = 'http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>';
f.target='ifr1';
f.submit();
f.action = 'http://mydomain.com/texting/register.php?list_id=15';
f.target='ifr2';
f.submit();
}
</script>
*/
<script type="text/javascript">
$(function () {
$('submitTwice(f)').click();
});
</script>
<div style="display:none">
<iframe name="ifr1" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
<div style="display:none"><iframe name="ifr2" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
but it is not working, any suggestion to make it happen, the same data is to be sent to both the urls automatically using javascript
You can use jQuerys ajax and send the data with post, to both the urls.
first save all data you want to send in an valid data array. if you want it automated, you can do something like this:
var sendData = {};
$("#formId").find("input").each(function(i, item){
sendData[item.name] = item.value;
});
or as a simple string:
var sendData = "name=value&email=value";
then send the form data to both urls with ajax, as post type:
$.ajax({ url: "http://url1/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
$.ajax({ url: "http://url2/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
Note: make sure to return false to the button or sending form, you can do that something like:
$("formId").submit(function(){
// do ajax send data
return false;
}
EDIT: added unchecked code for this, with comments
$(document).ready(function(){
// grab the form and bind the submit event
$("#formId").submit(function(){
// collect all the data you want to post
var sendData = {};
this.find("input").each(function(i, item){
sendData[item.name] = item.value;
});
// send the request to both urls with ajax
$.ajax({ url: "url1", type: "POST", data: sendData,
success: function(response){
// handle response from url1
alert(response);
}
});
$.ajax({ url: "url2", type: "POST", data: sendData,
success: function(response){
// handle response from url2
alert(response);
}
});
// return false, to disable default submit event
return false;
});
});
just send name and email to the server script in a regular form,
then do two requests from within your register.php with something like HttpRequest or the like...
some freehand code:
client:
<form id="autoSubmitForm" method="post" action="/register.php?list_id=15">
<input type="hidden" name="name" value="<?php data['name2']; ?>" />
<input type="hidden" name="email" value="<?php data['email2']; ?>" />
<input type="submit" name="submit" value="Sign Up" style="visibility:hidden;" />
</form>
<script>
$(document).ready(function(){
$('#autoSubmitForm').submit();
});
</script>
server:
<?php
$name = $_POST["name2"];
$email = $_POST["email2"];
$url1 = 'http://lala'; //or relative to server root: '/lala'
$url2 = 'http://other';
sendRequest($url1, $name, $email);
sendRequest($url2, $name, $email);
?>
The implementation of sendRequest is worth another question (or reading the documentation of HttpRequest mentioned above)
Good luck, I see your duplicate question got closed...

Categories