Confused in slim framework and javascript ajax combination - javascript

I'm traying to make an ajax action in my project which is developed by Userfrosting system (A system that uses slim framework and twig).
There are 2 html select tags in sections.php called country and city.
When country is chosen, cities in that country will ve selected from the
database and will be shown in city tag with an ajax action.
I can do this with a normal php script, but can't do it in slim.
sections.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".country").change(function() {
var veri = $(this).val();
var dataString = 'veri=' + veri;
$.ajax({
type: "POST",
url: "deneme.php",
data: dataString,
cache: false,
success: function(html) {
$(".city").html(html);
}
});
});
});
</script>
<label>Country :</label>
<select name="country" class="country">
<option selected="selected">--Select Country--</option>
<option value="1">India</option>
<option value="2">United States</option>
<option value="3">United Kingdom</option>
</select>
<br/>
<br/>
<label>City :</label>
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
Posted value 'veri' will be taken by deneme.php and cities in that country will be fetched from database and all the cities will be listed in options.
deneme.php
require_once("../userfrosting/config-userfrosting.php");
require_once "../userfrosting/models/mysql/MySqlSiteSettings.php";
$veri = $app->request->post('veri');
if (isset($veri)) {
while ($data = $app->site->getCities($veri)) {
$cities = $data[city];
echo '<option value="'.$cities.
'">'.$cities.
'</option>';
}
When i choose the country, city option becomes empty and i get this error in error log;
"PHP Fatal error: Call to a member function getAktiviteler() on a
non-object in C:\xampp\htdocs\userfrosting\public\deneme.php on line
119"
I used many diffent ways but couldn't solve the problem.
Please help !

As alexw said, i went through UserFrosting and Slim tutorials and restructured my code. There was problem in fetching data from database and also in javascript part. Now my problem is solved. Thanks Alex.

Related

how to enter dynamic data to a javascript function after page load

I have a select box which options are coming from database depending on another selected option using ajax
$(document).ready(function(){
$("select.entity").change(function(){
var selectedEntity = $(".entity option:selected").val();
$.ajax({
type: "POST",
url: "entityName.php",
data: { entity : selectedEntity }
}).done(function(data){
$("#entityName").html(data);
});
});
});
// This is the select box where options are dynamic.
<label>Select Entity Name:</label>
<select id="entityName" name="entityName" class="select_box" required>
<option value="" disabled selected>Select Entity Type First</option>
</select>
This works fine but now i want a search box for the options. I am using this function for search.
var select_box_element = document.querySelector('.select_box');
dselect(select_box_element, {
search: true
});
As options are dynamic and loaded after the page load that's why this function doesnot work.
I need to push dynamic options into dselect function based on the selection.
Something like this might work for you. I've used CSS and JS for the dselect library, as shown in the official GitHub repo. In the example, Bootstrap 5 files are also included, since dSelect seems to be relying on Bootstrap 5 files.
The API used is from the free Pokemon API.
Some notes on the slight rewriting on how the AJAX is handled:
no need to call the AJAX, if there's nothing inside the first select element, and if we revert to the default #entityType value. We just need to clear the previous contents of the #entityName. That is what the if does right inside the change event handler
the AJAX call contains a predefined dataType attribute. This was done because I know in advance that the response in my example (response of Pokemon API) will be in JSON format. You can also do that in your specific case, if you control the back-end / the way entityName.php works and outputs its results. If you don't have that kind of control, you may want to omit this AJAX config parameter, and handle the results differently
instead of using $.ajax({...}).done(...), the example uses separate success and error handlers. This was just a preference choice. For differences between the use of success and done, please refer to this SO answer. In your specific case, .done(...) would have worked as well, with additional testing if the received data matches what you expect it to match, like this:
$.ajax({
// your ajax setup
}).done(function(data){
if(data) {
$("#entityName").html(data);
} else {
$("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
}
dselect($("#entityName")[0], { search: true });
});
the example also uses config, as shown in the official GitHub repo. Again, if you're happy with the way you're initializing your dselect, you can skip the configuration
$(document).ready(function(){
const config = {
search: false, // Toggle search feature. Default: false
creatable: false, // Creatable selection. Default: false
clearable: false, // Clearable selection. Default: false
maxHeight: '360px', // Max height for showing scrollbar. Default: 360px
size: '', // Can be "sm" or "lg". Default ''
}
dselect($("#entityName")[0], config);
$("#entityType").change(function(){
let entityType = $(this).val();
if(!entityType) {
$("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
dselect($("#entityName")[0], config);
return false;
}
$.ajax({
type: "GET",
url: "https://pokeapi.co/api/v2/type/" + entityType,
dataType: "json",
success: function(data) {
let pokemon = data.pokemon;
let pokeList = '<option value="" selected>Please choose your Pokemon</option>';
console.log(pokemon[0].pokemon.name);
for(var i = 0; i < pokemon.length; i++) {
let pokeName = pokemon[i].pokemon.name;
let pokeUrl = pokemon[i].pokemon.url;
pokeList += '<option value="' + pokeUrl + '">' + pokeName + '</option>';
}
$("#entityName").html(pokeList);
dselect($("#entityName")[0], config);
},
error: function(desc, err) {
alert("Error: " + JSON.stringify(desc) + ", " + JSON.stringify(err));
}
});
});
});
label {
margin-left: 15px;
}
#entityType {
margin: 15px 0 15px 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/#jarstone/dselect/dist/css/dselect.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<script src="https://unpkg.com/#jarstone/dselect/dist/js/dselect.js"></script>
<label for="entityType">Select Entity Type:</label>
<select id="entityType" name="entityType" class="select_box" required>
<option value="">Choose</option>
<option value="water">Water</option>
<option value="fire">Fire</option>
<option value="ground">Ground</option>
<option value="electric">Electric</option>
<option value="flying">Flying</option>
</select>
<select id="entityName" name="entityName" class="select_box" required>
<option value="" disabled selected>Select Entity Type First</option>
</select>
<div id="list"></div>
I use $("#entityName")[0] to get at the DOM element from the jQuery Object
}).done(function(data){
$("#entityName").html(data);
dselect($("#entityName")[0], { search: true });
});
Example - you need to add some CSS I think
const $select_box_element = $('#entityName');
const $entity = $('#entityType');
$("select.entity").change(function(){
if (this.value === "one") {
$select_box_element.html(`<option value="one">One</option><option value="oneone">OneOne</option>`)
dselect($select_box_element[0], { search: true });
}
else {
$select_box_element.html(`<option value="two">Two</option><option value="twotwo">TwoTwo</option>`)
dselect($select_box_element[0], { search: true });
}
});
dselect($entity[0], { search: true });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/#jarstone/dselect/dist/css/dselect.css">
<script src="https://unpkg.com/#jarstone/dselect/dist/js/dselect.js"></script>
<label>Select Entity Type:</label>
<select id="entityType" name="entityType" class="entity" required>
<option value="" disabled selected>Select Entity Type</option>
<option value="one">One</option>
<option value="two">Two</option>
</select>
<label>Select Entity Name:</label>
<select id="entityName" name="entityName" class="select_box" required>
<option value="" disabled selected>Select Entity Type First</option>
<option value="one">One</option>
<option value="one">One</option>
</select>

I am trying get price of specific product using ajax call. so far i had tried this. but i am not getting the price after selecting product

my blade.php
<select name="productname[]" class="form-control productname">
<option value="0" selected="true" disabled="true">Select Product</option>
#foreach ($stock as $product)
<option value="{{$product->id}}">{{$product->productname}}</option>
#endforeach
</select>
user select product from here and i want ptice input feild auto-filled.
<td><input type="text" name="price[]" class="form-control price"></td>
using this javascript
$('tbody').delegate('.productname','change', function(){
var tr=$(this).parent().parent();
var id = tr.find('.productname').val();
var dataId={'id':id};
$.ajax({
type : 'GET',
url : "{{route('findprice')}}",
dataType: 'json',
data : dataId,
success:function(data){
tr.find('text.price').val(data[0].price);
}
});
});
and in my controller I am using this thing.
public function findprice(Request $request)
{
$data = Stock::where('price')->where('id',$request->id)->first();
return response()->json($data);
}
anyone who can help me out.
You have a mistake in query. Add this
$data = Stock::select('price')
->where('id',$request->id)
->first();
You placed 'where' instead of 'select'

Dropdown only saves and then display's first value

So to continue my last question (link). I've finally got that sorted out (with help), but now the value of the name is only the first value of the drop down list.
A brief explanation, I have 2 drop down menu's and when you select a option from one (A) the other drop down menu is updated (B). I know it has something to do with an array but I can't figure this out.
Here are my files.
HTML
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<?php
$sttub = str_replace('&', 'en', $stub);
$q = $row["Categorie"];
echo "
<option class='dropdownmenu_A' value='".$sttub."' name='".$q."'>"
.$row["Categorie"]."
<span style='font-size:1.2rem;color:#F8F8F8;'>
(" . $row['x'] . ")
</span>
</option>
";
}}?>
</select>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
JavaScript
$(function(){
$('#main_cat').change(function(){
var $mainCat=$('#main_cat').val();
var $mainName = $(".dropdownmenu_A").attr("name");
// call ajax
$("#sub_cat").empty();
$.ajax({
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_call&main_catid=' + $mainCat + '&main_name=' + $mainName,
success:function(results)
{
// alert(results);
console.log($mainCat,$mainName);
$("#sub_cat").removeAttr("disabled");
$("#sub_cat").append(results);
}
});
}
);
});
function.php
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$q = $_POST['main_catid'];
$x = $_POST['main_name'];
echo '<option value="-1" selected="selected">'.$x.'</option>'.$option;
die();
} // end if
}
I have tried using <select id="main_cat" name="main_cat[]"> like I found on google but this didn't work. Using $x[] = $_POST['main_name']; just echos the word Array. How do I get this to work and display the correct option that is selected and not just the first every time.
To be clear, here are my drop down menu's (sometimes my brain goes faster then I can type, so I hope it's clear).
select{height:30px}
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_A' value='option-1' name='Option 1'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
</select>
<select id="sub_cat" name="sub_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_B' value='sub-option-1' name='Sub Option 1'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
</select>
So right now if I select Option 1 from dropdownmenu_A it only echo's the first value from dropdownmenu_A to dropdownmenu_B and not Option 2 or Option 3.
1- You can't have <span/> tags inside <option/> tags as the latter cannot have any child elements.
2- <option/> doesn't have a name attribute. If you want to create a custom attribute, use HTML5 data attributes. That's what they are for.
3- printf is your new friend.
printf('<option class="dropdownmenu_A" value="%s" data-name="%s">%s (%s)</option>', $sttub, $q, $row["Categorie"], $row['x']);
4- I believe the problem is $(".dropdownmenu_A").attr("name") as this would always pull the same name and not the selected name. In your particular case, I would do
$(function(){
$('#main_cat').change(function(){
var $option = $(this).find('option:selected'),
id = $option.val(),
name = $option.data('name');
// open your browser's console log and ensure that you get the correct values
console.log(id, name);
$("#sub_cat").empty();
// call ajax
$.ajax({
url: "<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data: {
action: 'my_special_ajax_call',
main_catid: id,
main_name: name
},
success: function (results) {
$("#sub_cat").removeAttr('disabled').html(results);
}
});
});
});
You should add a selected attribute to your selected option:
https://www.w3schools.com/tags/att_option_selected.asp

How to list the values according to selected value from select option

I have 2 drop down menu, let it be:
<select name="" id="district" onchange="selectbyDistrict()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
And for Next drop down menu, I have to retrive from database and display according to the selected values of above options
I use script as
$('#district').change(function(){
var value = $('#district').val();
$.get('get_ajax.php', {id:value}, function(data){
$('#new_location').html(data);
});
});
In get_ajax.php code var_dump($_GET); display nothing.
So How to complete this. Please Suggest me
Many Thanks in Advance
<select name="" id="district" onchange="selectbyDistrict(this)">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
Now Right the code for onchange Event And also include the ajax
function selectbyDistrict(obj){
var selectedValues = obj.value;
$.ajax({ method: "POST",
url: "district_subpart.php",
data: {'district':selectedValues}
}).success(function( msg ) {
// this is place you can right where you want to display
});
}
Now on the php File You right the code
district_subpart.php
$district = $_POST['district'];
// Mysql Connect Here
mysql_connect("hostname","mysql_username","mysql_password");
mysql_select_db("database_name");
$sql = "select * from district_subpart where district_id = ".$district;
$results = mysql_query($sql);
while($row=mysql_fetch_array($results)){
// right here code
}
die;

append value into dropdown-list

i'm using the source code for multiple selection
Dropdown check-list
Since, the example has been shown for the static values, i have edited as per my requirement, And i was trying to populate the values of the dropdown list using database, which means dynamically populating the values into the dropdown-list. But, i'm failed to do. Please help me. The dropdown list will be populated as per the option selected from the first dropdown
<select id="design" onmouseup="showOfficer()" >
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<select id="officers" class="officers" multiple="multiple"><div id="show_officer"></div></select>
my javascript
<script language="javascript" >
function showOfficer(){
document.getElementById("msg4").style.display="block";
$.ajax({
url: 'getValues.jsp',
data: 'design_id='+ $('#design').val(),
type: 'post',
success: function(msg){document.getElementById("show_officer").innerHTML=msg;
document.getElementById("msg4").style.display="none";
}});
}
</script>
getValues.jsp
<%#include file="../dbconfig.jsp" %><%
String design=request.getParameter("design_id");
String buffer="";
try{
int count=0;
ResultSet rs = state.executeQuery("SELECT OFFICER_ID,FIRST_NAME,LAST_NAME FROM OFFICER WHERE STATUS_TYPE='UNASSIGN' AND DESIGN_ID='"+design+"'");//
while(rs.next()){
buffer=buffer+"<option value='"+rs.getString(1)+"'>"+rs.getString(2)+" "+rs.getString(1)+"</option>";
count++;
}
if(count==0)
{
buffer=buffer+"<option value='ERROR'>OFFICERS ASSIGNED ALREADY</option>";
}
}
catch(Exception e){
buffer=buffer+"<option value='ERROR'>OFFICERS ASSIGNED ALREADY</option>"+e;
}
buffer=buffer+"";
//out.print(buffer);
response.getWriter().print(buffer);
%>
Please help me !!
I think this is what you're looking for:
success: function(html){
$("#msg4").hide();
$("#officers").html(html);
$("#officers").dropdownchecklist();
}
replace your success function with this and take that div out of your select.
If you're loading jQuery why don't you use it for more than just the ajax call?
remove the onmouseup, and try this:
$('#design').mouseup(function(){
$("msg4").show();
$.ajax({
url: 'getValues.jsp',
data: 'design_id='+ $('#design').val(),
type: 'post',
success: function(html){
$("#msg4").hide();
$("#officers").dropdownchecklist("destroy");
$("#officers").html(html);
$("#officers").dropdownchecklist();
}
});
});

Categories