jQuery generated elements not recognized on $_POST - php

I'm developing a Wordpress plugin using PHP and jQuery, the function below is called when the <select> input is changed, so far it works as intended and the inputs are generated properly but when I submit the form, the generated elements are undefined when called in $_POST.
<?php
function random_event() {
global $wpdb;
//Table for all the event details
$tablename = $wpdb->prefix."random_event";
// Table to store all banner stores
$tablename2 = $wpdb->prefix."random_event_banner_stores";
//Table for store all poster
$tablename4 = $wpdb->prefix."random_event_poster";
// Table storing all user registrations
$tablename3 = $wpdb->prefix."random_event_winners";
//Junction table to map the poster to banner store
$tablename5 = $wpdb->prefix."random_event_poster_banner";
//Junction table to map the poster to event
$tablename6 = $wpdb->prefix."random_event_poster_event";
$tablename5 = $wpdb->prefix."random_event_poster_banner";
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
$update_this_event = -1;
$banner_stores = [];
//Deletion
if(isset($_POST['delete_event'])) {
$event_id = esc_sql($_POST['event_id']);
$sql = "DELETE from $tablename WHERE id= '" . $event_id . "'";
try{
$event = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
$banner_store_id = esc_sql($_POST['banner_id']);
$name = esc_sql($_POST['banner_store_name']);
$description = esc_sql($_POST['banner_store_description']);
$location_note = esc_sql($_POST['banner_store_location_note']);
$address = esc_sql($_POST['banner_store_address']);
$status = esc_sql($_POST['banner_store_status']);
$sql = "UPDATE $tablename SET name = '" . $name . "'
, description = '" . $description . "'
, location_note = '" . $location_note . "'
, address = '" . $address . "'
, status = '" . $status . "' WHERE id = '" . $banner_store_id . "'";
try{
$participants = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['select_update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
// $pssql = "select * from $tablename2";
// $banner_stores = $wpdb->get_results($pssql);
$pssql = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.store_id is null";
// $pssql = "select * from $tablename2";
$banner_stores = $wpdb->get_results($pssql);
$pssql2 = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.id = '".$update_this_event."'";
$current_banner_store = $wpdb->get_results($pssql2);
if(count($current_banner_store) != 0) {
array_push($banner_stores, $current_banner_store[0]);
}
$poster_sql = "select ap.*, a.name as poster_name, ap.qty as qty from $tablename6 as ap inner join $tablename4 as a on a.id = ap.poster_id where ap.event_id = $update_this_event";
$poster_event = $wpdb->get_results($poster_sql);
$poster_petone = [];
foreach($results as $result) {
if($result->id == $update_this_event) {
$poster_sql = "select a.* from $tablename5 as ap inner join $tablename4 as a on a.id = ap.poster_id where banner_store_id = ".$result->store_id;
$poster_petone = $wpdb->get_results($poster_sql);
}
}
}else if(isset($_POST['cancel_update_event'])){
$update_this_event = -1;
}else if (isset($_POST['save_update_event'])) {
$update_this_event = intval(esc_sql($_POST['event_id']));
$title = esc_sql($_POST['title']);
$qty = 0;
$description = esc_sql($_POST['description']);
$prize = esc_sql($_POST['prize']);
$event_code = esc_sql($_POST['event_code']);
$event_from = esc_sql($_POST['event_from']);
$event_to = esc_sql($_POST['event_to']);
$banner_store_id = esc_sql($_POST['banner_store_id']);
if(isset($_POST['poster_ids'])){
$poster_ids = $_POST['poster_ids'];
$poster_qtys = $_POST['poster_qty'];
}
$query = "UPDATE $tablename set title='$title',description='$description',event_code='$event_code',valid_from='$event_from',valid_to='$event_to',store_id='$banner_store_id', prize = '$prize' ";
$query .= "where id = $update_this_event";
$result_insert = $wpdb->query($query);
$delete_query = "delete from $tablename6 where event_id = $update_this_event";
$wpdb->query($delete_query);
for($i = 0; $i < count($poster_ids); $i++) {
$poster_id = esc_sql($poster_ids[$i]);
$poster_qty = esc_sql($poster_qtys[$i]);
$poster_query = "INSERT INTO $tablename6 (event_id,poster_id, qty) values ";
$poster_query .= "('$update_this_event','$poster_id','$poster_qty');";
$poster_insert = $wpdb->get_results($poster_query);
$poster_result = $wpdb->insert_id;
}
$update_this_event = -1;
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
}
?>
<style type="text/css" emb-not-inline="">
.table-container {
width: 100%;
max-width: 100%;
overflow-x: auto;
}
.hidden {
display: none;
}
.banner-button {
background-color: #ffffff;
border-radius: 5px;
padding: 5px;
font-size: 13px;
min-width: 75px;
}
table {
border: none;
text-align: center;
}
table tr:nth-child(even) {
background-color: #dddddd;
}
table tr:nth-child(odd) {
background-color: #ffffff;
}
table th {
background-color: #23282d;
color: #ffffff;
}
table th:first-child{
border-radius: 20px 0px 0px 0px;
}
table th:last-child{
border-radius: 0px 20px 0px 0px;
}
table {
border-radius: 20px 20px 0px 0px;
}
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<h1>View All events</h1>
<br/>
<div class="table-container" style="
width: 100%;
max-width: 100%;
overflow-x: auto;
">
<table cellpadding="10" border=1 style="border-style: solid #AAA">
<tr>
<th>Title</th>
<th>Description</th>
<th>Prize</th>
<th>event Code</th>
<th>banner Store</th>
<th>poster Qty</th>
<th>Validity</th>
<th>QR code</th>
<th>Action</th>
</tr>
<?php
foreach($results as $result) {
if($update_this_event == $result->id) { ?>
<tr>
<form method="post" name="formtest1" id="formtest1">
<td valign="top"><input type="text" name="title" value="<?php echo $result->title ?>"/> </td>
<td valign="top"><input type="text" name="description" value="<?php echo $result->description ?>"/> </td>
<td valign="top"><input type="text" name="prize" value="<?php echo $result->prize ?>"/> </td>
<td valign="top"><input type="text" name="event_code" value="<?php echo $result->event_code ?>"/> </td>
<td valign="top">
<!-- <select onChange="changebanner(this)" id="banner_store_id" name="banner_store_id"> -->
<select id="banner_store_id" name="banner_store_id">
<?php
foreach($banner_stores as $pstore) {
if($result->banner_id == $pstore->id) {
?>
<option SELECTED value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}else {
?>
<option value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}
}
?>
</select>
</td>
<td valign="top">
<div id="poster_div">
<table border="0" cellpadding=5>
<?php
if(count($poster_event) == 0) {
for($i = 0; $i < count($poster_petone); $i++)
{
?>
<tr>
<td>
<input type="hidden" name="poster_ids[]" value="<?php echo $poster_petone[$i]->id?>"><?php echo $poster_petone[$i]->name?>
</td>
<td>
<input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_petone[$i]->qty ?>">
</td>
</tr>
<?php
}
}else {
for($i = 0; $i < count($poster_event); $i++)
{
?>
<tr>
<td><input type="hidden" name="poster_ids[]" value="<?php echo $poster_event[$i]->poster_id?>"><?php echo $poster_event[$i]->poster_name?></td>
<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_event[$i]->qty?>"></td>
</tr>
<?php
}
}?>
</table>
</div>
</td>
<td valign="top"><input id="event_from" name="event_from" type="text" value="<?php echo $result->valid_from ?>"/> - <input name="event_to" id="event_to" type="text" value="<?php echo $result->valid_to ?>"/> </td>
<td valign="top"></td>
<td valign="top">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> ">
<input type="submit" name="save_update_event" value="save" class="banner-button">
<input type="submit" name="cancel_update_event" value="cancel" class="banner-button">
</td>
</form>
</tr>
<?php
} else {
?>
<tr>
<td valign="top"><?php echo $result->title ?> </td>
<td valign="top"><?php echo $result->description ?> </td>
<td valign="top"><?php echo $result->prize ?> </td>
<td valign="top"><?php echo $result->event_code ?> </td>
<td valign="top"><?php echo $result->banner_name ?> </td>
<td valign="top"><?php get_poster_of_event($result->id ) ?> </td>
<td valign="top"><?php echo $result->valid_from ?> - <?php echo $result->valid_to ?></td>
<td valign="top"><?php generate_random("https://generic.com/event/?random=".$result->event_code, $result->title) ?> </td>
<td valign="top">
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="delete_event" value="delete" class="banner-button"/>
</form>
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="select_update_event" value="update" class="banner-button"/>
</form>
</td>
</tr>
<?php
}
}
?>
</table>
</div>
<script>
let jQueryNC = jQuery.noConflict();
jQueryNC( function() {
jQueryNC( "#event_to" ).datepicker({ dateFormat: 'yy-mm-dd' });
jQueryNC( "#event_from" ).datepicker({ dateFormat: 'yy-mm-dd' });
} );
jQueryNC("body").on("change", "#banner_store_id", function() {
changebanner(jQueryNC(this));
});
function changebanner(e){
let jQueryNC = jQuery.noConflict();
jQueryNC( "#poster_div" ).html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
let value = jQueryNC("#banner_store_id").val();
console.log(e.value);
formData.append('poster_id', value);
formData.append('action', 'get_poster');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let posters = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for(let i = 0; i < posters.length; i++)
{
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="poster_ids[]" value="'+posters[i].id+'">'+posters[i].name+'</td>';
htmldiv += '<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="'+posters[i].qty+'"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#poster_div").html(htmldiv);
}
}
</script>
<?php
} ?>
Clarification: when the select input is not changed, the inputs inside container div are recognized upon submitting without any errors, but when the contents of container div are changed via changebanner; the new inputs and tables are created but if it is submitted, the inputs like poster_ids[] is not recognized by $_POST['poster_ids']
EDIT added the entire code in hopes of clarifying the problem

I tried to explain the issue in my comments but maybe it will be easier to see here.
Your initial form on page load has a bunch of inputs etc in it, including some poster_ids and poster_qty.
If you submit that form, by clicking the submit button, a standard HTML form submission via POST happens. All the inputs that exist in the form on page load will be sent in the request, and your PHP will get all of them.
But if you don't submit the form, and instead change the selected #banner_store_id option, some Javascript takes over. That JS will do a few things:
Create an empty formData object, ignoring everything currently in your form;
Add 2 new key/value pairs to that formData
POST those 2 values to your PHP. Note this is not a standard HTML POST like the one that happens when you click submit, it is an AJAX POST. It is essentially independent of the <form> on the page, and it will only POST the fields from the form if you specifically add them. The code you have does not do that, and so does not include any of your existing form fields.
If you try to use $_POST['poster_ids'] in the PHP which receives this JS POST, it will fail, because those fields were not in the request. The only things there are a poster_id and an action.
If you do want to include all the fields in your form in the data you POST via JS when changing #banner_store_id, you need to create a formData with the form itself, as shown in the docs:
let myForm = document.getElementById('formtest1');
let formData = new FormData(myForm);
If you do this, then all the inputs on your form are bundled up and included in that formData, and just like with the normal POST will all be sent to your PHP.
Here's the relevant part of your code, commented to explain it further:
function changebanner(e) {
// Create a new FormData object - **NOTE** it is empty! You have not passed
// in your existing form, so none of the form inputs already on the page are
// in FormData. If you POSTed it right away $_POST would be completely empty.
let formData = new FormData();
// Now add 2 items to it
formData.append('poster_id', value);
formData.append('action', 'get_poster');
// Now make your POST, and send formData, which has just those 2 items
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
// The POST is done, you sent poster_id and action and nothing else to your PHP
}

Try taking out the onchange(this) in the select and instead use the jQuery on.("change").
Without seeing the exact error or what you have tried it is hard to say exactly but trying to access a variable that has not be created yet often gives an undefined because you are trying to access it before it exists. By using the jQuery on function you can find things added after DOM has loaded.
Good luck.
$("body").on("change", "#data_store_id", function() {
changeSELECTED($(this));
});
function changeSELECTED(e) {
let jQueryNC = jQuery.noConflict();
jQueryNC("#container_div").html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
formData.append('data_id', e.value);
formData.append('action', 'get_data');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/adminfolder/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let datas = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for (let i = 0; i < datas.length; i++) {
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="data_ids[]" value="' + datas[i].id + '">' + datas[i].name + '</td>';
htmldiv += '<td><input type="text" name="data_qty[]" placeholder= "Qty Allocation" value="' + datas[i].qty + '"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#container_div").html(htmldiv);
}
}
<select id="data_store_id" name="data_store_id">
<?php
foreach($data_stores as $dstore) {
if($result->data_id == $dstore->id) {
?>
<option SELECTED value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}else {
?>
<option value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}
}
?>
</select>

Related

PHP / AJAX: Delete unsuccessful at AJAX

Currently, I created a system that has AJAX function. To be more clear, below is my current process flow:
1) dashboard.php will display 3 select option which is team, time from and time to
2) user need to complete all 3 select option and click button 'search'. At this point where AJAX (range.php).
3) All data row will be listed and each data have a delete button. User can delete data based on data row.
My problem is, the data is not deleted.
Below is my current code.
dashboard.php
<select class="form-control" name="team" id="team">
<option value="">Please select...</option>
<?php foreach ($data as $row2): ?>
<option value= <?php echo $row2["team_id"]; ?> <?php echo (($_GET["team"] ?? '') == $row2["team_id"]) ? 'selected' : ''; ?> ><?php echo $row2["fullname"]; ?></option>
<?php endforeach ?>
</select>
<td width="1%"></td>
</td>
<td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" value = '<?php echo $_GET["from"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" value = '<?php echo $_GET["to"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="10%"><input type="button" name="range" id="range" value="Search" class="btn btn-primary"><td>
</tr>
</table><br>
<div id = "dashboard">
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker().attr("autocomplete", "off");;
$("#to").datepicker().attr("autocomplete", "off");;
});
$('#range').click(function(){
var from = $('#from').val();
var to = $('#to').val();
var team = $('#team').val();
if(from != '' && to != '' && team != '')
{
$.ajax({
url:"range.php",
method:"POST",
data:{from:from, to:to, team:team},
success:function(data)
{
$('#dashboard').html(data);
}
});
}
else
{
alert("Please select both team and date range");
}
});
if($('#from').val() && $('#to').val() && $('#team').val()){
$('#range').click();
}
});
</script>
range.php (AJAX)
<?php
require_once "../../../config/configPDO.php";
require_once "../../../config/check.php";
$email = $_SESSION['login_user'];
if(isset($_POST["from"], $_POST["to"], $_POST["team"]))
{
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0)
{
echo'
<form method="post" action="">
<div class="row" style="height: 300px; overflow-y: scroll;">
<div class="col-lg-12 grid-margin stretch-card">
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th>id</th>
<th>Date</th>
<th>Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
while($row = $sql->fetch(PDO::FETCH_ASSOC))
{
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td align="center">';
echo '<a class="btn-view btn-primary btn-sm" href="view_task/view_task.php?report_id='. $report_id .'" data-toggle="tooltip">View</a></td>';
echo '<td align="center">';
echo '<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">';
echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
delete_ajax.php
<?php
require_once '../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$sql = "DELETE FROM ot_report WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php?from='".$_POST["from"]."'&to='".$_POST["to"]."' &team='".$_POST["team"]."'");
?>
Can anyone knows what is the problem? The data cannot deleted!. Help anyone
maybe this is because in the range.php file you have 2 form tags
first is outside while function
<form method="post" action="">
and second one is in while function
<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">
try removing the first one

How to pass extra dynamic rows created from jquery to contrller in array codeigniter

This is my code, where a user can add dynamic rows by clicking add more link.
But when I print
print_r($this->input->post('name1'));
in controller, it prints only first value but I want all values of array.
<form action="test.php" method="post">
<table rules="all" style="background:#fff;">
<tr>
<td style="font-size:14px;" >Name</td>
<td style="font-size:14px;">Email</td>
<td style="font-size:14px;">Mobile</td>
<td><span style="font:normal 12px agency, arial; color:blue; text-decoration:underline; cursor:pointer;" onclick="addMoreRows(this.form);">Add More</span>
</td>
</tr>
<tr id="rowId">
<td><input name="name1[]" type="text" value="" size="17%"/></td>
<td><input name="age1[]" type="text" value="" /></td>
<td><input name="relation1[]" type="text" value="" /></td>
</tr>
</table>
<div id="addedRows"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var rowCount = 1;
function addMoreRows(frm) {
rowCount ++;
var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="name1[]" type="text" size="17%" maxlength="120" /></td><td><input name="age1[]" type="text" maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="relation1[]" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> Delete</p>';
jQuery('#addedRows').append(recRow);
}
function removeRow(removeNum) {
jQuery('#rowCount'+removeNum).remove();
}
</script>
</form>
Try saving it to another variable and printing it like this:
$name1 = $this->input->post('name1');
print_r($name1);
You can loop through all the POST item, so you print out all the POST values. Also, I suggest incremented the 'name' atttribute as well, so you will have name1, name2, name 3 etc, or just remove the number because you are using an array.
If you want to increment the 'name' attribute
To loop:
$counter = 0;
foreach ($this->input->post('name1') as $key => $value)
{
$counter++;
// $value = name1
echo $this->input->post('age". $counter ."');
echo $this->input->post('relation". $counter ."');
}
With array
To loop:
foreach ($this->input->post('name1') as $key => $value)
{
echo $value;
$this->input->post('age1');
$this->input->post('relation1');
}
I havent tested it myself
Change your view page:
put <?php echo form_open_multipart('test/add_member'); ?> instead of
<form action="test.php" method="post">
In Controller: Dynamic input array data can handle as follows, this may help you..thanks!
public function add_member()
{
if (!$this->ion_auth->logged_in()) {
redirect('auth/login');
}
$itemCount = count($this->input->post('name'));
$itemValues=0;
$query = "INSERT INTO You_table_name(name, age, relation) VALUES ";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
$name = $this->input->post('name');
$age = $this->input->post('age');
$relation = $this->input->post('relation');
if(!empty($name[$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $name[$i] . "', '" . $age[$i] . "', '" . $relation[$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
if (!$this->db->query($sql)) {
// echo "FALSE";
}else {
// echo "TRUE";
}
}
}

how to solve Undefined offset: error in php

I have a html code where I create a table and two radio button on each row. for giving different name to radio button on each row I used while loop and I++ way.
that is
<form action = "submit_varification.php" method = "POST" onclick = "return validate()">
<div style="position: absolute; left: 50px; top: 90px;">
<label class="right"><font color="white">Date:</font></label>
<input type="text" id = "frmDate" /><br>
<p id="date"></p>
</div>
<div style="position: absolute; left: 250px; top: 91px;">
<label class="right"><font color="white">V-ID:</font></label>
<input type="text" id = "myText" name = "reviewer" value = ""/><br>
</div>
<div style="position: absolute; left: 900px; top: 91px;">
<button type="button" name="show" id="show" onclick = "" >History</button>
</div>
<div style="position: absolute; left: 900px;">
<input type="submit" name="test" id="test" value="Submit" /><br/>
</div>
<script>
var date = new Date();
document.getElementById("frmDate").value = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
</script>
</body>
<table style="position: absolute; width:95%; left: 20px; top: 150px;" id = "table1">
<?php
$myDate = date('m/d/Y');
?>
<tr>
<th>Date</th>
<th>Time</th>
<th>Alias</th>
<th>Machine_Name</th>
<th>Build_Name</th>
<th>Build_version</th>
<th>WinDBG</th>
<th>.Net_Framework</th>
<th>Status</th>
</tr>
<?php
//get records from database
$sql3 = "SELECT * FROM data WHERE `Date` = '".$myDate."' ORDER BY id DESC";
$query = $conn->query($sql3);
if($query->num_rows > 0){
$i = 0 ;
while($row = $query->fetch_assoc()){ ?>
<tr>
<td><?php echo $row['Date']; ?></td>
<td><?php echo $row['Time']; ?></td>
<td><?php echo $row['Alias']; ?></td>
<td><?php echo $row['Machine_Name']; ?></td>
<td><?php echo $row['Build_Name']; ?></td>
<td><?php echo $row['Build_Version']; ?></td>
<td><?php echo $row['WinDBG']; ?></td>
<td><?php echo $row['.NET_Framework']; ?></td>
<td style='white-space: nowrap'><form><label class = "ready"><input type="radio" name="[<?php $i ?>]" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="[<?php $i ?>]" value = "Not Ready" >Not Ready</label></form></td>
</tr>
<?php $i++ ; } } ?>
</table>
</form>
and I want to store the value of each row to a database. so I used POST method on the form. and I am trying to take the value of radio button to database but I am facing a error like
Notice: Undefined offset: 0 in C:\wamp64\www\submit_varification.php on line 33
Notice: Undefined offset: 1 in C:\wamp64\www\submit_varification.php on line 33
Notice: Undefined offset: 2 in C:\wamp64\www\submit_varification.php on line 33
and the PHP code:
$query = $conn->query($sql4);
if($query->num_rows > 0){
$i = 0 ;
while($row = $query->fetch_assoc()){
//...insert into your DB.
$row1 = $row["Date"];
$row2 = $row["Time"];
$row3 = $row["Alias"];
$row4 = $row["Machine_Name"];
$row5 = $row["Build_Name"];
$row6 = $row['Build_Version'];
$row7 = $row["WinDBG"];
$row8 = $row[".NET_Framework"];
$status = $_POST["$i"]; // this is the error
$sql5 = "INSERT INTO history (`Date`, `Time`, `Alias`, `Machine_Name`, `Build_Name`, `Build_version`, `WinDBG`, `.NET_Framework`, `Status`, `Reviewed_By`)
VALUES ('".$row1."','".$row2."','".$row3."','".$row4."','".$row5."','".$row6."','".$row7."','".$row8."', '".$status."', '".$reviewer."') ";
if ($conn->query($sql5) === TRUE) {
//echo "New record created successfully";
//echo nl2br("\n");
echo "";
} else {
echo "Error: " . $sql5 . "<br>" . $conn->error;
}
$i++ ;
}
}
is anyone have any solution for this ?
Dump the array that populates $i for each loop. I would wager the array does not have the array key that the name="[<?php $i ?>]" is expecting.
Can you remove the brackets in the name attribute and see if its working correct. Below is the code:
<td style='white-space: nowrap'>
<form><label class = "ready">
<input type="radio" name="<?php $i ?>" value = "Ready">Ready</label>
<label class = "notready"><input type="radio" name="<?php $i ?>" value = "Not Ready" >Not Ready</label>
</form>
Plus it would be better if you have some static text appended to the name column and in server side, you can loop it:
<td style='white-space: nowrap'>
<form><label class = "ready">
<input type="radio" name="status_<?php $i ?>" value = "Ready">Ready</label>
<label class = "notready"><input type="radio" name="status_<?php $i ?>" value = "Not Ready" >Not Ready</label>
</form>
Let me know if this helps..
You make nested forms. replace the line
<td style='white-space: nowrap'><form><label class = "ready"><input type="radio" name="[<?php $i ?>]" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="[<?php $i ?>]" value = "Not Ready" >Not Ready</label></form></td>
with this:
<td style='white-space: nowrap'><label class = "ready"><input type="radio" name="<?php $i ?>" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="<?php $i ?>" value = "Not Ready" >Not Ready</label></td>
Also remove the brackets, like gopal panadi mentioned.
Furthermore I am not sure if you can have input tags inside labels. shouldn't they be next to each other?
Edit: after that if it fails, dump the $_POST array and see how/if the radio values are in $_POST. var_dump($_POST);die();

multiple submit on same page with php ajax

<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.

script dosen't execute ajax call

I'm sending ajax request to the file, but for some reason the file doesn't complete operation, I know that request reaches the file, because it echoes request received, and it stops there. I can't figure out why.
<?php
/**
* Created by PhpStorm.
* Date: 23.2.2015.
* Time: 5:20
* Version 1.1
*/
$nacin_rada = 'echo';//promjenjivo u session
$mysqli = mysqli_connect('localhost', 'root', 'password', 'database');
$year = date("Y");
echo 'request received';
if (isset($_POST['submit'])) { //get_magic_quotes_gpc removed in php 5.4.0
$username = stripslashes($_POST['username']);
$password = stripslashes(md5($_POST['password']));
$passverif = stripslashes(md5($_POST['passverif']));
$email = stripslashes($_POST['email']);
$ime = stripslashes($_POST['ime']);
$prezime = stripslashes($_POST['prezime']);
$dan = stripslashes($_POST['dan']);
$mjesec = stripslashes(intval($_POST['mjesec']));
$godina = stripslashes(intval($_POST['godina']));
$avatar_source = stripslashes($_POST['avatar']);
$sex = stripslashes($_POST['sex']);
if ($sex == 'žensko' and $avatar_source == '') {
$avatar_source = 'default_profile_female.jpeg'; //potrebno dodati podršku za default sliku
} elseif ($sex == 'muško' and $avatar_source == '') {
$avatar_source = 'default_profile_male.jpeg'; //potrebno dodati podršku za default sliku
}
if ($username == '' or $password == '' or $passverif == '' or $email == '' or $ime == '' or $prezime == '' or $dan == '' or $mjesec == '' or $godina == '' or $avatar_source == '') {
echo ' You didn\'t fill out all the forms';
exit;
}
if ($password <= 2) {
echo 'Password too short';
exit;
}
if ($passverif <= 2) {
echo 'Password verification too short';
exit;
}
if ($password != $passverif) {
echo 'Vaše lozinke se ne podudaraju';
exit;
}
if ($mjesec > '12' or $mjesec < '1') {
echo $mjesec . 'nije valjani izbor';
exit;
}
if ($godina > $year) { //year defined at line 12
echo 'Vi ste iz budučnosti?';
exit;
}
if ($godina == '0000') {
echo '0000 nije valjani izbor';
exit;
}
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE email='$email'") or die("Query Failed");// redefining sql query for user data selection
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if ($num_row >= 1) {
echo '<span style="color:white;">U bazi podataka več postoji račun s tim Emailom</span>';
} elseif ($num_row == 0) {
$insert_users = mysqli_query($mysqli, "INSERT INTO users(username, password, email, ime, prezime,sex, avatar, dan, mjesec, godina) VALUES ('$username','$password','$email','$ime','$prezime','$sex','$avatar_source','$dan','$mjesec','$godina')");
$insert_user_data = mysqli_query($mysqli, "INSERT INTO user_data(hometown, love_status, about) VALUES ('NULL','NULL','NULL' )");
echo 'Registracija uspješna,možete se prijaviti';
} else echo 'Registracija neuspjela';
}
?>
You had several errors:
In your AJAX call use this way to send the parameters, like bloodyKnuckles pointed out:
data: { username: username, password: password, passverif: passverif, email: email ... }
Also, $_POST['submit'] isn't defined. Instead, try using $_POST['username'] or something else from your parameters.
JQuery ajax method, data parameter takes, among other things, an object, such as:
data: { username: username, password: password, passverif: passverif, email: email ... }
You're passing:
data: "{username,password,passwordverif,email...}"
A couple things that don't work there: 1) not key: value pairs, and 2) that's a string, not an object.
Another problem, these:
var username = $('.username').val;
...need to be changed to:
var username = $('.username').val();
Notice the parenthesis at the end.
So you have 3 things to fix. Two in your JavaScript, and one in your PHP file.
JavaScript:
Use object notation in data setting.
Don't quote that object.
PHP:
Use something other than $_POST['submit'] to check for form data on your server script.
<html>
<style>
body{
outline: none;
background-color:#222222;
}
select{
background-color: #FFFFFF;
border: 0 solid transparent;
width: 100px;
}
table{
margin-left: 850px;
border: 1px solid blue;
border-radius: 5px;
background:#EAEAEC;
margin-top:0;
}
input{width:372px;height:34px;}
.submit{background-color:white;border:0 transparent}
.mjesec{position:absolute;margin-left:200px;}
.dan{margin-left:40px;position:absolute;margin-top:-25px;}
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function Registracija_ajax() {
var username = $('.username').val;
var password = $('.password').val;
var passverif = $('passverif').val;
var email = $('.email').val;
var ime = $('.ime').val;
var prezime = $('.prezime').val;
var dan = $('.dan').val;
var mjesec = $('.mjesec').val;
var godina = $('.godina').val;
var avatar_source = $('.avatar_source').val;
var sex = $('.sex').val;
$.ajax({
type: "POST",
url: "registration.php",
data: "{username,password,passverif,email,ime,prezime,dan,mjesec,godina,avatar_source,sex}",
beforeSend: function () {
$('.loading_gif').css('display:inline');
},
success: function (response) {
$('.response').html(response);
}
});
}
</script>
<body>
<table cellspacing="21">
<tr>
<td>
<input name="username" required="ddd" placeholder="username" class="username">
</td>
</tr>
<tr>
<td>
<input name="password" type="password" required placeholder="password" class="password">
</td>
</tr>
<tr>
<td>
<input name="passverif" type="password" required placeholder="password" class="passverif">
</td>
</tr>
<tr>
<td>
<input name="email" placeholder="email" required class="email">
</td>
</tr>
<tr>
<td>
<input name="ime" placeholder="ime" required class="ime">
</td>
</tr>
<tr>
<td>
<input name="prezime" placeholder="prezime" required class="prezime">
</td>
</tr>
<tr>
<td>
<select name="sex" class="sex" style="margin-left:40px;position:absolute;">
<option value="male">Muško</option>
<option value="female">Žensko</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="godina" class="godina" style="margin-left:200px;position:absolute;margin-top:-23px;">
<option value="0000">Godina</option>
<?php
$beggining_year = date('Y') - 13;
$end_year = '1975';
while ($end_year <= $beggining_year) {
echo '<option value="' . $beggining_year . '">' . $beggining_year . '</option>';
$beggining_year--;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select class="mjesec" name="mjesec">
<option value="0000">Mjesec</option>
<?php
$beggining_month = '1';
$end_month = '12';
while ($beggining_month <= $end_month) {
echo '<option value="' . $end_month . '">' . $end_month . '</option>';
$end_month--;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select class="dan" name="dan">
<option value="0000">Dan:</option>
<?php
$beggining_day = '1';
$end_day = '31';
while ($beggining_day <= $end_day) {
echo '<option value="' . $end_day . '">' . $end_day . '</option>';
$end_day--;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<input class="avatar" name="avatar" placeholder="Profile photo(link only)">
</td>
</tr>
<tr>
<td>
<button value="submit" class="submit" onclick="Registracija_ajax()" name="submit">Registracija</button>
</td>
</tr>
</table>
</body>
<div class="response"></div>
#Philip Sorokin ,you have the other file above.

Categories