Populate a second dropdown menu from mysql - php

I have seen that some people asked before similar questions but none of them answers my problem.
I have a question regarding ajax and php. In both of them I am relatively beginner.
What I try to do is a so-called: chained select boxes. I want to have 2 dropdown menus. When I select a value from the first one, then the second dropdown menu it gets populated from a mysql database.
For this purpose I use jquery, ajax, php and mysql.
I was trying to find some examples online but all of them seem rather complicated to me (I guess cause I am beginner).
I decided to make something of my own but I got stacked. I am not sure if the logic is correct.
So here we go (I will include only relevant code here):
Using jquery I send an ajax request:
$("#loc").change(function(){
var val = ($('#loc').val());
$.ajax({
type:'POST',
url:'query.php',
data: {val:val},
success:function(response){
$("#x").html(response);
} });
});
"loc" is the id of the first dropdown menu. I get the value and I send it to query.php
query.php has the following lines of code:
<?php
include('connect.php');
$area = $_POST['val'];
$query ="SELECT DISTINCT activity FROM main ORDER BY 1 where n_city='$area'";
$result = mysqli_query($dbcon, $query) or die('no available data');
$options="";
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){
$activity=$row["activity"];
}
?>
Now I am trying to figure out two things. 1) What should I return in the success function so I get a form which is populated with the results from the query? 2) Second and most important, is my idea actually correct or there is some logical mistake that I am missing?
Thanks a lot.
Dimitris

The clean solution would be to return a JSON array containing all the options for the second dropdown. This can easily be done by creating a normal PHP array and then using json_encode(). You can loop over the result and create new options in your JS function.
It will definitely work like this. However, it might be worth taking the time to learn how to use one of the available solutions.

Related

Send multiple AJAX data to PHP and update Mysql database

i am tying to build an application where user can reorder items (and save the order to database). The items user is reordering are navigation links, which are generated dynamically on the page from php loop:
$nav_links.='<li class="collection-item ui-state-default item" data-ord="'.$navorder.'" data-url="'.$pageurlname.'"><a>' .$pagename. '</a></li>';}
$navorder is order of the page in the navigation
$pageurlname is string which is used to call the page dynamically (index.php?page=$pageurlname) and is unique key in the table.
I am using jqueryUi sortable funcion to make the process drag & drop, it is working fine and each time i reorder the links, the new order is updated to "data-ord".. the sript:
$('#sortable').sortable({
stop: function(event, ui){
$(".sortable li").each(function(i, el){
$(el).attr('data-ord',$(el).index()+1);
});
}
});
Now to the problem, which is my ajax script:
$(document).on('click','.saveorder',function(){
var neworder = $('.collection-item').attr('data-ord');
var pgurl = $('.collection-item').attr('data-url');
$.ajax({
type:'POST',
dataType:'text',
url:'/rs/pages/nav_order.php',
data: { neworder:neworder, pgurl:pgurl },
success: function(data) {console.log(data); $('#response').html(data);},
error: function(data) {console.log('Error!', data); }
});
});
I am new to ajax, so it is mostly build on scripts i found in other quiestions here. (I was able to succesfully implement cript link this to my other functions) however it is not working in this case. The problem seems to be that i am trying to post multiple data for multiple rows (At this time i have 4 links i am trying to reorder, but the link count can be more or less). When i tried to get values of variables "neworder" and "pgurl" (using alert), it always show only the values for the first item.
I have tried lot of solutions found in similar quiestion but none of them worked, simply because user were posting form data and then serialized it, which is not my case because i am not sending data from the form.
Lastly here is the nav_order.php (i guess it is wrong here too, probably need to add foreach but at first i need to have the ajax working correctly):
<?php
include "/rs/include/db.php";
$neworder = $_POST['neworder'];
$pgurl = $_POST['pgurl'];
$query = mysqli_query($Connection, "UPDATE horus_pages SET nav_order='$neworder' WHERE url_name='$pgurl'") or die (mysqli_error($Connection));
echo 'Reordered';
?>
Also when i check the console, there is no data.
So please can you tell me how to correct the ajax script to send the data for each object and then handle it correctly in the php script? Hope i described my problem clearly. Thank you for any help.
Put data-id="your_database_id" in your links html. Selecting them in your database with href, will be slow and bug things if there are multiple records with the same href.
You have save button which sends the order and href of the first link it finds? And what happens when multiple items change their order? If you have many links, you will be throwing hundreds of mysql updates for each save?
You should be better off sending json to your php. Something like that:
[{id:123, order: 332}, {id:124, order:334}, ... ]
dataType:'text' becomes dataType:'json'
If you don't care about scalability, then this will work on the backend.
$data = file_get_contents("php://input");
$links = json_decode($data, true);
foreach($links as $link) {
$order = intval($link['order']);
$id = intval($link['id'])
// UPDATE table SET `order` = '$order' WHERE id = '$id'
}
Btw. Your php code allows SQL injection. Thats bad
Perhaps you can make the order 'float' and make an algorithm which finds empty spot. This will allow you to reduce these 100's of SQL requests to 1.

Jquery Autocomplete too slow

I have written this code what it does is if user types postcode or city name it fetches from database using like query now the problem is i have around 1260 records with two fields one is city and other is post code
SELECT code, area FROM post_codes WHERE code LIKE '$q%' or area LIKE '$q%' ORDER BY area LIMIT 4
i have read many questions posted by users and researched online as well but nothing works used query delay as well .i have even indexed both these fields in database as well .. its getting records too slow that is the first problem now my second problem is when user is in that text field for search and he presses tab he can bypass the search and write any invalid code he wants how to restrict that here is my code for reference.
$("#Postcode").autocomplete("get_codes2.php", {
width: 260,
queryDelay:0,
dataType: 'json',
parse: function(data) {
var array = new Array();
for(var i=0;i<data.length;i++)
{
array[array.length] = { data: data[i], value: data[i].areacode, result: data[i].areacode};
}
return array;
},
formatItem: function(row) {
return row.areacode;
}
}).result(function (){
I think Drupal's API search has a really nice approach to solving this problem. Their alternative to letting every incremental search hit the backend is to serve one big JSON file, which is used to autocomplete on client side.
In their implementation they're listening on the focus event for the search input, to fetch the JSON only when it's actually needed.

Managing multiple AJAX calls to PHP scripts

I have a set of 5 HTML dropdowns that act as filters for narrowing results returned from a mySQL database. The three pertinent filters are for "Province", "Region", and "City" selection, respectively.
I have three functions:
findSchools(), which runs when any of the filters (marked with CSS class .filter) are changed, and fetches the results via AJAX from a PHP script. Once that is done, two other functions are called...
changeRegionOptions(), which, upon changing the "Province" filter, and updates the available options using the same method as the first function, but posting to a different script.
changeCityOptions(), which runs if the "Region" filter was changed, and updates options, again using the same method.
The problem is that since I want these AJAX functions to run simultaneously, and they by nature run asynchronously, I've tried using $.when to control the execution of the functions, but it doesn't fix the problem.
The functions run, but the Region and City filters return blank (no options); the FireBug report shows absolutely no output, even though the POST request went through. The posted parameter for filter_province gets sent normally, but the one for region gets cut off at the end -- it sends as filter_region=, with no value passed. So I'm presuming my logic is wrong somewhere. The code is below:
// When any of the filters are changed, let's query the database...
$("select.filter").change(function() {
findSchools();
});
// First, we see if there are any results...
function findSchools() {
var sch_province = document.filterform.filter_province.value;
var sch_region = document.filterform.filter_region.value;
var sch_city = document.filterform.filter_city.value;
var sch_cat = document.filterform.filter_category.value;
var sch_type = document.filterform.filter_type.value;
$.post("fetch_results.php",
{ filter_province : sch_province,
filter_region : sch_region,
filter_city : sch_city,
filter_category : sch_cat,
filter_type : sch_type },
function(data) {
$("#results").html("");
$("#results").hide();
$("#results").html(data);
$("#results").fadeIn(600);
}
);
// Once the results are fetched, we want to see if the filter they changed
was the one for Province, and if so, update the Region and City options
to match that selection...
$("#filter_province").change(function() {
$.when(findSchools())
.done(changeRegionOptions());
$.when(changeRegionOptions())
.done(changeCityOptions());
});
};
This is just one of the ways I've tried to solve it; I've tried using an IF statement, and tried calling the functions directly inside the general select.filter.change() function (after findSchools(); ), but they all return the same result.
Any help with this would be great!
You need to turn async to false. After that, your code will be executed line by line.
For example like this, before calling $.post
$.ajaxSetup({async:false});
Try this .hope this is what you were expecting. jsfiddle->sample code

display html select (from PHP) via jquery?

So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

Categories