POST throwing undefined index on every var - php

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'>";

Related

How to make a cookie save and get system?

I am making a system that saves someone's UDID (iOS) and outputs it back in the original input field.
It is for an iOS web-app I am working on. I have tried this:
<?php
$udid = $_POST['udid'];
if(empty($udid)){
$udid = $_COOKIE['udid'];
} else {
$udid = $_POST['udid'];
}
?>
<form class='form-horizontal well' action='#' method='post'>
<input type='text' name='udid' class='input-large' placeholder="udid" value='<?php $udid ?>'>
<button type='submit' id='submit' class='badge-primary'>Save</button>
</form>
<?php
setcookie("udid", $udid, time()+31536000000, "/");
?>
I need the user's udid to be saved and then outputted in the input field. When I ran this, the UDID didn't display in the input field. What have I done wrong?
I think you error is on the line below:
<input type='text' name='udid' class='input-large' placeholder="udid" value='<?php $udid ?>'>
Change it to:
<input type='text' name='udid' class='input-large' placeholder="udid" value='<?= $udid ?>'>
Notice I changed: <?php $udid ?> to <?= $udid ?>
This way your PHP script will echo the variable.
In fact, <?= is just a shorthand for <?php echo since php5.4
You have to echo the variable $udid
value='<?php echo $udid ?>'
Make sure the variable $udid not empty else the cookie never assigned.

How can i output Ajax Value to a PHP Variable?

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.

Post form values where Field Names are dynamically created from a loop?

I have a page that is created dynamically from the information that a user has submitted on a previous page. For example on page 1, the user inputs some department names. They can enter as many as they want. On page 2, multiple sections are created for each department that was entered on page one. Inside each of these sections are going to be forms, I currently have it set up so that the names of the forms are created using a variable $a. I need to know how to post these items once the submit button in each section is clicked. I have tried several different ways and nothing is working. I want it so that ONLY the items with the same $a value as the submit button's $a get posted.
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a;?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a;?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
<?php
echo "</div>";
}
?>
*EDIT I need everything to be in one form because the point of the page is to add up all of the values that will be inserted into each of the individual sections later. *
**EDIT 2 :
I figured it out using #dirt 's jquery suggestion.
HTML:
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
<div id=$a>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a ?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a ?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<button type="submit" name="areaSub" value="<?php echo $a ?>" />Add</button>
<?php
echo "</div></div>";
} ?>
jQuery:
<script>
$(document).ready(function() {
$('#<?php echo $a ?>').submit(function() {
.post("include/action.php")
});
});
</script>
PHP:
if(isset($_POST['areaSub'])) {
$areaval = intval($_POST['areaSub']);
$area = mysql_real_escape_string($_POST["dep_area".$areaval.""]);
list($area_id, $area_name) = explode(',', $area, 2);
$bdep = mysql_real_escape_string($_POST["bdep".$areaval.""]);
echo $areaval;
echo $area_name;
echo $bdep;
}
EDIT: If its a single form with multiple sections and you don't want to trim out unwanted form data after the POST then I think you must use jQuery to trim the form values prior to the post to the server, so see my jQuery portion below for a crued example of how you would go about only posting the data for the selected button.
Short answer would be to use the Name/Value attributes of the submit button and evaluate that once posted. Multiple buttons with the same name can have different values and the values don't have to be the labels.
Example:
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<?php
# _POST:
if (isset($_POST['submit']) && $_POST['submit'] == '1') {
echo 'Department 1';
}
if (isset($_POST['submit']) && $_POST['submit'] == '2') {
echo 'Department 2';
}
?>
You could also use jQuery to get all elements contained in a certain Div ID. Something like (this is rough idea):
<div id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
</div>
jQuery:
$('#<?php echo $a; ?>').submit(function() {
do_something_with_form_$a
});
I'm not sure if I understand completely... but the issue you're having is that, when a user hits the 'submit' button for a given set of values (a given department), it submits ALL of the data on the page? And you only want the input fields for that specific area submitted?
Section off forms with the tag:
<form> </form>
So, you'll have multiple areas:
while(...) {
<form method="..." name="form $a">
<input name="... $a">
<input name="... $a">
...
<submit>
</form>
}
(Obviously this is pseudocode, adjust accordingly)

Strange output from variable to hidden form field

Below is a function that outputs a form with existing users from a database, with checkboxes and a submit button. The user choose one or several users to be removed and submits the form. What i'm working on right now is to implement a confirmation box in js ("Are you sure you want to remove..."), which shall contain the users that the user wants to remove.
By that reason I'm putting in the usernames in a hidden field that the js function will retrieve the username(s) from. The problem is that not only the usernames are put into the hidden input fields value attribute, but also several input fields as well (!?). If I hard code in for example 'username1,username2' in the attribute it works as it should, but not if I use the variable $users.
public function ShowUsers($userArray) {
$userIdArray = $userArray[0];
$userNameArray = $userArray[1];
$users = implode(",", $userNameArray);
echo $users; // username1,username2...
$nrOfUsers = count($userIdArray);
for ($i = 0; $i < $nrOfUsers; $i++) {
$users .= "<label for='$userIdArray[$i]'>
$userNameArray[$i]
<input type='checkbox' name='$this->_checkBox' value='$userIdArray[$i]' /><br/>
</label>";
}
$userList = "<div class='userList'>
<form id='form3' method='post' action=''>
<fieldset>
<p>Existing users</p>
$users
<input type='hidden' value='$users' />
<input type='submit' id='$this->_submitRemove' name='$this->_submitRemove' Value='Ta bort' />
</fieldset>
</form>
</div>";
return $userList;
}
The output is the following:
<input type='hidden' value='username1,username2<label for='47'>
username1
<input type='checkbox' name='check[]' value='47' /><br/>
</label><label for='50'>
username2
<input type='checkbox' name='check[]' value='50' /><br/>
</label>' />
I just don't get it why this happens? The content of $users (in this case 'username1' and 'username2') is there as expected, but why is the input and label tags put into the value attribute?
The problem is in your for loop. There you're appending all that HTML to the variable $users which already is $users == username1,username2. If you do echo $users; or even var_dump($users); just after you've finished the for loop, you'll see.
What are you trying to achieve in the for loop indeed? Did you rather mean
for ($i = 0; $i < $nrOfUsers; $i++) {
echo "<label for='$userIdArray[$i]'>
$userNameArray[$i]
<input type='checkbox' name='$this->_checkBox' value='$userIdArray[$i]' /><br/>
</label>";
}

Order ofQuery with AJAX PHP and MySQL

Got a bit of a confusing situation, I have a form on my webpage that allows a user to enter information into a database...
Form
<form id="insertbill">
Total <input type="text" id="total" name="total" /><br />
Bill name<input type="text" id="bill-name" name="bill-name" /><br />
bill descriptiion <input type="text" id="bill-description" name="bill-description" /><br />
bill colour<input type="text" id="bill-colour" name="bill-colour" />
<input type="button" value="submit" onClick="insertBill();" />
</form>
This form then send the information via AJAX to my php which then inputs it into my DB
AJAX
function insertBill()
{
$.post('insert_bill.php', $('#insertbill').serialize(),
function(data) {
$('#bills').append(data);
});
};
PHP
$uid = $_SESSION['oauth_id'];
$bill = mysql_real_escape_string($_POST['total']);
$billname = mysql_real_escape_string($_POST['bill-name']);
$billdescription = mysql_real_escape_string($_POST['bill-description']);
$billcolour = mysql_real_escape_string($_POST['bill-colour']);
#Insert Record
$query = mysql_query("INSERT INTO `outgoings` (user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('$uid', '$bill', '$billname', '$billdescription', '$billcolour')") or die(mysql_error());
Once this is done, the data is then returned to the webpage, with another form that allows the user to update the record...
Returned data/form
Print "<tr>";
Print "<th>total:</th> <td>".$bill . "</td> ";
Print "<th>bill name:</th> <td>".$$billname . "</td> ";
Print "<th>bill deposit:</th> <td>".$billdescription . "</td> ";
Print "<th>colour:</th> <td>". $billcolour . " </td></tr>";
echo "<th>edit:</th> <td>
<form id='bill-upd'>
<input type='hidden' value='". $billname."' name='billid' id='billid''>
Total <input type='text' id='total' name='total' /><br />
Bill name<input type='text' id='bill-name' name='bill-name' /><br />
bill descriptiion <input type='text' id='bill-description' name='bill-description' /><br />
bill colour<input type='text' id='bill-colour' name='bill-colour' />
<input type='button' value='submit' onClick='updateBill();' />
</form>
</td>";
My problem is that the returned form doesn't update, this is because I need to somehow find the id of the record that was inserted, place it into my form to be returned I think... I hope this isn't too confusing, but has anybody a better way of doing this without reloading the page?
here's what what you could include on your, insert_bill.php, view page:
<script>
var json=<?
$arr=array($bill, $billname, $billdescription, $billcolour);
echo json_encode($arr); ?>;
$('tr td:nth-child(0)').html(json[0]);
$('tr td:nth-child(1)').html(json[1]);
$('tr td:nth-child(2)').html(json[2]);
$('tr td:nth-child(3)').html(json[3]);
</script>
I guess the one outstanding issue is the "id" you says gets returned from your database. Can you explain a little further? Are their multiple forms on your insert_bill.php page? Regardless, you could put that $id into the array and feed it into and html() function like I did with the other variables.
You need to return the data from the database and then change, i imagine if you just need the id you must do.
in PHP
echo mysql_last_insert_id(); // so you get the last inserted id and "return" to the JS
In JS, inside the function data
You get the echo as a return and change the id
and then $("#billid").val(data)
I hope it help you

Categories