Display form result on same page using php with smarty - javascript

My web app is integrated to facebook. I created a form in tpl file with only has one input, which is select input. User has to choose one of his facebook group. The value of the option is id of each group.
So this is what i would like to do :
When user change the option (onchange), list of members of the selected group will appear bellow the select div. I don't know what i should use (javascript, jquery, ajax, etc) and how to implement it in my code.
Here my code snippet :
{* --- form in tpl file --- *}
<form method="post">
<fieldset>
<div class="row">
<p style="font-weight:bold;">Choose your facebook group :</p>
</div>
<div class="row">
<select name="group" onchange="idontknow">
{foreach from=$userGroupsData item=group}
<option value="{$group.id}">{$group.name}</option>
{/foreach}
</select>
</div>
<div class="row">
{* the place where members list will appear *}
</div>
</fieldset>
</form>
PHP code to retrieve member list of selected group (if I use submit method) :
<?php
$groupId = $_POST['group'];
$groupmember = $facebook->api('/'.$groupId.'/members');
$membergroup = $groupmember['data'];
foreach ($membergroup as $membergroups) {
echo "<li>".$membergroups['name']."</li>";
}
?>
Any help would be greatly appreciated. Thank you

I would make an Ajax request using jQuery:
$(function() {
$('body').on('change', 'select[name="group"]', function() {
var groupId = $(this).val();
$.post('path/to/your/script', groupId)
.done(function(data) {
$('form .row').html(data);
});
});
});
If it were me, I would have the backend return JSON data instead of HTML and I would build the HTML dynamically in the Ajax callback.
Also, this scenario is one of the many reasons I prefer to use MVC architecture on the backend. If you were using an MVC framework like say CodeIgniter for example, the URL you're posting the data to would take care of the routing like this:
MVC-style URL = 'mycontroller/mymethod/myparam'.
In this example, mycontroller would be the class (script) you're calling, mymethod would be the specific function you want to call in the controller, and myparam would be the data you're passing to that function.

Related

Use javascript variable in Laravel PHP

Hi i m trying to develop a students registration application with Laravel
a student could be register in many classes each class has a name and level so in registration page i want to show a cheackbox with Classes Name then when i click on a Classe the application show me in the same page a groupe of cheakbox with levels og the cheakes class for exemple if i click on English it shows me Beginin , intermediate ...
So in create.blade.php (register) i have
#foreach ($mat as $m)
{!!Form::label($m->matiere,$m->matiere.' :')!!}
<input type="radio" name="matiere" onclick="cli();" value={!!$m->matiere!!}>
#endforeach
And i create a Script to help with cli() function
function cli(){
classname=document.querySelector('input[name="matiere"]:checked').value;
alert(classname);}
my question is how could i get classnam value in PHP to show the levels of this class
I think you may be taking an odd approach to this.
In your controller, before you pass any variables to your view, you will want to organize your classes and the levels you want to return. If you have set up your model relationships then you could even do this:
Controller
public function index()
{
$classes = MyClassModel::all();
return view('create', [
'mat' => $classes,
]);
}
create.blade.php
#foreach ($mat as $m)
{!!Form::label($m->matiere,$m->matiere.' :')!!}
<input type="radio" name="matiere" value={!!$m->matiere!!}>
#foreach ($m->levels as $level)
// output each level for that class
#endforeach
#endforeach
You can then use javascript to show or hide the different levels as appropriate. I would avoid any asynchronous javascript unless you have enough classes and/pr levels that it would cause loading issues.
when the browser send request to server for this page, php make all of your html and javascript code and send them to browser and your javascript code run on browser, so you can't use php and javascript at the same place (ex. on the server).

fetch data from SQL and populate dynamicaly on html

i am working on simple retail management web app.i have sale page which have a input field which gets data from a bar code scanner.here is sample code of it
html code
<div id = "sale-form" class="form-group">
<label>PRODUCT CODE</label>
<input type="text" id ="get-code"><span class="errors" id="get-code- error"></span>
</div>
<script>
$(document).ready(function(){
$('#get-code').focus();
})
</script>
<div id="bill">
</div>
j query
$('#get-code').bind('change paste ',function(){
var vall = $(this).val();
if(vall == ""){
$('#get-code-error').text("NO PRODUCT CODE ENTERED");
}
else{
//run some script to fetch data and add row to $('#bill') dynamically;
}
})
i need help in the script which fetches data from SQL based on product code
adds a editable row to the div with id bill every time when new data is typed in input.i have tried with html table but unable to do that.
You almost did it: you have the change and paste event and it should work.
In the else statement, where you have the comment just make an ajax request to the web server to get the data and on the success parse the response and display it in the div. Documentation of the ajax method of jquery can be found here: http://api.jquery.com/jquery.ajax/
If the problem is adding the row in the div: just use the append method of jquery.

How to access the JavaScript variable in the python code in Web2py's view

I'm trying to store the value of the drop-down 'product' in a javaScript variable and then trying to use that variable in Python code in html view of Web2py framework to further create the drop down for the other component.
I tried two different ways, but both of them did not work.
I want to do a query on database using a keyword which is selected from the Product drop-down and hence generating the second drop down.
<script>
function run()
{
var e = document.getElementById('local_product');
var strUser = e.options[e.selectedIndex].text;
document.getElementById('div_release').innerHTML =' <label>Release : </label> {{rows1 = db(db.Builds.Build.like(\"}}strUser%{{\"")).select()}} <select> {{for r1 in rows1:}}<option>{{=r1.Build}}</option> {{pass}}</select>'
or
document.getElementById('div_release').innerHTML =' <label>Release: </label> {{rows2=db.executesql("Select Build from Builds where Build like\"request.vars.prod_tab\"" )}} <select> {{for r1 in rows2:}}<option>{{=r1}}</option> {{pass}}</select>'
}
</script>
<form method="POST" action="" name="product_filter">
<label>Product: </label>
<select id="local_product" onchange="run()" name=prod_tab >
{{ for r in product_list: }}
<option value="{{r}}">
{{=r}}
</option>
{{pass}}
</select>
{{pass}}
<input type="Submit" name=Set Value="Set">
<form>
Python code in web2py views is executed on the server before the page is sent to the browser, so it is not possible to execute any Python code within the browser in response to user actions. Instead, you must send an Ajax request to the server to retrieve additional data to inject in the page. For ideas on how to achieve what you want, see this answer.

Dynamic Select Field that Repopulates after Changes in Another Select Field - Laravel 5.2 and JS

I am developing a web app using Laravel 5 and trying to integrate some JS to help out a form. I want users to be able to select a category in one select field, at which point a second select field should populate with options within that category. (E.g., Select a profession: programmer, artist. If 'programmer' is selected, second select field populates with: C++, Java, Python. If 'artist' is selected, second select populates with: Photoshop, Illustrator, MS Paint.)
Note that I need to populate these fields from my database. I've found examples of what I am trying to do on the web that I have tried to adapt to my case. The one I'm using is here: http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html but I can't get it to work (it's fairly old--from 2010).
Here's my HTML and JS:
<!-- JS -->
<script type="text/javascript">
$(document).ready(function()
{
$("#field_main").change(function()
{
var id = $(this).val();
var fields="";
$.ajax
({
type: "POST",
url: "ajax_field.php",
data: {id: id},
cache: false,
success: function(data)
{
$.each(data,function(index,field)
{
fields+="<option value='"+field.id+"'>"+field.field+"</option>";
});
$("#field").html(fields);
}
});
});
});
</script>
<!-- Create the first select field, this part of the code works fine -->
<label>Area :</label>
<select name="field_main" id="field_main">
<option selected="selected">--Select Area--</option>
<?php
$areas = App\Area::all();
foreach($areas as $area){
echo "<option value=\"" . $area->id . "\">" . $area->area . "</option>";
}
?>
</select>
<!-- Create the second select field; this part is not working -->
<label>Field :</label>
<select name="field" id="field">
<!--<option selected="selected">--Select Field--</option>-->
</select>
Here's what ajax_field.php looks like:
<?php
namespace App\Http\Controllers;
use DB;
if($_POST['id'])
{
$id = $_POST['id'];
$fields = DB::table('fields')->where('area_ref', $id)->get();
return response()->json(['data' => ['fields' => $fields]]);
}
?>
As far as I can tell, nothing runs from ajax_skill.php. I tried echoing something out in that function, it didn't appear on my page, and the skills field never populates. The profession select field, however, populates fine.
Any thoughts on where this code is going wrong?
You need to return JSON when hitting that URL with AJAX. You don't need the HTML. Return only the skills data with return response()->json(['data' => ['skills' => $skills]]); and add the select element on the page populated with all of the skills.
Oh and, the ajax data property takes an object so it should be: data: {id: id}
Since you are using Laravel, half of your code looks like old school PHP which is useless when Laravel has a cleaner way for these things.
If you are new to PHP and Object Oriented Programming, I'd advice you to learn that before using Laravel. It will help you in the future.
Also, I'd advice you to read up the Laravel documentation, follow the tutorials there and even go to Laracasts and watch the Laravel 5 Fundamentals and Laravel From Scratch series to get up to speed with Laravel.

HTML Select field calls web services through ajax

I have some modal with forms where I create object to store into database.
In these forms I have a Select field like this:
<div class="form-group" id=existingUser>
<label>Username</label> <select class="form-control select2"
style="width: 100%;" th:field="*{user}">
<option th:each="user: ${users}" th:value="${user.username}"
th:text="${user.username}"></option>
</select>
</div>
where users is passed from Controller with Model. With this approach I have to update all page to refresh the values inside select field otherwise I can only update the table where I show the new created object but I can't use the new field in select.
The problems are the performance and the look refreshing page, furthermore I can't use these instruction to show my message
location.reload();
//reload only the tag with id carsTable, so only the table
//$('#carsTable').load(document.URL + ' #carsTable');
$('#addCarModal').modal("hide");
notifyMessage("Your car has been created!", 'success');
function notifyMessage(textMessage, typeMessage){
$.bootstrapGrowl(textMessage, {
type: typeMessage, // (null, 'info', 'error', 'success')
});
}
Is there a way to call ajax when modal is called? Or can I pass data from javascript to HTML (if I retrive values when add button is clicked).
Sometimes I also check if select field are empty and in this case show a message inside the modals instead form.Thanks
UPDATE. I thouth this code:
To start with only success manage:
function freeUserController($scope) {
$http.get("https://localhost:8080/users/")
.success(function(data) {
$scope.users = data;
});
}
in my html page:
<div ng-controller="freeUserController" class="form-group" id=existingUser>
<label>Username</label> <select class="form-control select2"
style="width: 100%;" name="user">
<option ng-repeat="user in users" value="{{user.username}}">
{{user.username}}</option>
</select>
</div>
I assume you are rendering the HTML on the server. There is probably no way to make it re-render just that element. However, there are different ways you can do this:
One, you could start using client-side MVC / rendering like Angular.js. That way, you could automatically refresh the select field when a new field is added.
Two, you could put the new option into the select field without using an MVC system. That would require uncoupling the data from the view, so I wouldn't recommend it. However, you could have the submit button perform an ajax call to make sure the server reacted correctly, and only add the new option when the server response has arrived. Your code would look something like this:
$.ajax(url).done(function(){
$('#my-select').append('<option>').html('your data')
}).fail(function(){
// show error message...
});

Categories