How can i output Ajax Value to a PHP Variable? - php

Problem :
There is a Value1 that is calculated from Ajax Function addToAuthorizeform();
There is a Value2 that is a PHP varibale $amount. This variable should show the output of the value1 that is calculated by Ajax Function.
How it is possible?
My code so far:
//AJAX FUNCTION THAT OUTPUTS AN AMOUNT
//SEE LINE 24 value="'+arrData[1]+'" <-- This is the correct value that needs to be //output on PHP VARIABLE
<script>
function addToAuthorizeForm() {
$wbc('#slots_purchased').html('');
var new_html = '';
var i = 1;
$wbc('#booking_slots').find('input').each(function () {
if ($wbc(this).attr('checked')) {
var slot_id = $wbc(this).val();
//ajax request to get data
$wbc.ajax({
url: '<?php echo plugins_url('
my_plugin / public ');?>/ajax/getSlotInfo.php?slot_id=' + $wbc(this).val(),
success: function (data) {
arrData = data.split("$");
if (arrData[1] > 0) {
q = 1;
if ($wbc('#seats_' + slot_id).val() != undefined) {
q = $wbc('#seats_' + slot_id).val();
}
new_html += '<input type="hidden" name="x_amount_' + i + '" value="' + arrData[1] + '" />';
$wbc('#slots_purchased').html(new_html);
i++;
}
}
});
}
});
}
</script>
Now The PHP Variable is
$amount = '';
Now I need to know what code should I put after $amount = 1 so I can call or echo the Ajax same value '+arrData[1]+' that is calculated on line 24 of the Javascript Function.
Here is the Authorize.net HTML form that i am using to Submit.
<?php
require_once 'anet_php_sdk/AuthorizeNet.php'; // Include the SDK you downloaded in Step 2
$fname = $bookingReservationObj->getReservationName();
$api_login_id = $bookingSettingObj->getAuthorizeAPI();
$transaction_key = $bookingSettingObj->getAuthorizeTXN();
$amount = // I am not sure what to put here to call Ajax value that i need answer
$fp_timestamp = time();
$fp_sequence = "123" . time(); // Enter an invoice or other unique number.
$fingerprint = AuthorizeNetSIM_Form::getFingerprint($api_login_id,
$transaction_key, $amount, $fp_sequence, $fp_timestamp)
?>
<!-- authorize.net form -->
<form action='https://test.authorize.net/gateway/transact.dll' METHOD='POST' name="authorize_form" style="display:inline">
<!-- Authorize Configuration -->
<input type='hidden' name="x_login" value="<?php echo $api_login_id ?>" />
<input type='hidden' name="x_fp_hash" value="<?php echo $fingerprint?>" />
<input type='hidden' name="x_fp_timestamp" value="<?php echo $fp_timestamp?>" />
<input type='hidden' name="x_fp_sequence" value="<?php echo $fp_sequence?>" />
<input type='hidden' name="x_version" value="3.1">
<input type='hidden' name="x_show_form" value="payment_form">
<input type='hidden' name="x_test_request" value="true" />
<input type='hidden' name="x_method" value="cc">
<input type='hidden' name="x_first_name" value="<?php echo $fname ?>">
<input type='hidden' name="x_last_name" value="<?php echo $fname ?>">
<input type='hidden' name="x_email" value="<?php echo $fname ?>">
<input type='hidden' name="x_phone" value="<?php echo $fname ?>">
<input type='hidden' name="x_description" value="<?php echo 'Cruzz Booking '; ?>">
<!--slots purchased-->
<div id="slots_purchased">
</div>
<input type='hidden' name="x_receipt_link_method" value="link">
<input type='hidden' name="x_receipt_link_text" value="Click here to return to our home page">
<input type='hidden' name="x_receipt_link_URL" value="<?php echo site_url('')."/?p=".$post->ID."&authorize_confirm=1"; ?>">
<input type="hidden" name=" x_cancel_url" value="<?php echo site_url('')."/?p=".$post->ID; ?>">
<input type="hidden" name="rm" value="POST">
</form>
How should I start?

In your code $wbc must be your jQuery Object, it's normally just $. If for some reason $wbc does not refer to the jQuery Object you have a problem. ajax is a method of the jQuery Object. The ajax method takes an Object Literal as its argument. A JavaScript Object Literal is really an Associative Array. url is a property of the Object You are passing in as an argument. The value for that property is '<?php echo plugins_url('my_plugin/public');?>/ajax/getSlotInfo.php?slot_id='+ $wbc(this).val(), which you must be running through your server, so this must be a .php file. To use plugins_url() you must be using WordPress.
You are using the $wbc.ajax({type:'GET'}) method so additional information can be sent like 'getSlotInfo.php?slot_id='+$wbc(this).val()+'&anotherProperty=anotherValue. So the & seperates properties.
See where your code says getSlotInfo.php?slot_id=? The slot_id part can be accessed with $_GET['slot_id'] on the page your url is sending information to, which happens to be getSlotInfo.php. You can use <?php $varHere = $_GET['slot_id'] ?> on your getSlotInfo.php page to create a PHP variable that holds jQuery.
If you had a dataType: 'json' in your ajax method Object argument, like $wbc.ajax({dataType: 'json'}), then you could use PHP to generate JavaScript Object Notation, which is an Associative Array. The PHP method of choice for this on your getSlotInfo.php page will be json_encode(). As long as you print or echo json_encode() with PHP, when you have a successful response the data argument of $wbc.ajax({success: function(data){}}) will hold the Associative Array, which can be used with JavaScript's for in loop like:
for(var i in data){
var property = i;
var value = data[i];
}
Your PHP, on getSlotInfo.php, that sends to this JavaScript Object Literal might look like:
<?php
if(isset($_GET['slot_id']) && isset($_GET['anotherProperty'])){
$ary = array('prop1' => $_GET['slot_id'], 'prop2' => $_GET['anotherProperty']);
echo json_encode($ary);
}
else{
header('LOCATION: urlOfChoice.html');
}
?>
Using this methodology there is no reason to split the data since its not a string response. Instead it's already JSON.
This might help you understand the post method Jquery AJAX post to PHP.

Related

how to use php to get data from a input form preset data?

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.

Passing an array to another page (Form)

I have the following array and form on page1.php:
$my_array = array("Volvo", "BMW", "Toyota");
echo " <form id=\"my_form\" action=\"page2.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"hidden\" name=\"id\" value=\"10\">
<input type=\"hidden\" name=\"input_name\" value=\"".serialize($my_array)."\" />
Send </form>";
On the page2.php I want to print_r the array:
$id = $_POST['id'];
$passed_array = unserialize($_POST['input_name']);
print_r($passed_array);
Why I can't receive my_array on page2? I can't see the mistake I made!
PS: I received id on page2.
i'm glad #ksealey pointed out a more proper method of doing this, but for the sake of answering the question...the reason it's not working is that the serialize alone is not enough to prevent the invalid html. see result of what the serialize leaves in the html:
so you need to be sure the html you produce is valid. you might use encoding like base64 to produce safe html:
echo " <form id=\"my_form\" action=\"\" method=\"post\"";
echo "enctype=\"multipart/form-data\">";
echo "<input type=\"hidden\" name=\"id\" value=\"10\">";
echo "<input type=\"hidden\" name=\"input_name\" ";
echo "value=\"".base64_encode(serialize($my_array))."\" />";
then you can just add the decode to your output:
$passed_array = unserialize(base64_decode($_POST['input_name']));
print_r($passed_array);
If there is data to be passed from page to page use a session
<?php
//Page 1
session_start();
$value = 'Value from page 1';
$_SESSION['page_1_value'] = $value;
?>
<?php
//Page 2
session_start();
echo 'Value from page 1: '.$_SESSION['page_1_value'];
$_SESSION = array(); //If you want to wipe the session data after
OR, pass as value params that get cleaned, JSON object maybe?
<form id="my_form" action="page2.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="10">
<input type="hidden" name="input_name" value="<?php echo json_encode($my_array); ?>" />
<a href="javascript:{}" onclick="document.getElementById('my_form').submit(); return false;">Send</a
</form>
<?php
//Page 2
$object = json_decode(strip_tags(stripslashes($_POST['input_name'])));
var_dump($object);
I will say the first answer is safer.
This is the HTML that your first page is generating:
<input type="hidden" name="input_name" value="a:3:{i:0;s:5:" volvo";i:1;s:3:"bmw";i:2;s:6:"toyota";}"="">
One easy solution would be to replace your double quotes in
value=\"".serialize($my_array)."\"
with single quotes as so:
value='" . serialize($my_array) . "'
or you can escape the quotes in your serialized array as so:
value=\"". htmlspecialchars(serialize($my_array))."\"
I will just add my 2 cents in here :)
You may want to use a framework of some sort as this will ease the job for you a lot with situations like this (or similar). For example with Codeigniter framework you could have a form (view) that sends data to controller and in controller you could just grab the whole array as so:
$data = $this->input->post('array');
$data[0] should == 'Volvo'
So view:
<?php $my_array = array("Volvo", "BMW", "Toyota"); ?>
<form id="my_form" action="<?php echo site_url(controller_name/controller_function)" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="10">
<input type="hidden" name="input_name" value="".serialize($my_array)."" />
Controller:
public function foo() {
$data = $this->input->post('array');
for($i=0; $i<sizeof($data); $i++) {
echo $data[$i];
}
}

PHP form output multiple fields duplicate

Hello i want to create this array output from FORM post with PHP
Here my FORM, duplicate with javascript the DIV data with class .duplicated
<?php print_r($_POST); ?>
<form method='post'>
<input name='group_name'/>
<input name='group_'/>
<div class='duplicated'>
<input name='group_values[][name]'/>
<input name='group_values[][price]'/>
</div>
<div class='duplicated'>
<input name='group_values[][name]'/>
<input name='group_values[][price]'/>
</div>
</form>
This form return this array
It's because a empty bracket like that makes php / html create a new "key/value", make your
<input name='group_values[][name]'/>
<input name='group_values[][price]'/>
Into:
<input name='group_values[1][name]'/>
<input name='group_values[1][price]'/>
And you should see a difference, if you need it to happen by itself you can use a varaible, set it to 0 or what ever value you want your array to start from, and give it +1 each time you want a new "group" Like so:
<?php $i = 0; //Initializes the variable ?>
<input name='group_values[<?php echo $i; ?>][name]'/> //Array key = 0
<input name='group_values[<?php echo $i; ?>][price]'/> //Array key = 0
<?php $i++; //Increases the variable with 1 ?>
<input name='group_values[<?php echo $i; ?>][name]'/> //Array key = 1
<input name='group_values[<?php echo $i; ?>][price]'/> //Array key = 1
Of course it can be done in a more efficient / smarter way, but this is just to give you a basic example
For Javascript it will depend on how you duplicate the data, but the idea is basically the same
var key = 0;
var duplicateInput1 = "<input name='group_values[" + key + "][name]'/>" +
"<input name='group_values[" + key + "][price]'/>";
key++;
var duplicateInput2 = "<input name='group_values[" + key + "][name]'/>" +
"<input name='group_values[" + key + "][price]'/>";
var duplicateForm = duplicateInput1.concat(duplicateInput2);

POST throwing undefined index on every var

I'm defining POST here:
else if(isset($_POST["Edit"])){
$result_set = $sqlConn->query("SELECT Art, Ime, Cijena, Kol FROM permatable WHERE Art='{$_POST["Art"]}' LIMIT 1");
$Item = $result_set->fetch_array();
$_POST["Art"] = $Item["Art"];
$_POST["Ime"] = $Item["Ime"];
$_POST["Cijena"] = $Item["Cijena"];
$_POST["Kol"] = $Item["Kol"];
header("Location: EditP.php");
}
Now the Post "Edit" and the if statment is being called just fine. I've also checked the query and it returns everything it needs to.
Now on the header location I get undefined index on all of these vars and thats coming from the following code:
echo "<input type='text' placeholder=".$_POST["Art"]." name='Art'>
<input type='text' placeholder=".$_POST["Ime"]. "name='Ime'>
<input type='text' placeholder=".$_POST["Cijena"]." name='Cijena'>
<input type='text' placeholder=".$_POST["Kol"]." name='Kol'>";
Am I doing something wrong? I can't see any mistakes myself and this has been bothering me for a while now.
That won't work.
you can't send POST with header location
you can try to add them to your url
foreach($item as $key=>$value)
{
$items .= $key."&".$value ;
}
header("Location: EditP.php?".$items);
and in the edit.php page
echo "<input type='text' placeholder=".$_GET["Art"]." name='Art'>
<input type='text' placeholder=".$_GET["Ime"]. "name='Ime'>
<input type='text' placeholder=".$_GET["Cijena"]." name='Cijena'>
<input type='text' placeholder=".$_GET["Kol"]." name='Kol'>";
You cannot redirect the user w/ POST variables. It will not work. Read here. The best way to do it is to create a form and then automatically submit it via JavaScript as soon as the page loads. Example:
<form id="my_form" action="http://example.com" method="post">
<input type="hidden" name="name" value="<?php echo htmlspecialchars($name); ?>">
<input type="hidden" name="email" value="<?php echo htmlspecialchars($email); ?>">
<input type="hidden" name="etc" value="<?php echo htmlspecialchars($etc); ?>">
</form>
<script type="text/javascript">
//Our form submission function.
function submitForm() {
document.getElementById('my_form').submit();
}
//Call the function submitForm() as soon as the page has loaded.
window.onload = submitForm;
</script>
$result_set = $sqlConn->query("SELECT Art, Ime, Cijena, Kol FROM permatable WHERE Art='($_POST["Art"])' LIMIT 1");
Try changing curly braces to small braces.
Well, I used SESSION at the end so I just changed the code to following:
$result_set = $sqlConn->query("SELECT Art, Ime, Cijena, Kol FROM permatable WHERE Art='{$_POST["Art"]}' LIMIT 1");
$Item = $result_set->fetch_array();
$_SESSION["Art"] = $Item["Art"];
$_SESSION["Ime"] = $Item["Ime"];
$_SESSION["Cijena"] = $Item["Cijena"];
$_SESSION["Kol"] = $Item["Kol"];
header("Location: EditP.php");
And for the EditP:
echo "<input type='text' placeholder=".$_SESSION["Art"]." name='Art'>
<input type='text' placeholder=".$_SESSION["Ime"]. "name='Ime'>
<input type='text' placeholder=".$_SESSION["Cijena"]." name='Cijena'>
<input type='text' placeholder=".$_SESSION["Kol"]." name='Kol'>";

jQuery Get Value From Looping in PHP

I'm using jQuery. Now I want to get value base on ID value from textbox loop.
Example :
<?php
while
{
$id = $d['id'];
?>
<input type="text" name="text" id="txt" value="<?php echo $id; ?>"/>
<input type="submit" class="btn_confirms" id="txt<?php echo $id; ?>" value="Go"/>
<?php
}
and jQuery like this:
$(function() {
$(".btn_confirms").click(function()
{
var txt_id = $('#txt').val();
alert(txt_id);
}
});
Example if I have 3 data.
The problem is, when I click button Go, it just show first value of PHP loop. Another button Go 2 & 3 is show same value.
Any help, please.
You can't have duplicate IDs on the page, they should be unique. For repeating elements either use classes, or make IDs unique (like you're doing for the buttons).
Something like this should work:
<input type="text" name="text" id="txt<?php echo $id; ?>" value="<?php echo $id; ?>"/>
<input type="submit" class="btn_confirms" id="button<?php echo $id; ?>" value="Go"/>
Then, to fetch the id of the input field from the click function, you can do something like this:
$(".btn_confirms").click(function()
{
var txt_id = $(this).attr('id').replace('button', 'txt');
var value = $('#'+txt_id).val();
alert(txt_id + ": " + value);
})
See it here: http://jsfiddle.net/shomz/R9s2R/
you can try this
<?php
while
{
$id = $d['id'];
?>
<input type="text" name="text" id="txt<?php echo $id; ?>" value="<?php echo $id; ?>"/>
<input type="submit" class="btn_confirms" id="btn<?php echo $id; ?>" textbox_id="#txt<?php echo $id; ?>" value="Go"/>
<?php
}
?>
<script>
$(function() {
$(".btn_confirms").click(function()
{
var textbox_id = $(this).attr('textbox_id');
var textbox_val = $(textbox_id).val();
alert(textbox_val);
});
});
</script>
DEMO

Categories