Use javascript variable in Laravel PHP - javascript

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).

Related

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

Submitting a form with a complex structure dynamically generated in Javascript to a PHP script via POST method

I'm trying to figure out the best way to submit a form with a complex structure that is dynamically generated in Javascript to a PHP script via the POST method.
The form has this kind of hierarchical structure:
<div class="item">
<textarea class="subitem_textarea"></textarea>
<input type="text"/>
<input type="text"/>
</div>
<div class="item">
<textarea></textarea>
<input type="text"/>
<input type="text"/>
<input type="text"/>
</div>
The number of items is variable and can't be known in advance since items are created by the user. Each item has one <textarea> field, but a variable number of <input type="text"/> fields, since those are also created by the user.
I need to save the content of the form into a database, in a way that preserves this structure, so the PHP script must be able to know which field belong to which item.
I guess that one way to do this is, on the client side (Javascript + jQuery), to arrange for the fields to be given names in such a way that, on the server side (PHP), I can figure that out. For instance, using Javascript + jQuery, I could arrange for the HTML of the form that is dynamically generated on the client side to be:
<div class="item">
<textarea name="textareas[0]"></textarea>
<input type="text" name="texts[0][0]"/>
<input type="text" name="texts[0][1]"/>
</div>
<div class="item">
<textarea name="textareas[1]"></textarea>
<input type="text" name="texts[1][0]"/>
<input type="text" name="texts[1][1]"/>
<input type="text" name="texts[1][2]"/>
</div>
Then, on the server side, I can just recover the structure in PHP by inspecting the $_POST array. However, I can't help but think that I shouldn't have to bother with naming fields in a particular way, that it should be possible to recover the content and structure of the form in a simpler way.
For instance, in order to make various Ajax calls, I already need to store the content and structure of that dynamically created form in a Javascript object as it's being filled, which I send to the server using JSON.stringify when I make the Ajax call and recover in PHP with json_decode
For instance, if I store the content and structure of the dynamically created form in a Javascript object as it's being filled (which I already have to do anyway in order to make various Ajax calls that require that information), perhaps I can somehow use JSON.stringify to send that object to the PHP script that processes the form and use json_decode to get the correct data structure on the server side without the hassle. In fact, I guess I could even do that with another Ajax call that is made when the user clicks on the submit button, instead of doing it through a regular form submission. But I don't suppose it's the best practice and, since I don't have much experience in web development, I want to know what's the best practice to a form with a complex structure dynamically generated in Javascript to a PHP script via the POST method.
EDIT: Just to clarify, since Bilel pointed out I didn't say what I'm planning to do with the data in the form, the PHP script on the server side is going to store the data in the database in a way that preserves the structure.
That's a detailed Question but you didn't told us How are you going to use these collected Data ?
If it's meant to be stored and displayed, then yes you already found the easiest solution by encoding $_POST data with json.
If for example, you could later need relational functionalities like querying User Ages (those being posted through input fields), then you should think about pre-structuring your data. With jQuery/Javascript functions first into a well formatted Json and later Parse the json on the server side to Insert each input field in it's appropriate Database field.
Even, it's against design conventions and space consuming, I do sometimes store the whole json in a separate field near other structured database records. New DBMS can handle json types...
Just to show you an example, I made this function to store a pre-structured json containing Room Information in a booking system, where we can dynamically add extra rooms:
function jss(){
var json = {};
json.rooms = $('.camera').map(function() {
return {
max : $(this).find(".max").val()
, arrange : $(this).find(".arrang").val()
,kids: $('[name^=enf]', this).map(function() {
return {
age: $(this).val()
};
}).get()
, adults: $('[name^=pers]', this).map(function() {
return {
name: $(this).val()
};
}).get()
};
}).get();
return JSON.stringify(json, null, "\t");
}

how to call javascript function in layout content or view

I am calling the javascript function in the view of an layout. I have a common layout for different views but there are 2 views in specifically i want to check the screen width. In layout i can define the script but they will work on my whole application so just i want to mention them specifically in 2 views. I could have make 2 javascript files and include them in their respective views but i think this is not a good option.
How will i approach to this issue?
i have two views mobile-view and desktop-view.
Option 1:
Put the JavaScript in a small .js file, and include that file in the specific views with echo $this->Html->script('...');
Option 2:
Create an element with the JavaScript in it (echo $this->Html->scriptBlock('...');), and reference that element from each of the views via echo $this->element('...');
With the HtmlHelper you can buffer JavaScript script blocks and output them in the <head> or preferably at the end of the <body>, like so:
Your View
// Start a script block to be echoed at the end of the <body>
$this->Html->scriptStart(['block' => 'bottomScripts']);
echo "alert('Hi, it is JavaScript.');";
$this->Html->scriptEnd();
Nothing will happen unless you output the scripts and/or script blocks that are buffered inside the block called bottomScripts in a Layout or View:
Your Layout
…
<?= $this->fetch('bottomScripts'); ?>
</body>
</html>

Display form result on same page using php with smarty

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.

How to alter order of list items in a form?

I have made a Spring MVC app that displays a list of items to a user - how could I change the order of those items in JSP, so that the new order gets submitted to the server?
For example, the user gets the following list:
Pet Cat
Pet Dog
Pet Bird
The list is made up with this form:
<form:form action="/modifypetlist.do" method="POST" modelAttribute="petList">
<fieldset>
<div>
<ul id="sortable">
<c:forEach items="${petList.list}" varStatus="vs">
<li class="ui-state-default">
<form:label path="list[${vs.index}].pet">Pet</form:label>
<form:input path="list[${vs.index}].pet" />
</li>
</c:forEach>
</ul>
</div>
<input type="submit" value="send">
</fieldset>
</form:form>
I have included some Javascript that enables the user to drag and drop the rows in the list, e.g. moving the Dog line above the Cat line.
How do I communicate this to the server? (how could I rebuild the petList model from the form fields?) I can currently read the list in the server after submitting the form, but the list items come in original order, even if I change the names in the form (eg. Cat --> Mouse)
That's because they're naturally ordered by their primary key (which is an index), so usually the id of the row.
Try adding a "rank" field in the table that you will update once the data has been sorted and order your results by rank.
You need to persist the order information in your persistance layer. By doing this, you will need to trigger a call (an javascript ajax call for exemple) everytime you modify the order. This call should sent a request to the application server who will call the proper service to update your persistance layer for that list.
Then, you will also need to adapt your persistance layer to order the list with the "rank" information you persisted earlier when comes to moment to display your page.
I guess this is the most efficient way.
Good luck !

Categories