Table form dynamically refresh with php and ajax - javascript

I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>

change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});

If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.

Related

Pass/get drop down value into an sql variable without submit button/form

I need to get the value of the selected item on the drop down selection populated from sql database. Then that value is needed in the sql statement to get the specific record.
I already populated the drop down selection. Code below
<select name="year" id="year">
<?php
$query = mysql_query("SELECT distinct Year(fromdate) FROM emp WHERE empcode='$emp' order by Year(fromdate) desc");
while ($row = mysql_fetch_array($query)){
$year = $row[0];
echo "<option value=\"".$year."\">".$year."</option>";
}
?>
</select>
This is the php code for me to get the record using the value from the drop down.
<?php
$sql = mysql_query("SELECT salary FROM emp WHERE empcode='$emp' and Year(fromdate) = '$year'");
$row = mysql_fetch_array($sql);
$salary=$row[0];
?>
Then after that I need to pass the result to a textbox
<input id="salary" name="salary" value="<?php echo $salary; ?>">
What is the code needed for me to pass the selected item value from drop down "year" to PHP variable $year for sql statement? I already looked here in Stack Overflow for the answers but there is no question that look like mine.
What is wrong with people it needs sql why vote down
Do an ajax call to your php file, listening to your select onchange event, like so:
$('#year').on('change', function() {
$.post( "path/file.php", {
year: $(this).val()
})
.done(function( data, status ) {
console.log('data: '+data+' status: '+status);
if(status == 'success'){
//pass to your input ?
//data is what your php file will echo/output
$('#salary').val(data);
}else{
//how do you want to handle http error ?
}
});
});
If you want to get select box value without refreshing page then you need to do code with AJAX.
http://api.jquery.com/jquery.ajax/
On change please pass the year value to AJAX and then in AJAX file write down query for salary getting and after success full result put this value in salary filed using jQuery function

Array Post Ajax

The code I'm working shows all the products and the user assigns the corresponding price to each one through an input. Clicking on a single submit button will update all prices.
The problem is if I put an input for each record the server does not post all the records. Only 500 posts are recorded, not the total. The server does not allow me to modify the php.ini file to change the max_input_vars. This code works but it shows me the array in a single input. How do I make the form submit via javascript and post the entire array in a single input? What other solution can I use?
This is the code:
while ($row = mysql_fetch_array($result_categorias4334x)) {
$precio[] = $row['Precio'];
}
<input type="text" name="precios" value="<?php echo implode(",",$precio); ?>
//POST
if (isset($_POST['ok'])) {
$precios = $_POST['precios'];
$preciosarr = explode(",", $precios);
print_r($preciosarr); }
Before I do that:
while ($row = mysql_fetch_array($result_categorias4334x)) {
$precio = $row['Precio'];
?>
<input type="text" name="precios[]" value="<?php echo $precio; ?>">
<?php
}
But it doesn't post all the records. Only the first 500 records.

How to check if username exists without refreshing page using wordpress

I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>
use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**

How can I prefill my form based on a dropdown menu selection value?

I have a form that has a dropdown selection menu that loads invoice ids from my database. I'm trying to prefill my form based on the value of the invoice selected from the drop down menu. In my database is a column "invoiceidcopy" which contains a value(s) that shows as a selection(s) for my drop down menu. If you notice in my image of my database table below you will notice the first row/record's invoiceidcopy field is blank..in my drop down menu ...of course...the first selection is blank. Ultimately my code below im trying to get to prefill my form works only when i select the blank selection from the drop down menu but not for the other 2 selections? How can I prefill my form based on a dropdown menu selection value?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){
var invoiceidcopy = $('#dropdown-select').val();
e.preventDefault();
$.ajax({
url: "/tst/orders2.php",
data: {
invoiceidcopy: invoiceidcopy
}
}).done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['invoiceidcopy']))
{
$invoiceidcopy= $_GET['invoiceidcopy'];
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = '".($invoiceidcopy)."'";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die();
}
}
?>
it seems the source of your error is from the json data you are sending to php via ajax. you should try enclosing the data key in quotes so that javascript will not replace it with the variable value.
data: {
'invoiceidcopy': invoiceidcopy
}
Another possible source of your error is the sql to select the records from the table.
Have you tried removing the brackets from the variable name like so
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = '".$invoiceidcopy."'";
or even using braces like
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = {$invoiceidcopy}";
Also it will be good to check the value before it is sent to php just to be sure it is what you expect. For example you can do something like:
e.preventDefault();
var invoiceidcopy = $('#dropdown-select').val();
alert(invoiceidcopy); /*display the value to confirm it is correct */
// use the javascript console
console.log(invoiceidcopy);

AJAX does not POST results to php page

I'm trying to create a player edit system for an admin section of a football website. The process goes as follows:
Once a coach has logged in on 'coaches.php', they can then choose what coaching session they want to look at via dropdown, which then populates the 'player' dropdown (done via js below)
form on coach-home.php
<form id="form1" name="form1" method="post" action="coach-player.php">
<label>Activity :</label>
<select name="activity" class="activity">
<option selected="selected">--Select Activity Group--</option>
<?php
include('dbconnect.php');
$sql=mysql_query("select activity from coaches where username='$coach'");
while($row=mysql_fetch_array($sql))
{
$activity2=explode(",",$row["activity"]);
foreach ($activity2 as $activity)
echo '<option value="'.$activity.'">'.$activity.'</option>';
} ?>
</select> <br/><br/>
<label>Player :</label> <select name="username" class="username">
<option selected="selected">--Select Player--</option>
</select>
<input type="text" name="pid" class="pid" id="pid" value="<?php echo $pid; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
JS request on coach-home.php
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").click(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "GET",
url: "username.php",
data: dataString,
cache: true,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
username.php
<?php
if($_GET['activity'])
{
$activity=$_GET['activity'];
$sql=mysql_query("SELECT pid, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$pid=$row['pid'];
$username=$row['username'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
Once all of this is done, the coach submits the form, taking them to coachplayer.php. This is where the problem begins.
coachplayer.php is a template page, with empty fields filled with echo's, to echo the player details where necessary. A query runs to get the id of the selected player, bring up their details and fill the page. Instead, however, it echos what usually comes up if the query cannot find a matching result via $playerCount as shown below, saying "Player doesn't exist".
coach-player.php Query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['username'])) {
// Connect to the MySQL database
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE username='$puser' LIMIT 1");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$username = $row["username"];
$pid = $row["pid"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
}
} else {
echo "That player does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
The issue here is that whilst it is defined in username.php, the pid does not get sent over and saved when the rest of the form on coach-home sends. I have tried changing from GET to POST with no avail. I have also just tried using the 'username' instead of 'pid' but I get "That player does not exist."; - meaning no variables outside of the ajax request is sending.
What is it that needs to be altered to save and post the data mentioned?
Looking at your code the $username and $pid variables are not being passed to either coach-home.php or coach-player.php, thus when you try to write to the database the parameter $_GET['username'] or $_GET['pid'] is set (because you have provided an input field in your form), but it has no value! and thus there is no player that exists with an empty pid or username.
Also note that in the form you have specified the method as post, but in the php you are referencing the get hash. If you submit by post you access variables with $_POST, submit with get you access with $_GET.
My suggestion is to use the session hash to store the username and pid of the user.
When the user logs in:
$_SESSION['username'] = 'jonnysmith'
$_SESSION['pid'] = '45'
This will mean when you initiate the database query you will just reference the session value instead of the get value for the parameter.
Delete your input field for username/pid in the form.
Call session_start(); in your config.php file to enable the session hash.
Call session_destroy(); when the user logs out to clear the session hash.
Also you will need to logout and log back in for the changes to take effect and the value of username/pid to be stored in the session hash.
Happy hunting!
Your regex is actually replacing your whole username variable with ''
Based on your comment, I've done a test match with the name 'Radamel Falcao' and echo-ed $puser and I got empty string, so apparently, this regex is your problem.
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);

Categories