How to get the values from a submitted do...while form - php

I have the following code with a form inside a list that should submit the element through Ajax. The values in the form is repeated through a do ... while loop, so that the list become a dynamically list, like in this picture:
But when I click a button, the only element that is sent through the Ajax code is the value of the last button, even though I click on Oranges for example.
The code is as follow:
<script>
function submitForm() {
$.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#MyJobsForm').serialize(), success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}});
return false;
}
</script>
</head>
<body>
<ul id="btn_MyJobs" data-role="listview" data-inset="true">
<li id="MyJobs_List" class="push">
<form id="MyJobsForm" onsubmit="return submitForm();">
<?php do { ?>
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</form>
</li>
</ul>
<div id="myJobs_Right">
<div class="form_result"> </div>
</div>
</body>
The jQuery-ajax-demo.php page looks like this:
<?php
if(isset($_POST['name'])) {
$name = $_POST['name'];
?>
Your Name Is: <?php echo $name; ?><br />
<?php
die();
}
?>

If you have to do it this way, then you might try creating a new form for each button:
<?php do { ?>
<form onsubmit="return submitForm(this);"> <!--Note I added "this" -->
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
</form>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Then the only value that will get posted will be the hidden value that is in the form whose button you clicked. I updated the onsubmit call above to include this in the call. So you can do the below in your function:
function submitForm(form) {
var $form = $(form);
$.ajax({
type:'POST',
url: 'jQuery-ajax-demo.php',
data:$form.serialize(),
success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}
});
return false;
}

Related

How to send customer popup value in the controller

I am using CodeIgniter. I have a view button on the view page. If someone clicks on it then a custom popup will open and It will ask for feedback and approve. Also, I set input type hidden in this popup. After filling the form user will click on submit button.
But I am not getting the value in the controller but I am getting the hidden input value.
View
<?php echo form_open('Employee_control/admin_action_leave','id="admin_action_leave"'); ?>
View
<div class="view_popup_profile" id="popup-2" style="display: none;">
<div class="opacity"></div>
<div class="profile_content">
<div class="profile_header clearfix">
<div class="profile_header_right">
<input type="hidden" name="roster_id_send" id="roster_id_send" value="2">
<select name="admin_approved_status" id="admin_approved_status">
<option value="" disabled selected>Status</option>
<option value="1">Approved</option>
<option value="0">Pending</option>
<option value="-1">Reject</option>
</select>
<?php echo form_error('admin_approved_status'); ?>
</div>
</div>
<div class="profile_body">
<div class="row">
<div class="col-md-6 text_area_box">
<div class="admin_feedback">
<h3>Feedback</h3>
<textarea class="form_control" name="admin_feedback" id="admin_feedback"></textarea>
<?php echo form_error('admin_feedback'); ?>
<button type="submit" class="btn">Submit</button>
</div>
</div>
</div>
</div>
<div class="profile_footer">
Close
</div>
</div>
</div>
<?php echo form_close(); ?>
Controller
public function admin_feedback_leave(){
echo $admin_approved_status=$this->input->post('admin_approved_status');
echo $admin_feedback=$this->input->post('admin_feedback');
echo $roster_id_send=$this->input->post('roster_id_send');
}
I tried using ajax instated of form
Same issue I am getting. It's display only hiddle value
$("#admin_action_leave").validate({
// Specify the validation rules
rules: {
admin_approved_status:{
required:true
},
admin_feedback:{
required:true,
minlength:15,
maxlength:250
}
},
submitHandler: function(form) {
//form.submit();
//var a= document.getElementById("admin_approved_status").value;
//alert(a);
var admin_approved_status = $('#admin_approved_status').val();
var admin_feedback = $('#admin_feedback').val();
var roster_id_send = $('#roster_id_send').val();
// alert(admin_feedback);
//alert(roster_id_send);
//alert(admin_approved_status);
$.ajax({
url: baseUrl + "/Employee_control/admin_feedback_leave",
method: "POST",
data: {
admin_approved_status: admin_approved_status,
admin_feedback:admin_feedback,
roster_id_send:roster_id_send
},
success: function(data)
{
alert(data);
}
}); //AJAX
}
});
After implementing the code. I am just sharing the small part of the code.
My issue is I am not able to send the data to the controller. I tried two-way one using ajax and second using form submit. I am sharing the form submit code.
When I am adding the below code then it's not sending the data to the controller. If I remove the if and foreach condition then I am getting the output.
<?php $n=1; if(isset($admin_data_leave)){foreach ($admin_data_leave as $row) {?>
<!--some html code here-->
<?php $n++;}}else{echo "No data found";}?>
Whole code
<?php echo form_open('Employee_control/admin_feedback_leave', 'id="admin_action_leave"'); ?>
<table cellspacing="0" class="applied_leave_list_table">
<tbody>
<?php
$n = 1;
if (isset($admin_data_leave)) {
foreach ($admin_data_leave as $row) {
?>
<tr>
<td><?php echo $n; ?></td>
<td> View </td>
</tr>
<div class="view_popup_profile" id="popup-<?= $row->roster_id; ?>" style="display: none;">
<div class="profile_content">
<div class="profile_header_right">
<input type="hidden" name="roster_id_send" id="roster_id_send" value="<?php echo $row->roster_id; ?>">
</div>
</div>
<h3>Admin Feedback</h3>
<textarea class="form_control" name="admin_feedback" id="admin_feedback"></textarea>
<?php echo form_error('admin_feedback'); ?>
<button type="submit" class="btn">Submit</button>
</div>
<?php
$n++;
}
} else {
echo "No data found";
}
?>
</tbody>
</table>
<?php echo form_close(); ?>
Jquery validation
$('#admin_action_leave').each( function(){
var form = $(this);
form.validate({
rules: {
admin_approved_status:{
required:true
},
admin_feedback:{
required:true,
minlength:15,
maxlength:250
}
}
});
});
When I am adding the below code then it's not sending the data to the
controller. If I remove the if and foreach condition then I am getting
the output.
...which means, the content of the variable $admin_data_leave is not fulfilling the condition, ie. Either it is not set(not defined) or its not a traversible object or its empty.
Try putting the following code before the condition and look at the output...
echo "<pre>";
var_dump($_POST);
echo "</pre>";
die();

How to display the results from a separate PHP file in an HTML page?

I need to display the sum in the HTML form page itself. A part of the code is given below in my PHP file:
<?php
while($row = mysqli_fetch_array($search_result)):?>
<?php
$sum=$sum+$row['value'];
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['value'];?></td>
</tr>
<?php endwhile;?>
In my HTML form I have a total button. When I click that, I need to display the sum value. How can I do that?
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button">Total</button><br><br>
</form>
As I assume that you want to show total, if it is correct then follow below method
$sum = 0;
while($row = mysqli_fetch_array($search_result)):?>
$sum+= $row['value'];
<?php endwhile;?>
echo $sum;
or
if you want to show result without reloading the page. you have to code in ajax request.
We use ajax in html page to access the content from the php page :
HTML:
<html>
<script src="jquery.min.js"></script> // script download
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button" id="total">Total</button><br><br>
Your sum:<span id="sum"></span>
</form>
</html>
<script>
$( "#total" ).click(function() {
$.ajax({
url : "phptest.php",
type: "POST",
success: function(data)
{
$('#sum').html(data);
}
});
});
</script>
PHP: here your php code
<?php
echo "10";
?>
You need to use PHP SESSIONs, and play with the information you're sending in the POST request. Basically, both buttons will need to be of type submit so that they both send the request to the process (process.php). Then you can use sessions to set your results.
Do it in this manner:
index.php
<?php session_start(); ?>
<form action="process.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button name="total_btn" type="submit">Total</button>
</form>
<div id="results">
<?= (!empty($_SESSION["table"])) ? $_SESSION["table"] : "" ?>
<br>
<?= (!empty($_SESSION["sum"])) ? "Sum: " . $_SESSION["sum"] : "" ?>
</div>
<?php
session_destroy();
process.php
<?php
session_start();
$sum = 0;
$table = "<table>";
while ($row = mysqli_fetch_array($search_result)) {
$sum += $row['value'];
$table .= "<tr>
<td>{$row['id']}</td>
<td>{$row['time']}</td>
<td>{$row['value']}</td>
</tr>";
}
$table .= "</table>";
if (isset($_POST['total_btn'])) {
$_SESSION["sum"] = $sum;
}
$_SESSION["table"] = $table;
header('Location: index.php');
if i understood your problem correctly, then u need Ajax call. GET or POST based on your preferences.on that your HTML code will be separate from php code basically php code will respond to Ajax call and give you out put.
Modified code- Test.html
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button" id="gettotal">Total</button><br><br>
</form>
<script>
$("#gettotal").click(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',//based on your choice or requirement
url: 'calculate.php',
success: function(response) {
//here u decide where to show output value
alert(response);
},
error: function(result) {
alert('error');
}
});
});
</script>
calculate.php
<?php
$sum = 0;
while($row = mysqli_fetch_array($search_result))
{
//calculate your total and send back as JSON obj.
$sum=$sum+$row['value'];
}
echo json_encode($sum);
?>

issue sending a retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Try Changing Your Code A bit like Below .
Jquery part
success: function(d){
var output=d[0].data; // Will output only first record
$('#cuentas').html(output);
} // End of success function of ajax form
PHP PART
$centro = $_POST['centro'];
$output_string = array('data'=>$centro);
echo json_encode($output_string);
if still not works Check The Developer tool in chrome or firebug in firefox to monitor the Requests
Looking at your code:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
I miss an ending-tag for the div id="centro". Therefore the click-event for jQuery("#centro") will not trigger.
I suppose it should be like this: (Always set <form> and </form> inside OR outside of a div, do not mix and put <form> outside and </form> inside of a div. Some things wont work as expected when you do a mix like that.
<?php
$result = 'works';
?>
<div id="centro">
<form id="form">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
</div> ><!-- end of div centro -->
<div id="cuentas">
</div>
I solved it, now this works, plus I added a gif loader:
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
var result = $("input#centro").val();
$.ajax({
url: 'request.php',
type:'POST',
data: { 'dataString': result },
beforeSend: function(){
$("#loader").show();
},
success: function(output_string){
$("#loader").hide();
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
<div id="loader" style="display:none"><img src="ajax-loader.gif" width="20px" height="20px"></div>
Click here
<br>
<input type="hidden" name="centro" id="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP
<?php
$data = $_POST['dataString'];
$output_string = '';
$output_string = '<h3>'.$data.' '.'testing'.'</h3>';
echo $output_string;
?>
Output: "works testing"

Posting search value via html button

I am searching for a possibility to replace the lowre input text field with a button like: <input type="button" class="button" name="search" value="Urban" onclick="">.
HTML CODE:
<form method="post" action="search.php" id="search_form">
<input type="text" name="search" value="<?php echo $_POST['search']; ?>" class="search_sounds"/>
<input type="submit" value="" class="submit" />
</form>
The whole script is supposed to search the sounds of a database:
PHP CODE:
<?php if(isset($_POST['search']) && !empty($_POST['search']))
{
include('searchfunction.php');
if(count($data) > 0)
{
?>
<script type="text/javascript">
$(document).ready(function(){
var description = '';
var myPlaylist = [
<?php
echo(implode(',', $data));
?>
];
$('#main').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
description:description, }
);
});
</script>
<?php
}
else
{
echo ('No sounds found.');
}
}
?>
add an id element to your button, like this (I removed the onclick="" code)
<input type="button" class="button" name="search" value="Urban" id="search_button">
Then use some simple jQuery:
$('#search_button').click(function() {
$('#search_form').submit();
});

Update div on AJAX submit jQuery is updating all divs

I'm trying to update a div with an ajax post. Problem is...it's updating every div.
Here's the json.php:
//json.php
$data['months'] = $db->escape_value($_POST['check']);
$data['id'] = $db->escape_value($_POST['hidden']);
$query = "UPDATE month SET months = '{$data['months']}' WHERE monthID = '{$data['id']}'";
$result = $db->query($query);
if($result) {
$data['success'] = true;
$data['message'] = "Update Successful!";
$data['text'] = $_POST['check'];
echo json_encode($data);
} else {
$data['message'] = "Update could not be completed.";
}
And the html:
<?php
$query = $db->query('SELECT * FROM month');
?>
<html>
<head>
<title>jQuery/Ajax - Update is updating all divs</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.check, button.save, input.cancel, div.message").hide();
$(".edit").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").hide();
$(this).parent().siblings("li.liThree").children("button.save").show();
$(this).parent().siblings("li.liFour").children("input.cancel").show();
$(this).parents("ul").siblings("div.showText").hide();
$(this).parents("ul").siblings("input.check").show();
$(this).hide();
return false;
});
$(".cancel").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").show();
$(this).parent().siblings("li.liThree").children("button.save").hide();
$(this).parent().siblings("li.liOne").children("input.edit").show();
$(this).parents("ul").siblings("div.showText").show();
$(this).parents("ul").siblings("input.check").hide();
$(this).hide();
return false;
});
$("form[name=form1]").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText").html(data.text);
$(".message").html(data.message).slideDown("fast");
$(".check").hide();
$("button.save").hide();
$(".cancel").hide();
$(".edit").show();
$(".delete").show();
$(".showText").show();
return false;
}
}, "json");
return false;
});
});
</script>
</head>
<body>
<div class="message">message</div>
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
<div class="container">
<div class="showText"><?php echo $row['months']; ?></div>
<input name="check" type="text" class="check" value="<?php echo $row['months']; ?>" />
<input name="hidden" type="hidden" class="hidden" value="<?php echo $row['monthID']; ?>" />
<ul class="list">
<li class="liOne">
<input name="edit" type="button" class="edit" value="edit" />
</li>
<li class="liTwo">
<input name="delete" type="submit" class="delete" value="delete" />
</li>
<li class="liThree">
<button name="save" type="submit" class="save" value="<?php echo $row['monthID']; ?>">save</button>
</li>
<li class="liFour">
<input name="cancel" type="button" class="cancel" value="cancel" />
</li>
</ul>
</div>
</form>
<?php } ?>
<!--<a id="reset" href="test3.php">reset</a>-->
</body>
</html>
You need to specify a context (the form) for the elements you're changing:
$("form[name=form1]").submit(function(){
var form = this;
var params = $(this);
$.post(form.action, { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText", form).html(data.text);
$(".message", form).html(data.message).slideDown("fast");
$(".check", form).hide();
$("button.save", form).hide();
$(".cancel", form).hide();
$(".edit", form).show();
$(".delete", form).show();
$(".showText", form).show();
return false;
}
}, "json");
return false;
});
Also, if you hide a parent element, the children are hidden, too, so you probably want to do that...
Every div has the same class: showText. They need unique IDs instead, like Div1, Div2. Then update them by their ID: $("#Div1")
Hint, instead of answer:
How many elements does $(".showText") return?
2nd Hint: It's more than one!
===
Edit for more clarity:
The first issue is that you're selecting by classes like .showText. But you're creating multiple forms, each of which has an element that matches .showText. You need some way to point at the right element in each form. One way to solve this is to add an ID on each FORM tag, so you can then select things like $('#form-number-$N .showtext) -- which selects any elements with class="showtext" inside the element with id "#form-number-$N"
You're looping over rows in your database and writing the forms. So you need some variable data to identify each individual form.
You've got a while loop that populates $row:
<?php while($row = $db->fetch_assoc($query)) { ?>
But currently, every form you create has a name attribute of "form1".
So what if, instead of:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
You did something like:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form<?PHP echo $row['id']; ?>" id="<?PHP echo $row['id']; ?> class="myFormClass" method="post">
Then you could use a handler that looks something like:
$("form.myFormClass").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(this.id + " .showText").html(data.text);
...
return false;
}
}, "json");
return false;
});
Do you see what's happening there?

Categories