How do I pull rows from mysql with Javascript onchange - javascript

I have a website where info of registered member from various countries and states are collected. On my search form, I have 3 fields; Country, State and Sex.
I listed all the countries of the world in my search (as a dropdown), but the state field is empty. Want I want is that once a visitor select a country, i want only the states of that country which registered members have are in my database to be pulled into the state field, instead of all the state of that country.
Eg 3 members from USA are from New York, New Jersey and Georgia. On selecting USA in the country dropdown, only these 3 state should appear under the state instead of the 50 states in america.

You would need to do a script, for example, in php(or any server side language), that does the query, it would look like:
$countryId = $_POST['countryId'];
$sql = "SELECT fields FROM states WHERE countryId = $countryId";
$result = .... etc;
returning an json object for example to the main page.
And from the main page you should do a Ajax request to the php page, getting the json object returned depending on your option selected and populating the next field.
You could have a look at jQuery framework as at least I, find easier than using raw javascript.

You could pull the the states of the registered members from your database using php or any server-side language you are using. Then you can use AJAX to get the states as an xml or a JSON object. You can the use the members of the object to populate the dropdown.
Example sql query string to get states of registered users: Select state From user_details WHERE country = 'USA'. This should return the states (probably in an array);
Example PHP code that will be retrieved by an AJAX call: $reply = {states: [NJ, NY, AZ]}.
Example JS code to parse the above reply: var reply = JSON.parse(serverReply);
var states = reply.states;
. I hope this helps

Related

How can I retrieve data from a foreignID

I am new to laravel and I am struggling to retrieve data using the query Builder.
Consider the following migration on the Hotel table:
$table->id();
$table->timestamps();
$table->foreignIdFor(User::class);
$table->foreignIdFor(Room::class);
Now consider that I have in my HotelController:
$hotel = Auth::user()->hotels which retrieves this on dd:
[{"id":1, "user_id":51,"room_id":11, "booking_id":7}
[{"id":2, "user_id":51,"room_id":16, "booking_id":21}
[{"id":3, "user_id":51,"room_id":18, "booking_id":44}
[{"id":4, "user_id":51,"room_id":45, "booking_id":33}
I now want to retrieve the data from each of the room_id and booking_id from each of the Auth users which in this case is user 51. Can anyone help me with how can I achieve this?
Thank you in advance
Assuming you defined the relationships (belongsTo, hasOne, hasMany, etc) in the models for Hotel, Room and Booking, you can just iterate through the list of hotels getting each hotel into a $hotel local variable, and asking for their related models information like this:
foreach ($hotels as $hotel) {
$hotel->room // gets you the related room
$hotel->booking // gets you the related booking
}

How to solve syntax error or access violation for PHP Laravel project?

I have two tables which are claim table and claim_type table. Currently, I want to get the name of the claim inside the claim_type table. So, from the table Claim, we will get which type of claim (in the form of id) and after that, we can get the name of the type. I already have queried it inside MySQL workbench like this.
SELECT claim_types.name, count(*), sum(amount) FROM myteduh_v1.claims
join claim_types on claim_type_id = claim_types.id
group by claim_type_id;
When I post to the PHP, which to query it is like below. It turns out some error.
$ClaimsType = ClaimType::pluck('name')
->count()
->join('claim_types','claim_type_id','=', 'claim_types.id')
->groupBy('claim_type_id')
->get();
dd($ClaimsType);
$Claims_pie_chart = Charts::create('pie', 'highcharts')
->title('Total Claims Based On Type of Claims')
->labels(['$ClaimsType'])
->values([15,25,50])
->dimensions(1000,500)
->responsive(true);
After that, I want to insert the $ClaimsType into the labels variable to be pie chart labels. The question is, is it wrong the way I query the database inside the PHP controller?
If you want to use aggregation in one query, you should use DB:raw() in select
$ClaimsType = Claim::select(['claim_types.name', DB:raw('count(*)'), DB:raw('sum(amount)')])
->join('claim_types','claim_type_id','=', 'claim_types.id')
->groupBy('claim_type_id')
->get();
now you can use ->toSql() instad of ->get(), and you will see that query is same as yours raw query.

I want to store changeable data within one column of my table row

So, I have a vue component called stats. Basically how its stored is it has a name for example: 'goals'. It fetches the row with the id/name of 'goals' from the database and the point is to access the info column within that to fetch specific data.
This is how the row would look
ID Name Info Created_at Updated_at
"1" "user" "{"goal": 1,"current":500}" "2019-04-28 03:54:44" "2019-04-28 03:54:46"
I want to be able to access the data within the Info column and display it accordingly. I can't seem how to get it working though within javascript.
This is how i call it
axios.get('/api/stats/user').then((res) => {this.test = res.data; console.log(this.test)});
and in the console i get the object i want but info looks like this:
info: "{"goal": 1000, "current":500}"
and I can't seem to be able to grab it by ['goal'] or this.test.info.goal which is what I want
First of all, create a resource file for yor model and create an accessor for your info/goal field.
You should use the resource files for each json response which contains models/collection of models.
This way you can modify what to display in your json response about each model.

jQuery Autofill textbox with information from another autofill

I am having an issue with jQuery autocomplete. Basically I have a search bar, and when you type in what you're looking for the jQuery code I have calls a php script which does a MySQL query and returns everything I need and fills in the text boxes accordingly. What I then want to do is take the value I receive from that autocomplete, and use it in another autocomplete to fill in more data. The tricky part is that the data I need to get with the 2nd query is located in a different table than the first query, which share a relationship. My question is do I need a completely separate function to do this, or can I simply put both queries in the 1 php script and have the information from the first query be used for my 2nd query.
Any help is appreciated thanks!
Here is the jQuery function:
$(function() {
/* $('#abbrev').val("");
*/
$("#q16_location16").autocomplete({
source: "location_query.php",
minLength: 1,
select: function(event, ui) {
$('#q16_location161').val(ui.item.LocationID);
$('#SystemName').val(ui.item.SystemName);
$('#SiteAddress1').val(ui.item.SiteAddress1);
$('#SiteAddress2').val(ui.item.SiteAddress2);
$('#SiteCPP').val(ui.item.SiteCPP);
$('#Contact').val(ui.item.Contact);
$('#SiteLocationHours').val(ui.item.SiteLocationHours);
}
});
});
and the php script:
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("
SELECT Location.LocationID,
Location.SystemName,
Location.SiteAddress1,
Location.SiteAddress2,
CONCAT_WS(' ', Location.SiteCity, Location.SiteProvince, Location.SitePostalCode) AS SiteCPP,
CONCAT_WS(' ', Location.ContactName, Location.ContactPhone, Location.ContactEmail) AS Contact,
Location.SiteLocationHours,
CONCAT_WS(' ', SystemName, SiteNameLocation, SiteAddress1, SiteCity, SiteProvince, SitePostalCode) as expr2
FROM Location
WHERE Location.SystemName like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteNameLocation like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteAddress1 like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteCity like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteProvince like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SitePostalCode like '%".mysql_real_escape_string($_GET['term'])."% '
LIMIT 0,15");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['LocationID'] = $row['LocationID'];
$row_array['value'] = $row['expr2'];
$row_array['SystemName'] = $row['SystemName'];
$row_array['SiteAddress1'] = $row['SiteAddress1'];
$row_array['SiteAddress2'] = $row['SiteAddress2'];
$row_array['SiteCPP'] = $row['SiteCPP'];
$row_array['Contact'] = $row['Contact'];
$row_array['SiteLocationHours'] = $row['SiteLocationHours'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr, $return_arr2);
So when the user types in "New York" they can can select that option. In my example New York has an ID of 5. I also have a query that selects different streets in new york but this is in a separate table. in my streets table however, there is a "LocationID" column that for every street in new york will have a value of 5. So I want to take that ID of 5 when a user enters in new york and generate all the streets from a different table which also have that ID. I have tried multiple things in terms of creating a new function but I am just unsure of how I would pass that ID to the function.
Thanks
You can use one PHP script for this. Here's about what I'd think the basic structure will look like:
Pass two values to "location_query.php". The first value would be the name of the table that you want to query. The second value could be the selection result from the auto-complete text box.
Create a prepared statement in "location_query.php" from the two values that were passed to "location_query.php".
Perform your query.
JSON encode the result (just like you did before).
I'd also like to point out a security concern with your code. You should be using Mysqli and prepared statements instead of PHP's MySQL and mysql_real_escape_string. mysql_real_escape_string has been shown to have security deficiencies that can lead to security breaches and PHP's MySQL class has been deprecated. Mysqli and Prepared statements are much safer, and, in my opinion, provide for cleaner code since it allows for the separation of the SQL and the parameters.
Hope this helps!
EDIT: I think I understand what you're trying to do now, but I think there's a better way to go about doing it. Instead of assigning the id value to a hidden field and trying to have jquery detect every time that field is changed, I would just do the following:
For your first text box's select method:
select:function(event, ui) {
$.get("location_query.php", {
searchterm:$(ui).val()
}, yourFunction);
}
Here's an example implementation of "queryFinished":
function queryFinished(data, textStatus, jqXHR) {
var mJSON = $.parseJSON(data);
/* mJSON is the parsed JSON data returned from your "location_query.php"
script.*/
//TODO the rest of your code
}
Here's what's going on:
We define a custom function to be called when the first text box has a new item selected. This functions only purpose is to call a GET on "location_query.php".
Then, we pass the value of the selected field from the first text box via our GET call.
We then create a function to be called when GET returns.
Finally, we parse the encoded JSON that is returned by "location_query.php". After that, you can perform whatever tasks you need with the parsed JSON (mJSON in our example).
Taking this approach keeps us from having to worry about "listening" for a value change in our hidden ID field and makes everything nice and clean.

Django Dynamic Drop-down List from Database

I wanted to develop a Django app and one of the functionalities I'd like to have is dynamic drop-down lists...specifically for vehicle makes and models...selecting a specific make will update the models list with only the models that fall under that make....I know this is possible in javascript or jQuery (this would be my best choice if anyone has an answer) but I don't know how to go about it.
Also, I'd want the make, model, year and series to be common then the other attributes like color, transmission etc to be variables so that one needs only enter the make, model, year, and series only for a new vehicle. Any ideas would be highly appreciated.
The 3 things you mention being common, make, model, year, would be the 3 input values. When given to the server, an object containing the details would be returned to the calling page. That page would parse the object details (using JavaScript), and update the UI to display them to the user.
From the Django side, there needs to be the facilities to take the 3 inputs, and return the output. From the client-side, there needs to be the facilities to pass the 3 inputs to the server, and then appropriately parse the server's response.
There is a REST api framework for Django that makes it rather easy to add the "api" mentioned above -- Piston. Using Piston, you'd simply need to make a URL for that resource, and then add a handler to process it. (you'll still need to skim the Piston documentation, but this should give you an idea of what it looks like)
urls.py:
vehicle_details = Resource(handler=VehicleDetails)
url(r'^vehicle/(?<make>.*)/(?<model>.*)/(?<year\d{2,4}/(?P<emitter_format>[a-z]{1,4}), vehicle_details, name='vehicle_details'),
handler.py:
class VehicleDetails(BaseHandler):
methods_allowed = ('GET',)
model = Vehicles #whatever your Django vehicle model is
def read(self, request, *args, **kwargs):
# code to query the DB and select the options
# self.model.objects.filter()...
# Build a custom object or something to return
return custom_object
This simply sets up the url www.yoursite.com/vehicle/[make]/[model]/[year]/json to return a custom data object in JSON for jquery to parse.
On the client side, you could use jquery to setup an event (bind) so that when all 3 drop downs have a value selected, it will execute a $.get() to the api URL. When it gets this result back, it passes it into the Jquery JSON parser, and gives the custom object, as a javascript object. That object could then be used to populate more drop down menus.
(Big warning, I just wrote the following off the top of my head, so it's not meant to be copy and pasted. It's just for the general idea.)
<script type="text/javascript">
// On document load
$(function() {
$('#dropdown_make').bind('change', checkForValues());
$('#dropdown_model').bind('change', checkForValues());
$('#dropdown_year').bind('change', checkForValues());
});
function checkForValues() {
if ($('#dropdown_make').val() && $('#dropdown_model').val() && $('#dropdown_year').val())
updateOptions();
}
function updateOptions() {
url = '/vehicle/';
url += $('#dropdown_make').val() + '/';
url += $('#dropdown_model').val() + '/';
url += $('#dropdown_year').val() + '/';
url += 'json/';
$.get(url, function(){
// Custom data object will be returned here
})
}
</script>
This is uncanny: Dynamic Filtered Drop-Down Choice Fields With Django
His question:
"Here is the situation: I have a database with car makes and models. When a user selects a make, I want to update the models drop-down with only the models associated with that make. ... Therefore I want to use Ajax to populate the data."
You're not the same guy? :)

Categories

Resources