I have an html form that I submit to a php server. If I submit the form the standard way with a submit button and an action="screen_custom.php", then it works fine. I see a page full of valid JSON data.
But if I submit the form using a jquery ajax call, then an empty json array is returned. I believe the php is unable to find the form values for some unknown reason. Anyway, how do I debug the php during an ajax call? The response must only include the data needed to populate a jquery DataTable. If I echo debugging output, then the datatable will fail to populate.
Here's some code that successfully submits the form to the php and returns good json data.
<form id="criteriaForm" method="post" action="screen_custom.php">
<table>
<tr>
<th>Filter By</th><th>Criteria</th><th title="Show this column">Show</th>
</tr>
<tr>
<td><label title="Percentage increase">Appreciation Potential (%)</label></td>
<td>
<select name="upside">
<option value="any">Any</option>
<option value="gt0">> 0%</option>
<option value="gt10">> 10%</option>
</select>
</td>
<td><input type="checkbox" id="showUpside" name="showUpside" value="true">
</tr>
</table>
<input type="submit" value="Run">
</form>
Here's some code that fails to return the same json data:
<form id="criteriaForm" method="post" action="">
<table>
<tr>
<th>Filter By</th><th>Criteria</th><th title="Show this column">Show</th>
</tr>
<tr>
<td><label title="Percentage increase">Appreciation Potential (%)</label></td>
<td>
<select name="upside">
<option value="any">Any</option>
<option value="gt0">> 0%</option>
<option value="gt10">> 10%</option>
</select>
</td>
<td><input type="checkbox" id="showUpside" name="showUpside" value="true">
</tr>
</table>
<button type="button" onclick="runCustomScreen()">Run</button>
</form>
And the javascript:
function runCustomScreen() {
$('#customTable').DataTable({
"ajax": {
type: 'POST',
url: "screen_custom.php",
data: $('#criteriaForm').serialize(),
complete: function(jqXHR, textStatus) {
console.log("Run was successful, textStatus="+textStatus);
},
error: function(e, textStatus, errorThrown) {
alert("textStatus="+textStatus +", errorThrown="+errorThrown);
}
}
});
return false; //needed if called by onclick event
}
Here's the parts of the php that handle the form data and return the json:
$upside = $_POST["upside"];
$sql = "SELECT * FROM stocks " .$where;
//echo '<script>'
//echo 'sql=' .$sql .'<br>';
//echo 'console.log(' .$sql .')';
//echo '</script>';
$rs = mysql_query($sql);
//store result in an array
$results = array();
while($row = mysql_fetch_object($rs))
{
$results[] = $row;
}
$data = json_encode($results);
echo '{"data":' .$data .'}';
//close the db connection
mysql_close($connection);
Note that if I uncomment any but the last echo, then the datatable won't populate. So how can I debug this?
I figured out how to debug it. In the chrome debugger, select the Network tab, then select "screen_custom.php" from the list, then select the Response tab. It shows the output from the php. I uncommented the echo sql statement and could see that in fact, the form parameters are not being read, as I suspected.
Then I googled on that problem and found the solution was to modify the data paramenter js as shown below:
data: function(d) {
var form_data = $('#criteriaForm').serializeArray();
$.each(form_data, function(key,val) {
d[val.name] = val.value;
});
},
I don't know why the first method didn't work as I could see the correct parameters being sent in the header. But this works.
Did you tried to use the isset($_POST['value']) method on your php script? where value is the name that you will assign to your submit button.
Related
I have a PHP file which SELECT's all from the row found based on an SQL query. When I put the echo in a div, I get all information, but when I try to echo it into an input box in a form, it does not shows.
What am I doing wrong?
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
DO_CUSTEDIT.PHP
$custName = $_POST['custName'];
$query = "SELECT * FROM `CustDB` WHERE CustName LIKE '%$custName%'";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
$custID = $row['CustID'];
......;
}
if (!$result) {
echo $db->lastErrorMsg();
$db->close();
exit;
} else {
echo $custID;
echo ......;
$db->close();
exit;
}
EDITCUST.PHP / Javascipt
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
if (strMessage == "Customer updated successfully") {
$("#message").text(strMessage);
$("#neweditform").get(0).reset();
} else {
$("#message").text(strMessage);
}
}
});
});
});
</script>
EDITCUST.PHP / HTML
<form id="editcustform" name="editcustform" action="" method="post">
<div class="row">
<div class="column-half" style="background-color:#fff">
<table>
<tr>
<td>
<a>Customer ID</a>
</td>
<td>
<div class="inputb">
<input type="text" name="custID" value="<?php echo (isset($custID)) ? $custID: ''; ?>" readonly/>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<table style="table-layout:fixed">
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="subeditcust" type="submit" class="mainbtn">Create</button>
</td>
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="reseteditcust" type="reset" class="mainbtn">Reset</button>
</td>
</table>
</div>
</form>
<input type="text" name="custID" value="<?php echo (isset($custID) ? $custID: ''); ?>" readonly/>
Replace this line with yours it will work. IA
It seems you have two different files, right? DO_CUSTEDIT.PHP and EDITCUST.PHP
The variables are being created on DO_CUSTEDIT.PHP and the when you are creating the HTML code those variables ($custID) are not setted.
Is one file including or requiring the other?
EDITCUST.PHP is your first page from you are submitting form to DO_CUSTEDIT.PHP
When you land on EDITCUST.PHP variable $custID is not created
When the form is submitted through ajax, the ajax returns the data inform of object or array depending on how you are echoing the data from DO_CUSTEDIT.PHP
I would recommend to use json_encode() php function to return inform of array
To debug the value by logging the data in console (though function console.log())
After returning the value from ajax, you have to populate the value in form through jquery something like $(input[name="custID"]).val( data.custID )
I managed to figure it out!
DO_CUSTEDIT.php / PHP
$results = array($custID, $custName);
echo json_encode($results, JSON_PRETTY_PRINT);
EDITCUST.php / HTML
<input type="text" id="custID" name="custID" value="" readonly/>
<input type="text" id="custName" name="custName" value="" readonly/>
EDITCUST.php / JS
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: 'json',
success: function(data){
document.getElementById('custID').value = data[0];
document.getElementById('custName').value = data[1];
}
});
});
});
</script>
I am using 2 drop down lists. One list comes from Ajax code. My question is this, how do I keep the ensure the value remains in the second drop down while the form is reloaded. I am using trigger change event for value of model drop down.
My code is below
---i
Trigger Change Jquery i used from stack overflow.
--i have one more table name model the value of vehicle comes from make table.
--
<?php
include "conn.php";
$exe=$con->query("select * from make");
?>
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$('#make').trigger("change");
//console.log(make);
function getModel()
{
var mid= document.getElementById("make").value;
//console.log(mid);
$.ajax({
type:"POST",
url :"model.php",
data:"makeid="+mid,
success:function(ans)
{
document.getElementById("model").innerHTML=ans;
}
});
}
</script>
</head>
<body>
<form method="post">
<table align="center">
<tr>
<td>Make</td>
<td>
<select name="make" id="make" onchange="return getModel()">
<?php
while ($row=$exe->fetch_object())
{
?>
<option value="<?php echo $row->make_id?>">
<?php if(isset($_POST['make']) && $_POST['make']==$row->make_id) echo "selected";?>
<?php echo $row->make_name?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Model</td>
<td><select name="model" id="model">
<option value="">.....</option>
</select></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
This code will store your dropdown value to the storage
let dropdownModel= document.getElementById("model").value
localStorage.setItem("myValue", dropdownModel);
This code will load your stored value from your dropdown and put it back to it
document.getElementById("model").value = localStorage.getItem("myValue");
Use jquery to call on change,
$(document).ready(function(){
$("#make").on('change', function(){
var make_id= $("#make option:selected").val();
$('#model').empty();
$.ajax({
url: 'model.php',
type: 'POST',
dataType: "text",
data: {
make_id: make_id,
}
}).done(function(data){
$('#model').html(data);
});//ajax success function
}).change();
});
in model.php make a drop down like this
<option>A</option>
<option selected >B</option>
With this code you can get the second drop down names model value. Then you can select it when the form has loaded.
<script>
$(document).ready(function() {
$("#make").trigger('change');
$("#model").selectedIndex = <?php echo $_POST['model']?>;
});
</script>
Here is my dilemma. A multi-select drop-down displays pre-selected options. When the user makes any changes, I'm running some code in the PHP action file (called through a submit button). I'm trying to accomplish this using a flag and updating the flag in the onchange event of "select option". The rest is working fine. I just wanted to execute the queries in action file only when the user changed selections in drop down rather than every time the form is submitted. However I'm unable to pass the flag successfully. I know I'm missing something basic and have spent two days looking at it. Any help is appreciated.
The relevant code is pasted below:
//Initialize flag
<?php
...
$multi_prog_change_flag = '0';
...
?>
//Hidden Form Element
<form action="update_u.php" method="post" id="cForm" name="cForm" onsubmit="return validateForm()" autocomplete="off">
...
<?php echo '<input type="hidden" id="email" value="'.$email.'"> ';?>
<?php echo '<input type="hidden" id="multiprogchangeflag" name="multiprogchangeflag" value="'.$multi_prog_change_flag.'"> ';?>
...
// Drop-down Element where update is triggered
<tr id="odd">
<td><select id="programName" name="programName[]" onchange="updateflag();>" multiple="multiple" size=10>
..
<option name="drop1" value ="<?php echo $data['Program_Id'] ?>" <?php if ($data[curr_prog] == '1') echo 'selected="selected"'; ?>> <?php echo $data['Program_Name'];?></option>
..
</select>
<input type="hidden" id="pNames" name="pNames" value="" />
</td>
</tr>
// Function to update flag
function updateflag() {
<document.getElementById("multiprogchangeflag").value = "1";
}
// update_u.php PHP Action File
$multi_prog_flag=mysql_real_escape_string($_POST['multiprogchangeflag']);
if ($multi_prog_flag == '1'){
$multi_prog_delete_query=mysql_query("UPDATE multi_prog_access SET is_act = '0', Updated_by = '$updatedby', update_timestamp = NOW() WHERE user_id = '$useid'");
$count = count($multi_prog_names);
for($i=0;$i<$count;$i++){
$multi_prog_ID=$multi_prog_names[$i];
$multi_prog_update_query=mysql_query("INSERT INTO multi_prog_access (user_id, Prog_id, created_by, is_act, Update_timestamp) VALUES ('$ids','$multi_prog_ID', '$updatedby', '1', NOW())");
}
}
So I tried Google before I posted this and didn't find anything that suited my needs. I was hoping you guys could help.
I have a form simple just a drop down box and a checkbox. The drop down box shows a list of names pulled from a database. The checkbox is initially unchecked. What I want to happen is that when the user clicks on the box the page will refresh and update the drop down box to include more names in the list depending up on the sql query that I have set up.
so form looks like this :
<form name="search" method="post" action="myaction.php">
<table width="100%">
<tr>
<td><label>Select a name to search for:</label></td>
<td><select name='mynames'><?php
echo "<option value='0'>-- Select a Name --</option>";
mysql_data_seek($request_staff, 0);
while ($row_mynames = mysql_fetch_assoc($mynames)) {
echo "<option value='".$row_mynames['myID']."'>".$row_mynames['firstName'] . " " . $row_mynames['lastName'] ."</option>" ; }?></select></td>
<td><input type="checkbox" name="checkActive" value="1">Include additional Names</td>
<td><button id="submit" type="submit" ><span>Search</span></button></td>
</tr>
</table>
</form>
I think I may need some javascript but I wasn't sure I found several things that suggested just checking when the submit button is checked, but I need it to check before the form is submitted.
the sql statement is pretty simple just
$sql = "Select myID, fName, lName, extraNames from myTable $mysearch;
I want a where clause like this : (I know this isn't correct code but this is what I want it to do)
if checkbox is checked {
$mysearch = "";
}else {
$mysearch = "Where extraNames = 1";
}
I have some javascript that checks a checkbox on another page, but I couldn't figure out how to change the sql query (written in php) with the javascript. Thanks for any help you may provide.
HTML
<form name="search" method="post" action="myaction.php" id="myForm">
<table width="100%">
<tr>
<td><label>Select a name to search for:</label></td>
<td><select name='mynames'><?php
echo "<option value='0'>-- Select a Name --</option>";
mysql_data_seek($request_staff, 0);
while ($row_mynames = mysql_fetch_assoc($mynames)) {
echo "<option value='".$row_mynames['myID']."'>".$row_mynames['firstName'] . " " . $row_mynames['lastName'] ."</option>" ; }?></select></td>
<td><input type="checkbox" name="checkActive" value="1" onclick="$('#myForm').submit();">Include additional Names</td>
<td><button id="submit" type="submit" ><span>Search</span></button></td>
</tr>
</table>
</form>
PHP
$sql = "Select myID, fName, lName, extraNames from myTable";
if (!empty($_POST['checkActive'])) {
$sql .= "WHERE `extraNames` = 1";
}
Since the web page is running in a browser on the client side (the HTML) and the SQL query is running on the server (the PHP), you'll need to add a parameter to the page (the HTML) that indicates if the check box was clicked. When the form is submitted to the myaction.php URL on the server, you can then feed the value of that parameter into the if checkbox is checked statement.
I have a drop down if the value selected in drop down its shows the data in html table regarding the value selected in dropdown, i have search box now search is working fine it displays result without refreshing the page ,problem is now its showing the drop down html table and searched value result on the same page ,but i want to display the searched result on the same html table,see my code below,can anyone guide me to do this thanks.
<html>
<select name="client" id="client" style="margin:-8px 0 0 1px;background-color:#E8E8E8;width:104px;position: absolute;">
<option value="">Select Client</option>
<?php
i am connection to mysql
$sql=mysql_query("xxxxxxxxxx");
$clientid=$_GET['clientid'];
while($row=mysql_fetch_assoc($sql))
{
if(strlen($_GET['clientid'])>0 && $_GET['clientid']==$row['clientid'])
{
print' <option id="client" name="client" value="'.$row['clientid'].'">'.$row['clientid'].' </option>';
}
else{
print' <option id="client" name="client" value="'.$row['clientid'].'">'.$row['clientid'].' </option>';
}
}
?>
</select>
<form id="lets_search" action="" style="width:0px;margin:-27px 0 0;text-align:left;">
<input type="text" name="region" id="region">
<input type="text" name="country" id="country">
<input type="submit" value="search" name="search" id="search">
</form>
<div id="content"></div>
<table id="CPH_GridView1" >
<thead class="fixedHeader">
<tr>
<th style=" width:103px">Region </th>
<th style=" width:102px" >Country </th>
<tbody id="fbody" class="fbody" style="width:1660px" >
<div id="content">
<?php
$client_id = $_POST['title'];
if($client_id!=""){
$sql_selectsupplier = "xxxxxxxxxxx";
echo ' <td style="width:103px" class=" '.$rows["net_id"].'">'.$rows["clientid"].'</td>
<td style="width:102px" id="CPH_GridView1_clientid" class=" '.$rows["net_id"].'">'.$rows["region"].'</td>';
</div>
</tbody>
</table>
</html>
//javascript on the same page
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var valueregion = $('#region').val();
var valuecountry = $('#country').val();
$.post('clientnetworkpricelist/testdb_query.php',{valueregion:valueregion,valuecountry:valuecountry}, function(data){
$("#content").html(data);
});
return false;
});
});
</script>
testdb_query.php
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'xxxxxx';
$dbPassword = 'xxxxxxxxxxxx';
$dbDatabase = 'xxxxxxxxxxxxxx';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
$region=$_POST['valueregion'];
$country=$_POST['valuecountry'];
$clientid=$_POST['clientid'];
if (strlen($region) > 0 && $region!="" ){
$sql_search.= " AND s.region = '".$region."' ";
}
if (strlen($country) > 0 && $country!="" ){
$sql_search.= " AND s.country = '".$country."' ";
}
$query = mysql_query("SELECT * FROM supplierprice s,$clientid c WHERE s.supp_price_id = c.net_id $sql_search");
echo '<table>';
while ($data = mysql_fetch_array($query)) {
echo '
<tr>
<td style="font-size:18px;">'.$data["region"].'</td>
<td style="font-size:18px;">'.$data["country"].'</td>
</tr>';
}
echo '</table>';
?>
for best practice separate your php code from html - get all the data from the db in an array before rendering the html, and afetr that just use foreach in the html to parse each row.
put the DB login and connection in a differnet file and inlcude it with require_once() at top of the page
display errors for better understandig of your script
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
comment "i am connection to mysql" this line since it will bring an error in this format
After connecting to the DB initialize
$sql_search = ""; // otehrwise it will bring a notice when calling "$sql_search.="
and check the http_request so that it won't bring any errors when first accessing the page without the $_POST data
if ( $_SERVER['REQUEST_METHOD'] === 'POST')
{
//code for displaying the new table with the post data
}
Ok, I see two issues with your HTML code. One is that you are using two html elements with same ID ("content"), which is not the purpose of ID. Second, placing div inside the tbody is not valid HTML.
From your explanation I got that you are trying to show the result of both the actions in a single table.
So, remove first div
<div id="content"></div>
from code and update code inside $.post to something like this
$("#CPH_GridView1").append(data);
Also, remove the div inside tbody as well.