Why does my submit button not submit to mySQL? - php

I have a php form I'll call it "php1" that uses ajax to populate the input text boxes from a mySQL db. to do so it uses a secondary page I'll call "php2". On php2 there is a submit "button" being used to submit any changes to the mySQL db. Every aspect works beautifully, except the submit, unless I test php2 by itself, then it submits to the db.What am I doing wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function myBlur(str){
if (str == "") {
document.getElementById("demo").innerHTML = "You Must Enter a Device Name! <br>";
$("#demo").css("background-color","red");
$("#Name").css("background-color","red");
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("form1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","php2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
This is to call the second page.
<fieldset><legend>Input</legend>
<div width="100%" id="form1">
<div id="demo"><br></div><br>
<form method="post" action="php1.php">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="<?php echo $Name ?>" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="<?php echo $MAC ?>">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="<?php echo $Own ?>">
Type: <select name="Type" id="Type" required="required" readonly="true" value="<?php echo $Type ?>">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
</form>
That is the form code from php1
$sql = "SELECT * FROM $table WHERE Name = '$q'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$N=$row["Name"];
$MA=$row["MAC"];
$Ow=$row["Own"];
$Ty=$row["Type"];
echo "<tr>";
echo "<form method='post' action='php1.php' id='UpAss'>",UpAss,"
<br><br>
Device Name: <input type='text' id='Name' name='Name' value=".$N." onBlur='myBlur(this.value)'>
MAC Address: <input type='text' id='MAC' name='MAC' readonly='True' autocomplete='off' value=". $MA.">
Owner or Location: <input type='text' id='Own' name='Own' value=". $Ow.">
Type: <select id='Type'>
<option value='".$Ty."'>". $Ty."</option>
<option value='Desktop'>Desktop</option>
<option value='Laptop'>Laptop</option>
<option value='Server'>Server</option>
<option value='Monitor'>Monitor</option>
<option value='Printer'>Printer</option>
<option value='Phone'>Phone</option>
<option value='iPhone'>iPhone</option>
</select>
echo "<input type='submit' id='Usubmit' value='Update Asset' form='UpAss' onClick='myUpdate()'></input></form>";
}
function myUpdate()
{
// Create connection
$connU = new MySQLi($db_host, $db_user, $db_pass, $db_name, $db_port);
// Check connection
if ($connU->connect_error) {
die("Connection failed: " . $connU->connect_error);
}
$Name = ($_POST["Name"]);
$MAC = ($_POST["MAC"]);
$Own = ($_POST["Own"]);
$Model = ($_POST["Model"]);
$OS = ($_POST["OS"]);
$Type = ($_POST["Type"]);
$sqlU = "REPLACE INTO SET $table SET MAC='$MAC', Own='$Own', Type='$Type' WHERE Name=$Name;";
if ($connU->query($sqlU) === TRUE) {
echo "PPC-".$Name." Has Been Updated!";
} else {
echo "Error: " . $sqlU . "<br>" . $connU->error;
}
$connU->close();
}
if(isset($_POST['Usubmit']))
{
myUpdate();
}
?>
And that is the code to load the form from php2 in to php1. I am sure it is something simple that I am missing and would appreciate any help. all this code works great, but the submit.
*(I left the DB information out of this code on purpose.)

1.) For Posting(Insert, update and delete via ajax)
This will get you started on how to post via ajax jquery. you can see comments on the code
You can also see that form parameter is set to id="add_content" which is refrenced in the jquery ajax call
<form method="post" id="add_content">
you can also see in the body of the html div that shows image loader when button is click and when result from backend is displayed hence
see sample on that
post.html
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$('#add_content').on('submit', function(e){
e.preventDefault();
alert('ok');
// display a loading image and message
$('#loader').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'post.php',
data:$(this).serialize(),
crossDomain: true,
cache:false,
success:function(msg){
// hide loader to display result
$('#loader').hide();
$('#showposts').fadeIn('slow').prepend(msg);
}
});
});
});
</script>
</head>
<body>
<div id="loader"> </div>
<div id="showposts"> </div>
<form method="post" id="add_content">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="100" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="1001">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="nancy read only">
Type: <select name="Type" id="Type" required="required" readonly="true" value="nancy type">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
<input type="submit" name="add" id="add" value="Add" />
</form>
</body>
example of post.php
<?php
// use strip_tags to avoid html injection that can also leads to xss attck
// sample with assets number
$asset_number= strip_tags($_POST['Name']);
$MAC= $_POST['MAC'];
$Own= $_POST['Own'];
$Type= $_POST['Type'];
// you can check for emptiness eg.
if($asset_number ==''){
echo "asset number is empty";
exit();
}else{
echo "success. my assests no is: $asset_number";
}
?>
sample 2.
if you want fetch records only with or without sending parameters, you can try
Remember to pass jquery library (jquery.min.js) if you are calling it from another page
<script>
$(document).ready(function(){
// set variable payload for formality. though you can pass it to backend as a variable
var payload= 'Am Nancy Mooree';
var datasend = "payload="+ payload;
$('#loader1').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'showresult.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader1').hide();
$('#listposts').fadeIn('slow').prepend(msg);
}
});
});
</script>
<div id="loader1"></div>
<div id="listposts"></div>
showresult.php
<?php
// assuming you are sending a post or get variables to query database
$payload= strip_tags($_POST['payload']);
// query your database to display result to ajax.
echo $result ="Am from database where payload is: $payload";
?>

Related

Input of Textboxes in a Dropdown Menu where I can edit these entries

is it possible to store the input of a Textbox in a Dropdown Menu and then edit/delete it in the Same Textbox after selecting it in the Dropdown Menu?
My Old version where I store the input in a Textfile:
<form action="namenerfassung2.php" method="get">
<p>First Name<br />
<input type="Text" name="namen" autocomplete="off" ></p>
<p>Surname<br />
<input type="Text" name="name" autocomplete="off" ></p>
<input type="Submit" name="" value="Speichern">
<select name="docsApp.options" size="10" multiple="multiple">
<option value="docsaktionen" title="" selected="selected" onclick="einrichtenCheck(this)">Hier Variable</option>
</select>
</br>
</br>
</form>
<?php
if ( $_GET['namen'] <> "" )
{
// Open File
$handle = fopen ( "nameliste.txt", "a");
// write Name
fwrite ( $handle, $_GET['namen'] );
// Add a Space
fwrite ( $handle, " " );
// write Name
fwrite ( $handle, $_GET['name']);
$numberNewline = "\r\n";
fwrite ( $handle, $numberNewline );
// Close File
fclose ( $handle );
echo "Thanks - Your data was saved";
// Exit File
exit;
}
?>
if you want to use php for this, you need ajax calls.
simple solution is to alter that select client side (javascript / jQuery in this case) and then save it to your text file by php, load file contents on page load..
I added three clickable spans in my example: http://jsfiddle.net/b3da/wynhpdyp/
//EDIT: spans are now buttons, form is submiting only names displayed in select :)
//EDIT2: complete working example. Don't forget to save .php and namelist.txt in UTF-8 encoding. Don't use it on public server (or filter your inputs with PHP, before you do):
<?php
if(isset($_POST['names'])) {
$names = $_POST['names'];
file_put_contents('namelist.txt', $names);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function(e) {
var action = $(this).attr('data-action'),
optionVal = $('input[name="namen"]').val()+' '+$('input[name="name"]').val(),
$selectedOption = $('select[name="docsApp.options"] option:selected'),
$nameList = $('select[name="docsApp.options"]');
if(action === 'add') {
$nameList.append($('<option>', {text:optionVal}));
}
if(action === 'edit') {
$selectedOption.text(optionVal);
}
if(action === 'remove') {
$selectedOption.remove();
}
e.preventDefault();
});
$('select').click(function() {
var selectedName = $('select[name="docsApp.options"] option:selected').text();
$('input[name="namen"]').val(selectedName.split(' ')[0]);
$('input[name="name"]').val(selectedName.split(' ')[1]);
});
$('form').submit(function(e) {
var nameList = {},
names,
i = 0;
$('select option').each(function(){
nameList[i] = $(this).text();
i++;
});
names = JSON.stringify(nameList);
$.ajax({
type: 'post',
url: '',
data: {'names':names},
success: function(){
$('.result').fadeIn(200).html('names saved').fadeOut(3000);
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form>
<label>First Name
<input type="Text" name="namen" autocomplete="off" >
</label>
<label>Surname
<input type="Text" name="name" autocomplete="off" >
</label>
<button data-action='add'>add to list</button>
<button data-action='edit'>overwrite selected name</button>
<button data-action='remove'>remove from list</button>
<br>
<select name="docsApp.options" size="10" multiple="multiple">
<?php
$names = json_decode(file_get_contents('namelist.txt'));
foreach ($names as $name) {
echo '<option>'.$name.'</option>';
}
?>
</select>
<br>
<input type="Submit" name="" value="Speichern">
<br>
</form>
<span class="result"></span>
</body>
</html>

select box outside my form code

I have a select box outside my form, When the users selects an option, the right form is being shown. But I want to send the value of the selected option together with the form.
<select id="selection" onchange="showForm()">
<option value="iphone">iPhone</option>
<option value="Android">Android</option>
</select>
<form action="iphone.php" method="post" id="form1">
<input type="text name="username" required>
</form>
<form action="android.php" method="post" id="form2">
<input type="text name="username" required>
</form>
Please note: This is a simple example, I want to know how you can send the value of the selectbox outside the form.
Add to each form a hidden input element:
<input type="hidden" name="selection" class="hiddenselection" />
Use javascript to copy the value on change. In jquery something like this:
$('#selection').on('change',function(){
$('.hiddenselection').val($('#selection').val());
})
function showForm(value) {
$.ajax({
type: "POST",
success: function(value){
if(value =='iphone'){
$("#form2").hide();
}else{
$("#form1").hide();
}
}
});
}
Keep the selected value in hidden field form1 and form2
<select id="selection" onchange="showForm(this)">
<option value="iphone">iPhone</option>
<option value="Android">Android</option>
</select>
<form action="iphone.php" method="post" id="form1">
<input type="text" name="username" required />
<input type="hidden" name="selection" id="iphone_selection" />
</form>
<form action="android.php" method="post" id="form2">
<input type="text" name="username" required />
<input type="hidden" name="selection" id="android_selection" />
</form>
<script>
function showForm(THIS){
var thisVal = $(THIS).val();
if(thisVal == 'iphone'){
$('#form2').hide();
$('#form1').show();
$('#iphone_selection').val(thisVal);
//$("#form1").submit();
}
if(thisVal == 'Android'){
$('#form1').hide();
$('#form2').show();
$('#android_selection').val(thisVal);
//$("#form2").submit();
}
}
</script>
<style>
#form1{
display:none;
}
#form2{
display:none;
}
</style>
https://jsfiddle.net/9tms99p5/
Try to include this script on your code.
<script type="text/javascript">
window.onload = function(){
document.getElementById("selection").onchange();
};
function showForm(){
if(document.getElementById("selection").value == "iphone"){
document.getElementById("form1").style.display = "block";
document.getElementById("form2").style.display = "none";
}else if(document.getElementById("selection").value == "Android"){
document.getElementById("form1").style.display = "none";
document.getElementById("form2").style.display = "block";
}
}
</script>

Prevent the default action when using jQuery for Ajax

I'm trying to prevent the default action when submitting a form with ajax but I believe I have my code wrong as the page seems to do a 'refresh' and the form clears but nothing is sent to the database. I tried adding the link to the php processing script in the 'action' part of the form and it does submit fine to the database so the problem seems to be with my jQuery code.
<script type="text/javascript">
$(document).ready(function(e){
e.preventDefault();
$("#rpack_add_form").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $("#rpack_add_form").serialize(), function(data) {
$('#ajaxResult').html(data);
});
}
});
});
</script>
My form code:
<div id="rpacks_admin" style="display: none;">
<h5>Add A New Recovery Pack</h5>
<form id="rpack_add_form" class='small_form' name='rpack_add_form' action='' method='post'>
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for content</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for contentrm</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add' name='add_rpack'>
</form>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
and my PHP if needed
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
include_once 'bcrypt.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if password and username has been submitted then add to DB
if (empty ($number))
{
echo "You need to enter a recovery pack number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}
The .validate() object has a sendForm parameter. It is set to true by default, but you need to set it to false, as in the code below, to prevent the form from being submitted:
$(document).ready(function () {
$('#rpack_add_form').validate({
submitHandler: function (form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $('#rpack_add_form').serialize(), function (data) {
$('#ajaxResult').html(data);
});
},
sendForm: false
});
});
You can reference the docs for more info.

Issue of submitting form

Have a form like:
<form name="myform" action="All.php" method="get">
<input type='text' id='tx' name='tx' value=''>
<td height="8" align="right" valign="middle">All Cities | Newyork | Police</td></form>
<script type="text/javascript">
function submitform(val)
{
$("#tx").val(val);
document.myform.submit();
}
</script>
And in All.php:
<form method="get" action="index1.php" id="frm1">
<select id="category" onchange="showSelected1();" style="width:150px">
<option></option>
<option value="1" <?php if($_GET["categoryText"] == "Marriages") echo "selected"; ?> >Marriages</option>
<option value="2" <?php if($_GET["categoryText"] == "Birthdays") echo "selected"; ?> >Birthdays</option></select>
<input type="hidden" id="categoryText" name="categoryText" value='<?= $_GET['categoryText']; ?>'/>
<select id="city" onchange="showSelected();" style="width:150px">
<option><?= $_GET['tx']; ?></option>
<option></option>
<option value="1" <?php if($_GET["cityText"] == "Newyork") echo "selected"; ?> >Newyork</option>
<option value="2" <?php if($_GET["cityText"] == "Police") echo "selected"; ?> >Police</option></select>
<input type="hidden" id="cityText" name="cityText" value='<?= $_GET['cityText']; ?>'/>
<input type="button" value="Submit" onclick="formSubmit()"/></form>
<script language="JavaScript" type="text/javascript">
<!--
function showSelected()
{
var selObj = document.getElementById('city');
var cityTextObj = document.getElementById('cityText');
var selIndex = selObj.selectedIndex;
cityTextObj.value = selObj.options[selIndex].text;
}
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--
function showSelected1()
{
var selObj = document.getElementById('category');
var categoryTextObj = document.getElementById('categoryText');
var selIndex = selObj.selectedIndex;
categoryTextObj.value = selObj.options[selIndex].text;
}
//-->
</script>
Means, from first page contents filling into a form itself in All.php. If somebody clicks submit button without changing the selection city, in All.php, its not showing and not taking the city value to index1.php. Why is that?
you can try
document.getElementById("myform").submit();
You have write wrong variable name into your below code
<script type="text/javascript">
function submitform(val)
{
$("#hx").val(val);
document.myform.submit();
}
</script>
your have used hx insted of tx, so your code may be like this
<script type="text/javascript">
function submitform(val)
{
$("#tx").val(val);
document.myform.submit();
}
</script>
change this and try your code again.
I have seen many other problems into your code , learn how to use single quote (') and double quote("). You have written this
value='<?= $_GET['categoryText']; ?>' which is wrong.
correct way is value='<?php $_GET["categoryText"]; ?>'
Update you code according to this and run it again and come back here if there any problem.

How to Inform user about ajax submission?

add.php - html markup.
dbadd.php - serverside script,
addpg.js - clientside including AJAX
RSV- form validator
I'm trying to do following: First validate the form (with RSV), if all things right, Then ajax submit (That's why i'm using myOnComplete). Inform user about submission. If user pressed for the first time save button then insert into db. Else update db.
The problems are:
It inserts data into db table but doesn't inform about succes or error
I can't figure out how to insert data into db If user pressed for
the first time save button or update data.
Tried all possible ways. There is no error. Please anyone help me to fix that.
addpg.js
function myOnComplete() {
return true;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Name field required.",
"required,title,Title field required.",
"required,menu, Menu field required",
"required,parentcheck,Parentcheck required",
"if:parentcheck=1,required,parent,Parent required",
"required,content,Page content field required"
]
});
});
$("#submit_btn").click(function () {
CKEDITOR.instances.content.updateElement();
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
if (message != null) {
//do what you like with the message
}
if (err != null) {
//do what you like with the erro
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
});
dbadd.php
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "All right" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
add.php
<div id="add">
<form id="add_form" method="" action="">
<input type="text" name="name" id="name" size="40" value="" class="text-input" />
<input type="text" name="title" id="title" size="40" value="" class="text-input" />
<select name="menu" id="menu">
<option value="" selected="selected">sample</option>
<option value="1">sample 1</option>
<option value="2">sample 2</option>
<option value="0">sample 3</option>
</select>
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
<select name="parent" id="parent"></select>
<textarea id="content" style="width:100%" name="content"></textarea>
<input type="submit" name="submit" class="button" id="submit_btn" value="Save" />
</form>
</div>
<script type="text/javascript" src="../../core/includes/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/addpg.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/rsv.js"></script>
For the first problem:
Without actually running the code or seeing a live example, I can't say for sure, but it looks like you have the right idea and it's just a syntax/usage error. For example:
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
Someone please scold me if I'm wrong, but aren't "msg" and "err" found in the JSON (result) rather than in xResponse? result.msg (or result["msg"]) and result.err (or result["err"])
If so, also be aware that I -believe- you will get an 'undefined' error when trying to declare both of those variables since only one of them will be present. You might want to wrap them in try/catch blocks.

Categories