why is jquery not passing a post value - php

I have a page with two forms on it. This shouldn't be a problem, but it is not working. My jquery looks like this:
$(document).ready(function()
{
$("table.jobs tbody tr td#ejob").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
$('#jobid').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#jobUpdate').submit();
});
var now = new Date();
var month = now.getMonth()+1;
var day = now.getDate();
var year = now.getFullYear();
if (month<10){month='0'+month}
if (day<10){day='0'+day}
var now = month +"/"+ day + "/" + year;
var calendarBox = $('#calDate');
//$('#calDate').val(calendarBox.datetimepicker('getDate'));
var thisone = $('#calDate').val(calendarBox.datetimepicker('getDate'));
calendarBox.datepicker(
{
minDate:('setDate', '' , new Date()),
defalt:calendarBox.val(now),
onSelect: function (selectedDateTime)
{
$('#calDate').val(calendarBox.datetimepicker('getDate'));
alert("Sendeing " + $('#calDate').val(calendarBox.datetimepicker('getDate')));
$('#calendarForm').submit();
}
});
}
);
and my forms look like this:
echo "<form id='calendarForm' action='view_rev8.php' method='POST'>";
echo "<table border='0' width='100%'class='calendarTable'>";
echo "<tr><td align='left'>Click on a job number to update or change job information</td>";
echo "<td align='right'></td>";
echo '<td align="right">Calendar: <input type="text" id="calDate" size="15" name"calDate"/></td></tr>';
echo "</table>";
echo "</form>";
//creates the form to post jobid for updateJobForm.php
echo'<form id="jobUpdate" action="../forms/updateJobForm.php" method="post">';
echo'<input type="hidden" name="jobid" id="jobid">';
echo '</form>';
The first function handles when a user clicks on a table item and submits the post value without a problem. The datepicker works and the form gets submitted, but i get the following error: Undefined index: calDate from the following page:
$pickedDate = $_POST['calDate'];
include_once("../php/job_class.php");
echo $pickedDate;
$obj=new jobs();
echo "<div style='border:solid 1px '>";
foreach ($obj as $val)
{
echo "<pre>";
echo print_r($obj);
//echo $obj->jobInfo();
echo "</pre>";
echo "</div>";
}
Why is this not working? It is a simple post from a well defined form, and as far as I can see all fields are named consistently and accurately.

You have invalid HTML in the input tag. (It's missing an = sign.)
<input type="text" id="calDate" size="15" name"calDate"/>
should be:
<input type="text" id="calDate" size="15" name="calDate"/>
So your JS is setting the value since you're using the ID, but the name is what is used for posting a form, which is why it is empty.

Related

Prevent Javascript form use back data on Back click

I create table using ajax. When i click on button it will read the row and create a form using ajax.
Everything is fine here. But when i click back button on browser, the data is somehow posted/display back as FORM. How to delete/prevent this when click on back.
Thing i have read:
1) Clear input for form. But where is reading input because form is created using function submitRowAsForm when button is clicked
2) Disable autocomplete. But this doesnt seem relevant and not work.
$(document).ready(function update(){
$.ajax({
url: 'getSchedule.php',
success: function(data,status)
{
createTableByForLoop(data);
},
async: true,
dataType: 'json'
}).then(function() { // on completion, restart
setTimeout(update, 30000); // function refers to itself
});;
});
function createTableByForLoop(data)
{
var table = "\
<div class='table-scrollable'>\
<table class=\"table table-responsive\">\
<thead >\
<tr>\
<th class=\"d-none\">ID</th>\
<th class=d-none>SHOWSCHEDULE_ID ID</th>\
<th>TITLE</th>\
<th>TIME</th>\
<th>ACTION</th>\
</tr>\
</thead>\
<tbody>"
for(var i=0; i<data.length;i++)
{
table += "<tr id=\""+i+"\">";
table += "<td class=d-none><input type=text class=\"form-control transparent-input\" name=SHOWSCHEDULE_ID value=\""+data[i]['SHOWSCHEDULE_ID']+"\" readonly></td>";
table += "<td><input type=text class=\"form-control transparent-input\" name=SHOWSCHEDULE_SHOWTITLE value=\""+data[i]['SHOWSCHEDULE_SHOWTITLE']+"\" readonly></td>";
table += "<td><input type=text class=\"form-control transparent-input\" name=SHOWBEGINTIME value=\""+data[i]['SHOWBEGINTIME']+"\" readonly> - <input type=text class=\"form-control transparent-input\" name=\""+data[i]['SHOWENDTIME']+"\" value=\""+data[i]['SHOWENDTIME']+"\" readonly></td>";
table += "<td><button onclick=submitRowAsForm("+i+") id=btnRoom class=\"btn btn-outline-success\" >Room</button>\
<button onclick=submitRowAsForm("+i+") id=btnBook class=\"btn btn-outline-warning\" >Book</button></td>";
table += "</tr>";
}
table +="</tbody></table></div>";
$('#idShowSchedule').html(table);
}
function submitRowAsForm(id) {
form=document.createElement('form');
form.method='POST';
form.action='OrderTicket.php';
$("#"+id).children().each(function() {
$(this).children().each(function(){
$(this).clone().appendTo(form);
});
});
document.body.appendChild(form);
form.submit();
}
To protect against the back button I would set a dirty flag on your page. That way when it's set you know you have done this before. So
Check to see if your dirty flag is set
If not set your dirty flag
Load data because this is a fresh loading of the page.
Make sure that you do this after the DOM Content has Loaded otherwise this will fail in some browsers.
Here is an example of how I didn't this in one of my old projects
document.addEventListener("DOMContentLoaded", function (event) {
var dirty = 0;
var dirtyEl = document.getElementById('page_is_dirty')
if (!dirty && dirtyEl && (dirtyEl.value != "0" && dirtyEl.value != "")) {
dirty = 1;
}
else if (dirtyEl) {
dirtyEl.value = '1';
}
var el = document.getElementById('ClickApp');
if (el && !dirty)
el.innerHTML = "<div id='ClickApp' ng-view='' click-main><br /><br /><center><h2>Loading Calendar</h2><br /><span id='ErrorInstructions'></span><br /><div class='ui-progress-bar ui-container' id='progress_bar' style='width: 350px'><div id='progressBar' class='ui-progress' style='width: 0%; float: left'></div></div><br /><br /><small><span id='LastError'></span></small></center></div>";
else {
var dirtyMEl = document.getElementById('page_is_dirty_message');
var dirtyMSG = dirtyMEl ? dirtyMEl.value : "You arrived here by hitting the back button. Please start over.";
el.innerHTML = "<div><br /><br /><center><h2>" + dirtyMSG + "</h2><br /><span id='ErrorInstructions'></span><br /><div class='ui-progress-bar ui-container' id='progress_bar' style='width: 350px'><div id='progressBar' class='ui-progress' style='width: 0%; float: left'></div></div><br /><br /><small><span id='LastError'></span></small></center></div>";
}
if (!dirty) {
//Do your data loading. Page transformaions, whatever
...
}});

Autocomplete existing textbox when selection clicked

I have a form where there are select option and a textbox. All I want to do is when I select specific option, it will pass the id to query the same table to get another column's value based on ID of selected option and then display the value in a textbox before insert/update the table.
This code will works if both field in my form using select field. So in my opinion, maybe my script for storing value in input text field is totally wrong. Please correct me if I do wrong.
My form code :
<form name="inserform" method="POST">
<label>Existing Customer Name : </label>
<select name="existCustName" id="existCustName">
<option value="">None</option>
<?php
$custName = $conn->query("SELECT * FROM customers");
while ($row = $custName->fetch_assoc())
{
?><option id="<?php echo $row['customerID']; ?>" value="<?php echo $row['customerID']; ?>"><?php echo $row['customerName']; ?></option><?php
}
?>
</select>br>
<label>Current Bottle Balance : </label>
<input type="int" id="currentBal" name="currentBal"></input><br>
<input name="insert" type="submit" value="INSERT"></input>
</form>
My script code :
<script type="text/javascript">
$(document).on("change", 'select#existCustName', function(e) {
var existCustID = $(this).children(":selected").attr("id");
$.ajax({
type: "POST",
data: {existCustID: existCustID},
url: 'existingcustomerlist.php',
dataType: 'json',
success: function(json) {
var $el = $("input#currentBal");
$el.empty();
$.each(json, function(k, v) {
$el.append("'input[value='" + v.currentBal + "']").val();
});
}
});
});
</script>
existingcustomerlist.php code:
<?php
include 'config/config.php';
$result = $conn->query("SELECT * FROM customers WHERE customerID = '" .$_POST['existCustID'] . "'");
$results = [];
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
header('Content-Type: application/json');
echo json_encode($results);
?>
I need help to solve this.
I assume you are trying to show the results as input text element next to the #currentBal element. Try by changing the script tag inside the success callback as shown below.
$.each(json, function (k, v) {
$el.after("<input type='text' class="currentBalTemp" value='" + v.currentBal + "' />");
});
Make sure to remove the .currentBalTemp elements on change event of select otherwise duplication will be shown. Add the below code on change event.
$('.currentBalTemp').remove();

Select All Checkbox from MYSQL

Today I'm currently using "Checkbox" and just a little problem. I have a dropdown list in my first page, I choose the items "DropDown 1" and then I click the Submit button after that it will go to the next page. So then, the second page will load all items under the "DropDown 1" using a checkbox only.
My problem is:
How can I check them all by using a checkbox "Check All", where the items in "DropwDown 1" are came from my database [MySQL].
Here's my code in page two:
<input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
<?php
$dropdown_value = (string)$_POST["id"];
echo "<br/>";
if ($dropdown_value == 'All Building')
{
$all = mysql_query("SELECT fldBldgName FROM tblbuildings");
while ($row = mysql_fetch_array($all))
{
echo "<tr><td>";
echo "<input type='checkbox' name='play[]' class='chk_boxes1' value='" . $row['fldBldgName'] . "'>";
echo $row['fldBldgName'];
echo "</td></tr><br/>";
}
}
?>
<script>
$(document).ready(function(){
$('input[name="all"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]').attr('checked', status);
});
});
</script>
look checked Attribute
echo "<input type='checkbox' class='chk_boxes1' name='play[]' value='".$row['fldBldgName']. "' checked>";
and why a <br> in a table?
EDIT
try this:
echo '<div><input type="checkbox" class="checkall"> Check all</div>';
$all = mysql_query("SELECT fldBldgName FROM tblbuildings");
while ($row = mysql_fetch_array($all))
{
echo "<div><input type='checkbox' name='play[]' class='chk_boxes1' value='" . $row['fldBldgName']."'>";
echo $row['fldBldgName'];."</div>";
}
and jQuery function:
$(function () {
$('.checkall').on('click', function () {
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
});
});
http://jsfiddle.net/H37cb/210/
Try listening to the change event on the .chk_boxes element. You should also use prop instead of attr when working with "binary" properties like `checked':
$('.chk_boxes').on('change', function(){
$('.chk_boxes1').prop('checked', $(this).prop('checked'));
});
http://api.jquery.com/prop/
You also need to wrap all your tr/td elements in a table element.:
<table>
<?php
...
?>
</table>
There's no need for br elements after a tr. tr will always start on a new line.

how to run php code on submit button without refreshing/ reloading the page

I want to execute some php code on submit button click without refreshing/reloading my page. Is it possible? also i have javascript function on page load that's why i don't want to refresh my page.
thanks in advance.
<?php
if(isset($_POST["search"]))
{
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
$add_to_textbox = "<input type='button' name='btn' value='add' />";
#****results in Grid****
echo "<table width='360px' border='1' cellpadding='2'>";
$rowID=1;
while($row = mysql_fetch_array($rs))
{
echo "<tr>";
echo "<td width='130px' id='name.$rowID.'>$row[Name]</td>";
echo "<td width='230px' id='link.$rowID.'><a href = '$row[Link]'>$row[Link]</a></td>";
echo "<td width='130px' onclick='Display($rowID);'>$add_to_textbox</td>";
echo "</tr>";
$rowID++;
}
echo "</table>";
#**********************
mysql_free_result($rs);
}
?>
<script type="text/javascript">
function Display(rowID){
var linkVal = document.getElementById('link'+rowID+'').innerHTML.replace(/<\/?[^>]+(>|$)/g, "\n");
document.getElementById("name").value = document.getElementById('name'+rowID+'').innerHTML;
document.getElementById("link").value = linkVal;
}
</script>
here is my code
Well, you need to use the javascript / ajax.
Example: on your submit link (a href for exaple), add call-in-to js function submitMe and pass on whatever variables you need
function submitMe() {
jQuery(function($) {
$.ajax( {
url : "some_php_page.php?action=getsession",
type : "GET",
success : function(data) {
alert ("works!"); //or use data string to show something else
}
});
});
}
IF you want to change some content dynamically, it is easy- you just need to create tags, and assign ID to them : <div id="Dynamic"> </div>
Then you load ANYTHING between those two tags using
document.getElementById("Dynamic").innerHTML = "<b>BOOM!</b>";
Meaning that you calling area between two tags and loading something into them. The same way you GET data from that place:
alert(document.getElementById("Dynamic").innerHTML);
Please read this:
http://www.tizag.com/javascriptT/javascript-getelementbyid.php
In addition, play and experiment with DOM elements and learn how they interact. It is not hard, just takes some time to grasp all concepts.
Whenever you send request ajax (with plain js anyway) from a html form, make sure you add the return false statement to prevent redirection:
something like:
<form method="post" ... onsubmit="ajax_post(); return false;">
You have to use ajax, but you can do it in plain javascript (without jquery). Jquery makes it easier.
plain javascript example: This function will trigger an ajax, via get, without parameter: you can tweak it so it run in POST and be able to send some parameter: file represent the php file to request and html represent the container whre the data will be displayed:
function plain_ajax(file,html){
if (window.XMLHttpRequest){
r=new XMLHttpRequest(); //For Most BRowser
} else{
r=new ActiveXObject("Microsoft.XMLHTTP"); //for Explorer
}
//When the state change
r.onreadystatechange=function(){
//ReadyState 4 = Loaded see: http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
//status 200 = ok see: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if(r.readyState==4 && r.status==200){
//Replace the content with the response, Using creatDocumentFragment is more efficient
//at the cost of a few more lines But it would alos allow you to append the data
//instead of replacing it using innerHTML;
document.getElementById(html).innerHTML = r.responseText;
}
}
//Opening the connection and sending the request.
r.open("GET",file,true);
r.send();
}
Your HTML or PHP form
<form action="submit.php" method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone Number: <input name="phone" id="phone" type="text" /><br />
<input type="button" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>
Your JavaScript
<script>
function SubmitForm() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
$.post("submit.php", { name: name, email: email, phone: phone },
function(data) {
alert("Data Loaded: " + data);
});
}
</script>
Your PHP page to do some activity
<?php
echo $_POST['name']."<br />";
echo $_POST['email']."<br />";
echo $_POST['phone']."<br />";
echo "All Data Submitted Sucessfully!"
?>

Ajax posting a form returns undefined error

I am trying to submit a form with ajax. Here is my complete code
<?php
$wparent = "123";
$method = "sms";
?>
<script type="text/javascript">
$(document).ready(function(){
$("#post_<?php echo $wparent;?>").click(function(){
$('#parentpost-<?php echo $wparent;?>').html('Loading.....');
$("#parentpost-<?php echo $wparent;?>").load("<?php echo SITE_URL;?>new_ajax/post_reply.php", {message:$("[name=replynote]").val(), method:$("[name=method]").val(), parent:$("[name=parent]").val()}); //end
}); // end of the main click function
});
</script>
<?php
echo "<textarea name='replynote' ></textarea>";
echo "<input type=\"submit\" class=\"post_button\" id=\"post_$wparent\" value=\"post\" />";
echo "<input type=\"button\" class=\"cancel_button\" value=\"Cancel\" />";
?>
<input type='hidden' name='parent' value='<?php echo $wparent;?>' />
<input type="hidden" name="method" value="<?php echo $method;?>" />
When I checked the post variables with firebug I saw that, its sending only the method correctly. All other values are sent as undefined. I could not find the error till now.
Try pre-populating the data map that you're passing:
$(document).ready(function () {
$("#post_<?php echo $wparent;?>").click(function () {
var message = $("[name=replynote]").val();
var method = $("[name=method]").val();
var parent = $("[name=parent]").val();
var data = {
"message": message,
"method": method,
"parent": parent
};
$('#parentpost-<?php echo $wparent;?>').html('Loading.....');
$("#parentpost-<?php echo $wparent;?>").load("<?php echo SITE_URL;?>new_ajax/post_reply.php", data); //end
}); // end of the main click function
});
If data is an object containing undefined values, then your jQuery selectors aren't working.
Also, since you're only using a name attribute to find your inputs, you may want to be more specific in the selectors.
Finally, the attribute selectors typically need the value of the attribute enclosed in quotes, so try these for your selectors:
var message = $('textarea[name="replynote"]').val();
var method = $('input[name="method"]').val();
var parent = $('input[name="parent"]').val();

Categories