HTML form data not being posted to use in SQL query - php

this should be simple but I have lost my way
simple form on HTML page - select Men, Women or Junior
then send that that value to a php page to perform SQL query and find all the Men, Women or Juniors using the variable "$trigen"
display the results on the HTML page using AJAX
if I set $trigen manually it works, but not when I choose the option in the form as set out in this code:--
my HTML:-
<!DOCTYPE html>
<html>
<div class="entry-content">
<form action="/getcustomer.php" method="POST">
<label for="trigen">Choose a gender:</label>
<select id="trigen" name="trigen">
<option value="Men">Men</option>
<option value="Women">Women</option>
<option value="Junior">Junior</option>
</select>
<button class="btn btn-primary text-center btn-block btn-flat" style="h2; margin: 20px; color:black; " name="trilookup" type="submit" onclick="showResults()"> Search</button>
</form>
</div>
<div id="results">Results go here if it works....</div>
<script>
function showResults(str) {
var xhttp;
if (str == "") {
document.getElementById("results").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
</script>
then my php code in "getcustomer.php"
<?php
//connect to the database
$conn=mysqli_connect('localhost','wetsuder_user1','user123','wetsuder_finder');
if($conn){
}
else{
echo "Sorry there is a connection error".mysqli_connect_error();
}
$trigen=$_POST['trigen'];
//this is the search
$sql = "SELECT id, Gender, Wetsuit FROM wp_wetsuitdata WHERE Gender = '$trigen'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["Gender"]." ".$row["Wetsuit"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

Your button is causing a form submission. Just add preventDefault() as the first line of your showResults function and it will prevent the form from submitting naturally. You're handling the form submission via ajax. Also you don't need to have an action or method on your <form tag for the same reason. Another way of preventing the form from submitting is like this: <form onsubmit="return false"
Also, change your function to find the value you want to send, since you're not actually passing that value through the function call str
function showResults() {
preventDefault(); // prevents form submission
// get the value
let str = document.getElementById('trigen').value;
// check to make sure it's there...
if (!str) return alert("Please select an option...");
var xhttp;
......
You're sending the data via GET (when you use the ?q=val on your URL, the data is being sent through GET. So, you can receive it in your PHP with this:
$trigen=$_GET['q'];

Related

Why am I not receiving any response from my PHP page and no other errors?

I have 2 pages, practice.php and addtocart.php. In practice.php, I gather info from a form and send the info using AJAX to addtocart.php. This page then connects to the database and inserts my values. However I am not receiving any response from addtocart.php and no data is being inserted in the database.
I have been trying to figure out the problem but cannot seem to find it. Please help.
practice.php
//form from which addtocart is being called
<form id="mehendicones">
Color: <input list="mehendi_color" class="mehendi_color"
id="mehendi_color1">
<datalist id="mehendi_color">
<option value="Black">
<option value="White">
<option value="Brown">
<option value="Dark Red">
</datalist>
<br>
<p id="price">17</p>
Quantity<input type="number" min="5" max="15"
id="quantity_mehendi_color" step="1">
<input type="submit" value="ADD TO CART" style="text-align:center;"
onclick="addtocart()" >
</form>
function addtocart() {
var request = new XMLHttpRequest();
var url = "addtocart.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-
urlencoded");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
alert(request.response);
}
};
var pdetails = "mehendi cones";
var pquantity = document.forms["mehendicones"]
["quantity_mehendi_color"].value;
var pcolor = document.forms["mehendicones"]
["mehendi_color1"].value;
var price = document.getElementById("price").innerHTML;
var data = ({
"pdetails": pdetails,
"pquantity": pquantity,
"pcolor": pcolor,
"price": price
});
request.send(data);
}
addtocart.php
<?php
include 'includes/database.php';
// Handling data in JSON format on the server-side using PHP
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST
//method
if($_POST){
$v= json_decode(stripslashes(file_get_contents("php://input")));
echo json_encode($v);
$v->pdetails;
$v->pcolor;
$v->pquantity;
$v->price;
$fname=$_SESSION['firstname'];
$id=$_SESSION['id'];
$nam=$fname.$id;
$sql="INSERT INTO ".$nam."
(userid,pdetails,price,pquantity,pcolor) VALUES
('$id','$pdetails','$price','$pquantity','$pcolor');";
$result=mysqli_query($con,$sql);
if(mysqli_num_rows($result) > 0){
echo "added to cart";
}else{
echo "couldnot add to cart..try again";
}
}
mysqli_close($con);
?>

How to call PHP function using Jquery and catch return type

I want to call PHP function with the help of JQuery and I also want that Jquery code catch the return type of the calling function for further processing...........
My jQuery code is:
$(document).ready(function(){
$('#ibtn_save').click(function(){
$.post('PHP/newdep.php', { dep_id: newdep.itext_depid.value }, function(result){
if(result == 'exist'){
$('#error_div').html(result).show();
}
});
});
});
My PHP Code is:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$deptid = mysql_real_escape_string($_POST['dep_id']);
$catcher = save_fxn($deptid);
echo $catcher;
}
function save_fxn($ltxt_deptid)
{
$query = "SELECT * FROM table_mstr_department WHERE DeptId='$ltxt_deptid'";
$query_result = mysql_query($query);
if (is_resource($query_result) && mysql_num_rows($query_result) > 0)
{
$sql_result = mysql_fetch_assoc($query_result);
return "exist";
}
else
{
$query = "INSERT INTO table_mstr_department (DeptId, DeptName) VALUES ('$ltxt_deptid','$ltxt_deptname')";
$output = mysql_query($query);
if (!$output)
{
echo "Data not inserted successfully!";
}
return "success";
}
}
?>
and HTML code is as
Please fix the errors below!
<p> <label for="dep_id">Department Id :</label> <input id="itext_depid" name="text_depid" type="text" /> <span class="sdepid"></span> </p>
<p> <label for="dep_name">Deparment Name :</label> <input id="text_depname" name="text_depname" type="text" /> <span class="sdepname"></span> </p>
<input type="submit" id="ibtn_save" name="btn_save" value="Save">
Well, your code seems ok. Since you haven't specified what is not working for you, I'm going to guess that the page reloads as soon as you press your "Save" button, not giving the ajax call the time to complete and to show your result.
This is happening because you use a type=submit button, which will submit your form after completing the onclick handler. The ajax call is performed, but by the time it returns, the calling page has gone.
There are two ways around this. You could change your input to anything beside a type=submit or type=image, for example, you could use:
<input type="button" id="ibtn_save" name="btn_save" value="Save">`
Or, you could have the onclick handler suppress the default action of the submit button, by having it return false:
$(document).ready(function(){
$('#ibtn_save').click(function(){
$.post('PHP/newdep.php', { dep_id: newdep.itext_depid.value }, function(result){
if(result == 'exist'){
$('#error_div').html(result).show();
}
});
return false;
});
});
Does this solve your problem? If not, please do specify what behavior you are encountering, and why you would like it to behave differently.

Confirm button before running deleting routine from website

I have a page on my website that is dynamically created with information from an SQL database. As well as the data being displayed a delete link is also created for each record which links to a php file called deleteRecord.php that deletes that record from the database.
Is there any way I can incorporate a confirmation message so that when the Delete link is clicked it will only run the deleteRecord.php file if the response is Yes?
You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
Delete
In a function:
Delete
and then put this in <head>:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
Delete
And put this in <head>:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"] is set.
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
You can do it with an confirm() message using Javascript.
Try this one :
<script type="text/javascript">
var baseUrl='http://example.com';
function ConfirmDelete()
{
if (confirm("Delete Account?"))
location.href=baseUrl+'/deleteRecord.php';
}
</script>
echo '<a type="button" onclick="ConfirmDelete()">DELETE ACCOUNT</a>';
<?php
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));
if(isset($_POST[add]))
{
$sno = mysqli_real_escape_string($con,$_POST[sno]);
$name = mysqli_real_escape_string($con,$_POST[sname]);
$course = mysqli_real_escape_string($con,$_POST[course]);
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";
//echo $query;
$result = mysqli_query($con,$query);
printf ("New Record has id %d.\n", mysqli_insert_id($con));
mysqli_close($con);
}
?>
<html>
<head>
<title>mysql_insert_id Example</title>
</head>
<body>
<form action="" method="POST">
Enter S.NO: <input type="text" name="sno"/><br/>
Enter Student Name: <input type="text" name="sname"/><br/>
Enter Course: <input type="text" name="course"/><br/>
<input type="submit" name="add" value="Add Student"/>
</form>
</body>
</html>
Another method using both onlcick & form submit button with php record id value (record to be delete).
Use php code to get the record ID to be deleted. This is working for me.
<form action="deleteRecord.php" method="POST">
<button onclick="return confirm('Are you sure! want to delete?')" type="submit" name="id" value="<?=$record['id'];?>" >Delete</button>
</form>
deleteRecord.php example file
<?php
$con=mysqli_connect("localhost","root","","dbname") or die(mysqli_error($con));
if(isset($_POST['id']))
{
$id = mysqli_real_escape_string($conn, $_POST['id']);
$query = "DELETE FROM table_name WHERE id='$id' ";
$query_run = mysqli_query($conn, $query);
}
mysqli_close($con);
if($query_run)
{
echo "Deleted Successfully";
exit(0);
}
else
{
echo "Not Deleted";
exit(0);
}
?>

change form input through drop down box AJAX and PHP

I've been trying to use AJAX and PHP to create a dynamically changed form where selecting an index on the drop down box automatically changes the type of input that is displayed on the form. I use a select box on the form that onchange() submits to the AJAX function. The function uses XML to call the PHP file. The the 2 types of inputs that I'm trying to switch between are a file upload and a drop down box that is populated by data that I have on a remote database. When I select the option for the file upload input, it displays fine, but the PHP database drop down box does not display when I select that option.
Can anybody tell me what I'm doing wrong?
Here is the code I have right now:
File Name: test.php
<html>
<body>
<head>
<script>
function getInputs(str) {
var xmlhttp;
if (str == "") {
document.getElementById("display").innerHTML = "";
return;
}
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "grabtest.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<form action="">
<select id='RecipeSelect' onchange='getInputs(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New file</option>
<option value='E'>Existing file</option>
</select>
<br>
<div id="display"></div>
<br>
</form>
</body>
</html>
File Name: grabtest.php
<?php
$q=$_POST["q"];
//connect to database on server
$con=mysqli_connect("connection","loginname","password","DBname");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($q=""){
echo "";
}
elseif ($q="N"){
echo "Select file to upload: <input type='file' name='newfile'>";
}
elseif ($q="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from TableName");
echo 'Recipes: <select name = "name">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Recipes"] . '</option>';
}
echo '</select><br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
}
mysqli_close($con);
?>
You are passing q in the query string and using POST. You need to either use GET or send q, in the send method of the XHR.

PHP/Javascript post js variable to php page

Though a novice in javascript, I need to take javascript variable (an array) reflecting what a user has done on client side and post it to a PHP server page on submit.
It was suggested that I include this as a value in a hidden field in a form to post to the php page. However, since the JS variable is dynamically created by the user, I can't write to the page for inclusion in the form unless I call a function that refreshes the page. To avoid a double page refresh, I'd prefer to have the submit function both grab the data and simultaneously post it to the php script. AJAX if I understand correctly, should not be needed because I'm okay reloading the page once on submit. I just don't want to reload twice.
The following uses the function suggested by Andrew to set the js variable and post. Th form posts as I get the other hidden variable in the form but I am not getting the variable set by js, possibly because there is a mistake with the naming of the variables.
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function postData(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
window.location = "posttoserver.php?data="+options[i].value;
}
function setTheValue(val) {
var options = document.getElementById(listBoxID).options;
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<form id="myForm" action="getdata.php" method="get">
<input type="hidden" name="data" />
<input type="hidden" name="mode" value="savedit">
<button onclick="setTheValue(options)">Submit Data</button>
</form>
</body>
</html>
On the other end I have in getdata.php:
<?php
$mode = $_REQUEST['mode'];
$option = $_REQUEST['data'];
echo $mode;
echo $option;
print_r ($option);;
?>
Finally solved it days later with document.getElementById('varname').value
For newbs like me, document.getElementById does not merely retrieve data as you might think and most documentation mentions. It also sets data.
The key is to write the statement backwards and also (as you must do to retrieve a value) put id== into the element you want to set.
If you write var test = document.getElementById('text'); and you have put id="text" in some field, it will retrieve the value of text. That's what the usual documentation mentions. However, if you write:
document.getElementById('varname').value = "dog"
it will insert "dog" into the element that contains id=varname.
While that may be obvious to the more experienced, it certainly confused me.
Following code works.
<html>
<head>
<script>
function Post(data)
{
document.getElementById('varname').value = data
}
</script>
</head>
<body>
<form action = "" method="get">
<input id="varname" type="hidden" name="d">
<button onclick="Post('dog')">Post to Server</button>
</form>
</body>
</html>
You can go ahead and create a form like you normally would with an empty hidden field:
<form id="myForm" action="posttoserver.php" method="get">
<input type="hidden" name="data" />
...
<input type="submit" value="Submit" />
</form>
And you can use a JavaScript function to set the value of the hidden field:
function setTheValue(val) {
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
You can then call the function setTheValue(val) when your button is clicked or whatever.
I hope this helps!
jQuery actually makes this very simple. You have the right idea but using window.location is going to change your page. What you are looking to do is make a async request to another url while you remain on your current page.
http://api.jquery.com/jQuery.ajax/

Categories