ajax POST on form sumbit event not working properly - javascript

i have problem with ajax post with form submit event. i have table generated by opentable.php
here code for opentable.php
<?php
session_start();
require("dbc.php");
$memberid = $_SESSION['memberid'];
$sql = "SELECT * FROM `open` WHERE `memberid`='$memberid'";
$mydata = mysql_query($sql);
echo "<table><tr><th>Time</th><th>Type</th><th>Size</th><th>Price</th><th>Profit</th><th></th><th></th></tr>";
while($record = mysql_fetch_array($mydata)){
echo "<form action = assets/close.php id=closeform>";
echo "<tr>";
echo "<td>" . $record['opendate'] . "</td>";
echo "<td>" . $record['type'] . "</td>";
echo "<td>" . $record['size'] . "</td>";
echo "<td>" . $record['openprice'] . "</td>";
echo "<td>" . $record['profit'] . "</td>";
echo "<td>"."<input type=hidden name=openid value=".$record['openid']." </td>";
echo "<td>" . "<input type=submit name=close value=close". " </td>";
//echo "</tr>";
echo "</form>";
}
echo "</table>";
?>
and ajax javasript for submit event trade.js
$(document).ready(function() {
$('#closeform').submit(function( event ) {
event.preventDefault();
var $form = $( this ),
price = $('#price').val(),
id = $form.find( "input[name='openid']" ).val(),
url = $form.attr( "action" );
var posting = $.post( url, { openid: id, closeprice: price } );
var r=confirm("Are you sure?");
if(r =true){
posting.done(function( data ) {
alert(data);
});
}
else
{
alert("Transaction canceled")
}
});
}
i tested it, and it runs like normal php form. and error there is no $_POST data passed.
please give me recomendation for this kind of event thanks.

closeform is a dynamically added form, try using .on():
$(document).on('submit', '#closeform', function ( event ) {

Related

Editable table without using jquery plugins

I want to create a table with editable contents(using an "edit" button on each row), without the use of Bootstrap, or any other plugin.
I want to only use HTML,PHP,AJAX,JavaScript. Is this kind of task possible, and if so, can someone post some sample code or example?
SQL results work fine.
$sql_query = "SELECT User.user_id,User.name,User.surname,User.username,User.password,Role.role_name FROM User INNER JOIN Role ON User.role_id = Role.role_id";
$result = mysqli_query($conn, $sql_query);
$role_name = 'role_name';
while($rows = mysqli_fetch_array($result))
{ echo "<tr>";
echo "<td> $rows[$user_id]</td>";
echo "<td> $rows[$name]</td>";
echo "<td> $rows[$surname]</td>";
echo "<td> $rows[$username]</td>";
echo "<td> $rows[$password]</td>";
echo "<td> $rows[$role_name]</td>";
?>
<div id = "edit">
<td> <button type='button' id="<?php $rows[$user_id];?>" onclick="submit_id()"> Edit </button> </td>
</div>
<?php
}
echo "</table>"; ?>
<script>
function submit_id() {
var user_id = user_id.val();
$.ajax({
url:'reedit.php',
type: 'GET',
data: (user_id);
})
}
</script>
I want to have each edit button, to change only the row that it is aligned to.
I saw that you had jQuery at least..
I think this will help you a LOT:
<?php
$sql_query = "SELECT User.user_id,User.name,User.surname,User.username,User.password,Role.role_name FROM User INNER JOIN Role ON User.role_id = Role.role_id";
$result = mysqli_query($conn, $sql_query);
if(!$result) {
die(mysqli_error($conn));
}
$table_html = "<table id=\"usersTable\">";
while($rows = mysqli_fetch_array($result)) {
$table_html .= "<tr>";
$table_html .= "<td>" . $rows["user_id"] . "</td>";
$table_html .= "<td>" . $rows["name"] . "</td>";
$table_html .= "<td>" . $rows["surname"] . "</td>";
$table_html .= "<td>" . $rows["username"] . "</td>";
$table_html .= "<td>" . $rows["password"] . "</td>";
$table_html .= "<td>" . $rows["role_name"] . "</td>";
$table_html .= "<td><button type=\"button\" class=\"editBnt\">Edit</button></td>";
$table_html .= "</tr>";
}
$table_html .= "</table>";
echo $table_html;
?>
<script>
$(function() {
$("#usersTable").on("dblclick", "td td:not(:first-child) td:not(:last-child)", function() {
$(this).html("<input type=\"text\" class=\"form-control dynamicInput\" value=\""+$(this).text()+"\"></input>").children("input").focus();
$(this).on("change blur", "input.dynamicInput", function() {
$(this).parent("td").text($(this).val());
});
});
$("#usersTable").on("click", "button.editBnt", function() {
var row = $(this).parent().parent(),
user_data = {
user_id: row[0].cells[0].innerText,
name: row[0].cells[1].innerText,
surname: row[0].cells[2].innerText,
username: row[0].cells[3].innerText,
password: row[0].cells[4].innerText,
role_name: row[0].cells[5].innerText
};
alert("You can now save the data or do what ever you want here.. check your console.");
console.log(user_data);
});
});
</script>
you can use the content-editable attribute to make your cells editable
something like:
var rows = document.querySelectorAll("tr");
row.foreach(function() {
this.addEventListener('click', function() {
this.setAttribute('contenteditable','contenteditable');
});
});
You will want to put the click listener on your button instead of the row

Pass MYSQL row id to javascript variable

I have this script which is triggered when a button with the class .press_me is pressed.The buttons are on a column from a php generated mysql table:
$result = mysqli_query($con,"SELECT * FROM tbname");
echo "<table id='main'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='right-middle user'>" . $row['ID'] . "</td>";
echo "<td class='right-middle user'>" . $row['Nume'] . "</td>";
echo "<td class='right-middle done'>" . $row['Teme_facute'] . "</td>";
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me'>" ."</td>";
echo "<td class='right-middle undone'>" . $row['Teme_nefacute'] . "</td>";
echo "<td class='right-middle uncheck'>" . "<img src='img/uncheck.png'>" . "</td>";
echo "<td class='side-table resetDone'>" . "<img src='img/resetDone.png'>" . "</td>";
echo "<td class='side-table resetUndone'>" . "<img src='img/resetUndone.png'>" . "</td>";
echo "</tr>";
}
echo "</table>";
And the script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
And counter.php:
<?php
echo $_POST["id"];
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
I'm having trouble updating only the value on the same row as the button pressed.When i run the page in this configuration counter.php returns no id passed and i think the problem is with the passing of the row id. Can anyone help me update only the value on the row with the pressed button?
I'm aware of sql injection but it's not the main problem now
Your id is empty
try this
echo "<td class='right-middle check'>" . "<img data-id='{$row['ID']}' src='img/check.png' class='press_me'>" ."</td>";
And in the script use this
var id=$(this).data("id");
change you javascript, looks like you are not sending data at all
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php",
// add this line
data: { id: id}
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
Replace below script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo $row[ID]; ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
NOTE: I assume that you are working with single record. If not then it
will going wrong.
If this is working wrong then replace .press_me line with below:
$id = $row['ID'];
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me' id='<?php print($id);?>' >" ."</td>";
And script is like:
var id = $(this).attr("id");
Hope this help you well!

AJAX form refreshes page

Have been searching around for a while and can't find a proper answer to this problem. I have a "finance" tracker that has several hidden divs which using jQuery appear when the button to show that div is clicked. I have a Asset Tracker which queries a database and upon being checked updates the database with new values in adjacent input rows where the checkbox is located. I am trying to get the checkbox to submit the data without causing the page to reload and the div to "toggle" off again.
On the form section I attempted to remove the method='post' but instead when checking the box it reloaded the page and added all the post variables to the URL string. I removed the action='FBook.php' in an attempt to prevent the reloading, but that did not resolve the problem.
Here is the related code from the PHP file:
if(isset($_POST['AssetSetUpdate'])) { $AssetLastUpdate = $dtNowDate->format('Y-m-d');
foreach($_POST['AssetID'] as $key => $id) { if(isset($_POST['AssetSetUpdate'][$key])) {
$stmt_ATrackUp -> bindParam(':UpDate', $AssetLastUpdate, PDO::PARAM_STR, 10);
$stmt_ATrackUp -> bindParam(':UpNotes', $_POST['AssetNotes'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpThis', $_POST['AssetDescription'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpVal', $_POST['AssetValue'][$key], PDO::PARAM_INT, 3);
$stmt_ATrackUp -> execute(); } else continue; }
echo "<div class='Notice'>" . $PageTitle . " / Assets updated!</div>"; }
(other code)
$(document).ready(function() {
$("#AssetUpdateForm").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'FBook.php',
data: $(this).serialize(),
success: function() { alert('form submitted'); },
});
return false;
});
$('#ShFBAsset').click(function() { $('#FBAsset').toggle('slow'); });
(other code)
});
(other code)
$AssetCounter = 1;
$stmt_ATrack -> execute(); while ($row_ATrack = $stmt_ATrack -> fetch(PDO::FETCH_ASSOC))
{
$ChAge = $row_ATrack['Checked']; $cChAge = ''; switch(true)
{
case (strtotime($ChAge) >= strtotime('-7 days')): $cChAge = 'FBCAN'; break;
case (strtotime($ChAge) >= strtotime('-30 days')): $cChAge = 'FBCA1'; break;
case (strtotime($ChAge) >= strtotime('-90 days')): $cChAge = 'FBCA3'; break;
default: $cChAge = 'FBCA6'; break;
}
if(isset($row_ATrack['Serial'])) { $IfDSerial = "<strong>Serial: </strong>" . $row_ATrack['Serial'] . "<br/>"; } else { $IfDSerial = ''; }
if(isset($row_ATrack['UPC'])) { $IfDUPC = "<strong>UPC: </strong>" . $row_ATrack['UPC'] . "<br/>"; } else { $IfDUPC = ''; }
if(isset($row_ATrack['Related'])) { $IfDRelated = "<strong>Related: </strong>" . $row_ATrack['Related'] . "<br/>"; } else { $IfDRelated = ''; }
if(isset($row_ATrack['Location'])) { $IfDLocation = "<strong>Location: </strong>" . $row_ATrack['Location'] . "<br/>"; } else { $IfDLocation = ''; }
if(isset($row_ATrack['TagPhoto'])) { $IfDTagPhoto = "<strong>Tag photo: </strong><a href='Images/INV/" . $row_ATrack['TagPhoto'] . ".JPG'>" . $row_ATrack['TagPhoto'] . "</a><br/>"; } else { $IfDTagPhoto = ''; }
$IfDetails = "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'>" . ($IfDSerial) . ($IfDUPC) . ($IfDRelated) . ($IfDLocation) . ($IfDTagPhoto) . "</div></div>";
if($IfDetails == "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'></div></div>") { $IfDetails = ''; }
echo "<form id='AssetUpdateForm[" . $AssetCounter . "]' method='post'>";
echo "<tr><input type='hidden' name='AssetID[" . $AssetCounter . "]' value='" . $AssetCounter . "' />";
echo "<td><input type='hidden' name='AssetDescription[" . $AssetCounter . "]' value='" . $row_ATrack['Description'] . "' /><a href='https://www.google.com/#q=eBay+" . $row_ATrack['Description'] . "' target='_new_AssetSearch'>" . $row_ATrack['Description'] . "</a></td>";
echo "<td>" . $row_ATrack['Type'] . " - " . $row_ATrack['Category'] . "</td>";
echo "<td><input type='checkbox' name='AssetSetUpdate[" . $AssetCounter . "]' value='Now' onchange='this.form.submit();' /></td>";
echo "<td><input type='number' name='AssetValue[" . $AssetCounter . "]' value = '" . $row_ATrack['Value'] . "' style='width: 75px;' /></td>";
echo "<td class='" . $cChAge . "'>" . $ChAge . "</td>";
echo "<td><input type='text' name='AssetNotes[" . $AssetCounter . "]' value = '" . $row_ATrack['Notes'] . "' style='width: 140px;' /></td>";
echo "<td>" . $IfDetails . "</td>";
echo "</tr>";
echo "</form>";
$AssetCounter++;
}
Your JavaScript:
$("#AssetUpdateForm")
… is working on a form with id="AssetUpdateForm".
Your PHP says:
id='AssetUpdateForm[" . $AssetCounter . "]'
which in HTML terms becomes:
id='AssetUpdateForm[something]'
Even if the variable is empty, you still have the square brackets, so the ID is not going to match and the JavaScript event handler will never be bound to that element.
You need to either use the real ID or, since it appears that it can change, add a class to the form and use a .class-selector in the JavaScript.
NB: Your HTML is invalid. The particular problem you have has the potential to cause the same symptoms are you describe so just fixing the problem above might not be enough. Use a validator and write valid HTML too.
Had nothing to do with the HTML or PHP. Turns out that jQuery AJAX was conflicting with the onclick='this.form.submit();' property. I removed that and changed the ajax request to the following - and while it still has bugs as it won't work on the 2nd ajax request, it validates everything else is fine.
$(".Check2Update").on('change', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'FBook.php',
data: $(this.form).serialize(),
success: function(html) {
console.log('Successfully submitted AJAX!');
$("#TableAssets").replaceWith($('#TableAssets', $(html)));
}
});
});

Oop check if database table is empty

I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D

Javascript/PHP redirect

Hello fellow programmers!
I'm working on a personal project (mainly to learn php/javascript) and have ran into an issue with redirection when clicking on a link. I have a bit of a strange situation on a tabbed page I've created and I think that may be what is causing my problem.
I'm trying to allow the user to click the (which due to css has made it look different than normal ) to redirect them to a new page with more details. I THINK that the second tag on my page is what is throwing me off because I have a form in it.
I have tried tons of different things like window.location.href="", location.href="", document.location="", etc... But the same thing always occurs. I am able to get both alert messages, so I know I am getting into my JavaScript (even when I put it into it's own .js file).
Anyway advice/help would be very helpful. Also, if anyone has a suggestion on cleaning this code up a bit, that would also be truly helpful.
Below is basically what I have.
Thanks in advance for your help!
<html>
<head>
<title>test site</title>
<link rel="stylesheet" href="test.css" type="text/css" media="screen" />
<script src="test.js" type="text/javascript"></script>
<script type="text/javascript">
function viewDetails(modelId){
alert(modelId);
window.location.href="new url?ModelID=" + modelId;
alert('redirecting would be way awesome...');
}
</script>
</head>
<body onload="load()">
<div id="tabbed_box_1" class="tabbed_box">
<h4>Navigation Tabs<small>Select a tab</small></h4>
<div class="tabbed_area">
<?php
mysql_connect('host','user','password');
mysql_select_db("database");
echo "<ul class='tabs'>";
echo "<li><a href='javascript:tabSwitch(1, 2);' id='tab_1' class='active'>Inventory</a></li>";
echo "<li><a href='javascript:tabSwitch(2, 2);' id='tab_2' >Add Project</a></li>";
echo "</ul>";
echo "<div id='content_1' class='content'>";
echo "<ul>";
$modelsSQL = "SELECT * FROM Model ORDER BY Name";
$modelsResult = mysql_query($modelsSQL);
while ($modelRow = mysql_fetch_array($modelsResult)){
$modelID = $modelRow[0];
$sqlAvailCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 0";
$sqlSoldCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 1";
$resultAvailCount = mysql_query($sqlAvailCount);
$resultSoldCount = mysql_query($sqlSoldCount);
$rowAvailCount = mysql_num_rows($resultAvailCount);
$rowSoldCount = mysql_num_rows($resultSoldCount);
echo "<li><a href='' onclick='javascript:viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>"
. $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
}
echo "</ul>";
echo "</div>";
echo "<div id='content_2' class='content'>";
echo "<form action='project_insert.php' method='post' name='projectAddForm'>";
echo "<table cellpadding='5'>";
// Project Model Selection
echo "<tr><td>";
echo "<label for='model'>Model</label>";
echo "</td><td>";
echo "<select name='model' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$modelListSQL = "SELECT * FROM Model ORDER BY Name";
$modelListResult = mysql_query($modelListSQL);
while ($modelListRow = mysql_fetch_array($modelListResult)){
echo "<option value='" . $modelListRow['ID'] . "'>" . $modelListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Material Selection
echo "<tr><td>";
echo "<label for='material'>material</label>";
echo "</td><td>";
echo "<select name='material' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$materialListSQL = "SELECT * FROM Material ORDER BY Name";
$materialListResult = mysql_query($materialListSQL);
while ($materialListRow = mysql_fetch_array($materialListResult)){
echo "<option value='" . $materialListRow['ID'] . "'>" . $materialListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Finish Selection
echo "<tr><td>";
echo "<label for='finish'>finish</label>";
echo "</td><td>";
echo "<select name='finish' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$finishListSQL = "SELECT * FROM Finish ORDER BY Name";
$finishListResult = mysql_query($finishListSQL);
while ($finishListRow = mysql_fetch_array($finishListResult))
{
echo "<option value='" . $finishListRow['ID'] . "'>" . $finishListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Craftsman Selection
echo "<tr><td>";
echo "<label for='craftsman'>craftsman</label>";
echo "</td><td>";
echo "<select name='craftsman' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$craftsmanListSQL = "SELECT * FROM Craftsman ORDER BY FirstName";
$craftsmanListResult = mysql_query($craftsmanListSQL);
while ($craftsmanListRow = mysql_fetch_array($craftsmanListResult)){
echo "<option value='" . $craftsmanListRow['ID'] . "'>" . $craftsmanListRow['FirstName'] . " " . $craftsmanListRow['LastName'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
//Project Description
echo "<tr><td>";
echo "<label for='description'>Description</label>";
echo "</td><td>";
echo "<input type='text' name='description' id='textArea' style='width:250px'>";
echo "</td></tr>";
// Project Selling Price
echo "<tr><td>";
echo "<label for='price'>Price</label>";
echo "</td><td>";
echo "<input id='price' name='price' type='number' style='width:150px'>";
echo "</td></tr>";
// Project Completion Date
echo "<tr><td>";
echo "<label for='date'>Finish Date</label>";
echo "</td><td>";
$dateArray = getdate();
$month = $dateArray[mon];
$day = $dateArray[mday];
if ($month < 10){
$month = '0' . $dateArray[mon];
}
if ($day < 10){
$day = '0' . $dateArray[mday];
}
$todaysDate = $dateArray[year] . '-' . $month . '-' . $day;
echo "<input type='date' name='date' value='" . $todaysDate . "' style='width:150px'>";
echo "</td></tr>";
// Buttons
echo "<tr><td align='center'>";
echo "<input type='button' name='Save' value='Save' onclick='javascript:validateAndSubmit(this.form);' style='width:100px'>";
echo "</td><td align='center'>";
echo "<input type='button' name='Cancel' value='Cancel' onclick='javascript:cancelEntry();' style='width:100px'>";
echo "</td></tr>";
echo "</table>";
echo "</form>";
echo "</div>";
?>
</div>
</div>
</body>
window.location.href may not trigger reload in some browsers and cases..
You should add a reload after
like this:
window.location.href = '/foo/bar/';
window.locaton.reload(true)
But, some browsers delay milliseconds to perform location.href set. In this cases the window.location.reload(true) may complete before this.
Therefore, add a timeout in reload:
window.location.href = '/foo/bar/';
setTimeout('window.locaton.reload(true)', 500);
works in all browsers for me
Good morning! I found the cause of my problem this morning and have been able to resolve the issue. The problem I was causing is because I am using the tag (stylized by css) to display the information, with an onclick event to call my JS code to redirect. Within the tag I had the href='', thinking that the JS would override that functionality, it doesn't!
Removing the href='' from the tag resolved the issue and allowed me to redirect to the new page. A second solution is to use my php code to dynamically create the href link within the tag.
echo "<li><a onclick='viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
OR
echo "<li><a href='inventorydetails.php?ModelID=" . $modelID . "'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
I think I will go with the second example for two reasons. First, it provides the link icon when hovering (which I know I can add through css, but this is easier. Second, less JS code.
I thank you for all your help in resolving this!

Categories