Using Select Box to Update Display Query - php

I am just learning Ajax and am trying to update a mysql select query to filter results. I think the query is working fine, but not sure that I have the event working correctly.
Here is my HTML with the selection;
<div class="volunteers">
<h1>Volunteers</h1>
<div class="volunteerSelection">
<select id="vtSelect" name="volunteerS">
<option value="1">Comittee</option>
<option value="2">Day of Event</option>
</select>
</div>
<div id="volunteers">
</div>
</div>
This is the script that displays the data;
I have updated this to the suggestion and it works fine. Then I started working on my PHP and mysql query. See below;
$(document).ready(function(){
$('#vtSelect').change(function (e) {
e.preventDefault();
var selectedOption = $(this).find('option:selected');
$('#vtSelect option').removeAttr('selected');
$(selectedOption).attr('selected', 'selected');
var selectedOptionValue = $(selectedOption).val();
$.ajax({
type: "POST",
url: "includes/backDataProcess.php",
data: {
data: selectedOptionValue
},
success: function (data) {
$("#volunteers").html(data);
}
});
});
});
This is the PHP with the select query; I have update this and am getting data. I updated the name in the select tag, but I am not getting the select tag value in the query. When I comment out the post data and just fill in a value it posts fine. I am not getting any errors, it is just displaying 0 results.
<?php
include('readerConnect.php');
$sql = "SELECT * FROM contacts prc
JOIN states as st
ON (prc.stateId = st.idStates)
INNER JOIN volunteers as v
ON (prc.idContacts = v.contactId)
INNER JOIN volunteerType as vt
ON (v.volunteerTypeId = vt.idVolunteerType)
WHERE (volunteerTypeId = 1 /*`mysql_real_escape_string('$_POST[volunteerS]')`*/)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='contacts'>
<div class='contactName'>" . $row["firstName"] ." " . $row["lastName"] ."</div>"
."<div class='contactAddress'>" .$row["address1"] ." " .$row["address2"] ."<br>"
.$row["city"] ." " .$row["state"] ." " .$row["zip"] ."</div>"
."<div class='contactVolunteer'>" .$row["volunteerTypeId"]
."</div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I am not sure exactly where the issue is, I have tried both change and onchange to update, do I need an update button? I thought jquery would be able to do this with no update. Any help is greatly appreciated.

There are several obvious problems in your jQuery code. If you open your browser console you should see error onChange is not a function since there is no such jQuery method. You want change() or on()
Also you create a function showVolunteers() but it never gets called.
try:
$('#vtSelect').change(function (e) {
e.preventDefault();
var selectedOption = $(this).find('option:selected');
$('#vtSelect option').removeAttr('selected');
$(selectedOption).attr('selected', 'selected');
var selectedOptionValue = $(selectedOption).val();
$.ajax({
type: "POST",
url: "includes/backDataProcess.php",
data: {
data: selectedOptionValue
},
success: function (data) {
$("#volunteers").html(data);
}
});
});
Should you encounter more problems, use browser console network tab to inspect ajax request, and always use console to check for errors

Related

How to get an input value right in a MySQL SELECT (Ajax on WordPress)

I'm trying to use an input field value on a SELECT query, but it's returning as null or as an array.
I got the value with jQuery and I'm trying to use it to do a query with Ajax on WordPress.
My HTML
<input name="estado" type="radio" id="some-id" value="some-value">
My jQuery
$("#col1 input:radio").change(function(){
var ufname= $(this).val();
$.post({
url: "http://192.168.64.2/monsoy/site/variedades/resultados-de-produtividade/estado-variedade",
type: "POST",
data: ufname,
success: function(data) {
$("#col2").html(data);
},
error: function(e) {
console.log( e);
}
});
return false;
});
My PHP
$sSQL = " SELECT mapa_produtividade_variedade, mapa_produtividade_uf
FROM " . $wpdb->prefix . "mapa_produtividade
";
$sSQL .= " WHERE mapa_produtividade_uf = '".addslashes(strip_tags($_POST[]))."'";
$sSQL .= " GROUP BY mapa_produtividade_variedade";
$results = $wpdb->get_results( $sSQL , ARRAY_A );
if ($results) :
foreach($results as $row) : ?>
echo-results
Using <?php var_dump($_POST['estado']); ?>, I get NULL.
<?php var_dump($_POST); ?> will give me
["MT"]=>
string(0) ""
}
I need just that MT for my query (just that two characters), but I can get it without the whole array.
I'm just starting learning PHP, Ajax and MySQL, so I guess I'm missing something very simple.
Ok, so your using the $_POST supper global array without a key, so if your not supplying a key = values to the data in jQuery with $_POST won't work without being form-encoded key = value.
E.G
key=value&key2=value2
So if you're not doing that you need to read the raw php://input stream file_get_contents("php://input");
The other option is to change var ufname= $(this).val(); to var ufname= {val:$(this).val()}; and
$sSQL .= " WHERE mapa_produtividade_uf = '".addslashes(strip_tags($_POST[]))."'";
to
$sSQL .= " WHERE mapa_produtividade_uf = '".addslashes(strip_tags($_POST['val']))."'";
Also, addslashes is not a valid way to escape a string going into SQL, use Bind Parameters or at the very least the built into the module escapers, please read: http://shiflett.org/blog/2006/addslashes-versus-mysql-real-escape-string
and i mean i could use jQuery on your page via the Web Inspector console and run
(function(){
$.post({
url: "http://192.168.64.2/monsoy/site/variedades/resultados-de-produtividade/estado-variedade",
type: "POST",
data: "�' OR 1 = 1 /*",
success: function(data) {
console.log(data)
},
error: function(e) {
console.log(e);
}
});
})(jQuery);
And that string im sending is in php chr(0xbf).chr(0x27).' OR 1=1 /*';

On select of combobox value, label has to be displayed dynamically after a select query from database

In a file following code is written which populate the value of combobox :
<select id="company" required="required" class="form-control" value = "select" name="subject_code" placeholder="Select" >
<?php
//Iterating list of subjects available to be filled .
echo "<option> Select </option>";
foreach ($subjects_to_fill as $subject_id => $subject_name) {
# code...
echo "<option value=".$subject_id."> ".$subject_name." </option>";
}
?>
</select>
On selecting a particular item from the combobox, I want to display the faculty_name dynamically from faculty_table on the basis of $subject_id.
table structure:
faculty_table(faculty_id,faculty_name,subject_id)
subject_table(subject_id,subject_name,faculty_id)
You will need to use ajax for this task.
Add a <div> and below script in your current file.
<div id="faculty"></div>
<script type="text/javascript">
function get_faculty()
{
var id = document.getElementById("company").value;
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_faculty.php",
data: dataString,
success: function(html)
{
$("#faculty").html(html);
}
});
}
</script>
Now create another get_faculty.php file in same folder which will be called on onchange event of company dropdown.
Write below code in that file
if($_POST['id'])
{
$id=$_POST['id'];
$con=mysqli_connect("localhost","username","pass","dbname");
$sql=mysqli_query($con,"SELECT faculty_name from faculty_table where subject_id = ".$id);
while($row=mysqli_fetch_array($sql))
{
echo $row['faculty_name'];
}
}
Dont forget to write mysqli_connect credentials and query accordingly.

Select from mysql is not working in jQuery fancybox

Fancybox script POST my form data to go.php page then open go.php in fancybox iframe
<script>
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.post('go.php', $(this).parent().serialize())
.done(function() {
$.fancybox.open({
href : 'go.php',
type : 'iframe',
padding : 5
});
});
});
});
</script>
<select name="country">
<option value="US">US</option>
<option value="EU">EU</option>
</select>
<input type="button" value="Calculate" id="fancybox-manual-b"/>
in go.php, I receive the POST data from the form correctly and when I try to insert this data into DB, it's been inserted correctly too!
But now I want to select * from my DB table to echo all the data in the table where column = POST data, but this query doesn't work!
<?php
$country = $_POST[country];
mysql_query("INSERT INTO calculator (country) VALUES ('$country')"); //Works Correctly
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
} //Nothing appear
?>
Please checkout this method,
$country = $_POST[country];
if(mysql_query("INSERT INTO calculator (country) VALUES ('$country')"));
{
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
}
}
I used the same code you shared. But added an additional if loop on mysql_query part. It will make sure your select works after data being inserted.
We have to use jquery ajax to send form data to the php page with POST method then receive back any printed data from the php page in the ajax instead of the console.
We will open the fancybox iframe into ajax success instead of the console.
<script type="text/javascript">
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.ajax({
type: 'POST',
url: 'go.php',
data: $(this).parent().serialize(),
success: function(data){
$.fancybox(data);
},
fail:function(data){console.info(data)}
});
});
});
</script>

Limit Number of Results for Autocomplete Based on Dropdown Selection

I'm trying to figure out a couple things here and seem to be pretty close but hit a road block. My issue is, after I select a dropdown option (used to filter a large number of results), the results which should be available when I start typing in the autocomplete box are not available. If I hardcode a value that the dropdown is passing and start typing in the autocomplete box, everything works fine. It's only when I pass in that value that I am having the issue.
I have two PHP pages, one containing the layout which includes a dropdown (SQL for its results) and an autocomplete box and the other which contains the SQL for the autocomplete.
search.php
<select id="loc">
<?php
// sql for dropdown
while ($row = odbc_fetch_array($result)) {
echo "<option value\"".$row['Location']"\">".$row['Description']."</option>";
}
?>
</select>
<label for="search">Search: </label>
<input type="text" id="search" />
<script>
// Send value entered in the autocomplete box to data.php for it to be used in sql statement
$(document).ready(function(){
$('#search').autocomplete({
minLength: 3,
source: function(query, process) {
$.ajax({
url: 'data.php',
type: 'GET',
data: "name=" + $('#search').val(),
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
}
});
}
});
});
// Append selected dropdown value to URL so it can be accessed
$(document).ready(function() {
$('#search').change(function() {
var res = $(this).val();
location.href = "search.php?src="+res;
});
});
</script>
data.php
<?php
if (isset($_GET['src'])) {
$loc = $_GET['src'];
$fullname = explode(" ", $_GET['name']);
$sql = "SELECT p.lastname + ', ' + p.firstname as fullname,
l.city as city
FROM people p
JOIN location l on p.city = l.city
WHERE p.lastname like '".$fullname[1]."%' AND p.firstname like '".$fullname[0]."%'
AND l.city = '$loc'
GROUP BY p.lastname + ', ' + p.firstname, l.city
ORDER BY p.lastname + ', ' + p.firstname";
// DB connection and execute connection here
$array = array();
while ($row = odbc_fetch_array($db)) {
$array[] = $row['fullname'];
}
echo json_encode($array);
}
?>
So when I have my code like this and select an option from the dropdown, it runs through the select statement since the selected value is being passed in. If I echo the results on the search.php page, they are filtered correctly or if I navigate directly to the data.php page and pass in the correct parameters everything is correct. After I make a selection though, and start typing in the autocomplete box, I'm not getting any results. I'm guessing I need to somehow filter the results based on the selection, get those results and run a different query when I start typing?
Thanks in advance for any help and please let me know if I'm not clear on anything.
Well just like it ususally happens, after taking a break from it I've got it working now.
Below is the revised code with comments showing what I changed.
search.php
<select id="loc">
<?php
// sql for dropdown
while ($row = odbc_fetch_array($result)) {
echo "<option value\"".$row['Location']"\">".$row['Description']."</option>";
}
?>
</select>
<label for="search">Search: </label>
<input type="text" id="search" />
<script>
/* Send value entered in the autocomplete box to data.php
* for it to be used in sql statement */
$(document).ready(function(){
$('#search').autocomplete({
minLength: 3,
source: function(query, process) {
// Added the variable below to get the dropdown's selected value
var res = $('#loc').val();
$.ajax({
url: 'data.php',
type: 'GET',
// Edited: included the dropdown value
data: "src="+res + "&name=" + $('#search').val(),
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
}
});
}
});
});
/* This event is not needed since the value is set when a selection
* is made. 'change' passed that value to search.php causing
* the query to run without the search value. This caused a HUGE
* number of results, and usually causing the page to timeout.
* Making sure all variables get passed prior to running the query
* is a must. I knew this but got stuck on how to make it work. */
// Append selected dropdown value to URL so it can be accessed
//$(document).ready(function() {
// $('#search').change(function() {
// var res = $(this).val();
// location.href = "search.php?src="+res;
// });
//});
</script>
data.php
<?php
if (isset($_GET['src'])) {
$loc = $_GET['src'];
}
// Moved the $loc variable into the if statement above
// $loc = $_GET['src'];
$fullname = explode(" ", $_GET['name']);
$sql = "SELECT p.lastname + ', ' + p.firstname as fullname,
l.city as city
FROM people p
JOIN location l on p.city = l.city
WHERE p.lastname like '".$fullname[1]."%'
AND p.firstname like '".$fullname[0]."%'
AND l.city = '$loc'
GROUP BY p.lastname + ', ' + p.firstname, l.city
ORDER BY p.lastname + ', ' + p.firstname";
// DB connection and execute connection here
$array = array();
while ($row = odbc_fetch_array($db)) {
$array[] = $row['fullname'];
}
echo json_encode($array);
?>
I haven't finished a couple pieces on the main page such as disabling/hiding the autocomplete box until a selection is made from the dropdown and adjusting the query for additional filtering but those are next on my list. I'm sure there are a few other things I could clean up as well but my first goal was to get it working correctly and that's accomplished now!
If anyone is using php and has a few hundred thousand + results and would like to use an autocomplete box to filter those without waiting a ridiculous amount of time for the results to display, I hope this may be of some help. Not nearly as complex as I originally made it out to be but over thinking it will do that to you. Also, even though it's working now, feel free to add some suggestions and apologies for any grammatical errors!

Saving sortable to mysql with ajax jquery and php

I have a page with multiple drag&drop boxes, that works great, the thing that does not work are the links in the boxes. I would appreciate if someone could help me :). So I have a page where people can drag&drop boxes (it works fine, as I said before), the links inside the boxes are sortable aswell, but I can't seem to get them to save the values to mysql. I think there is a conflict between the two drag&drops, maybe I am doing it wrong, 'cause I haven't used ajax and jquery before.
//here is the jquery where I need to add some ajax
$(function() {
$('.dragbox-content').sortable({
connectWith: '.dragbox-content',
update: function(event, ui) {
var order=$(this).attr('id');
alert(order); // I get the order alert and it has one value that I need, but I need the sort order aswell
}
});
});
//this is the <div> that has the links in them and mysql query that gets the values
//from two different databases, one is for the boxes and the other for links.
//boxes db id = links title_id
echo '<div class="dragbox-content" id="order'.$widget['id'].'"';'>''</div>';
$sql10 = "SELECT u.*, w.id, w.link_address, w.link_name FROM db_boxes u LEFT
JOIN db_links w ON u.link_id = w.id WHERE
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights = '0') OR
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights LIKE '%26%') ORDER BY w.id ASC";
$result10 = mysql_query($sql10) or die (mysql_error());
while ($row = mysql_fetch_array($result10)) {
$link_id = $row['id'];
$link_address = $row['link_address'];
$link_name = $row['link_name'];
$title_id = $row['title_id'];
?>
<div class="move" id="<?php echo $link_id;?>">
<span class="link_style">
<div><?php echo $link_name;?> </div</span></div>
I just need somebody to tell me how can I save tile_id and sort_order to boxes database with ajax on every click a user makes on that page
See my example below:
http://jsfiddle.net/gRoberts/vMy7r/
$(function () {
$('ul').sortable({
update : function(e, ui) {
var ul = $(ui.item).closest('ul');
var index = 0;
var toPost = {};
ul.find('> li').each(function() {
index++;
$(this).find('input').val(index);
toPost[$(this).find('input').attr('name')] = index;
});
$.ajax({
url : '/echo/json/',
data : toPost,
type : 'POST',
dataType : 'json',
success : function(resp) {
alert(resp);
},
error : function() {
alert('There was a problem');
}
});
}
});
});
​
The above example can be used in two ways, if you remove the $.ajax it will update hidden form fields which you can then post normally.

Categories