Laravel Routes with AJAX file - javascript

I'm new to Laravel and I'm trying to learn how to create a dynamic drop down box where the 2nd drop down box will change depending on what is selected in the 1st one.
Here is my form code inside my blade file:
{!! Form::open(array('url'=>'', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
#for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
#endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}
Here is my AJAX code (also inside the blade file but in <script> tags:
<script>
$('#cinema').on('change', function(e){
console.log(e)
window.alert("On Change");
var cinema_id = e.target.value;
//ajax
$.get('/ajax-subcat?cinema_id=' + cinema_id, function(data){
//success data
console.log(data);
window.alert("On Success");
$('#sesh').empty();
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value=""' + subcatObj.id +'">'+subcatObj.name+'</option>');
});
});
});
</script>
And finally here is my route:
Route::get('/ajax-subcat', function(){
$cinema_id = Input::get('cinema_id');
$sessions = Session::where('cinema_id', '=', $cinema_id)->get();
return Response::json($sessions);
});
So this code is not generating any data and is instead giving me a 404 error.
I have verified that the AJAX code does go inside the "change" function, through alerts, however it is not showing the 2nd alert. In my limited understanding, I feel like there may be an issue in my routes file? As if the route file is returning data, the next function in AJAX should be running.
One thing I don't understand in the routes code is what Input::get('cinema_id') is doing. I think it's grabbing what the user input in the drop down box?

Since it's giving 404 error, I hope using full url will solve this. Use
//ajax
$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
//success data

Add header in your ajax call
headers : {
'csrftoken' : '{{ csrf_token() }}'
}

Seems like theres a few things going on here. It's important to separate what is happening on the on the server with Laravel, and in the client with your Javascript.
SERVER
Sends the form with data in it. Any blade syntax you use like this.
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
Is rendered on the server before it is sent to the client. That is how the first drop down is being populated with data when you load the page.
CLIENT
Looks like your using AJAX to make request based on users selection from the first drop down. This line:
$.get('/ajax-subcat?cinema_id=' + cinema_id, ...
Is going build request to your Route::get('/ajax-subcat', ... along with a query string. ?cinema_id=1. Input::get('cinema_id'); should take the value of the query string (1).
It looks like you've set up the the route correctly so I'm thinking its a problem with var cinema_id = e.target.value;. I'd check it's value before the request is made and make sure it lines up with the value that your query on the server is going to need.
The value of var cinema_id on the client, is going to be the value of $cinema_id on the server for your query.
Hope this helps,
Matt

Change
uploadUrl: '{{route("product/create")}}',
to
uploadUrl: '{{url("product/create")}}',
and add this in ajax
headers: {
'X-CSRF-Token':{{ csrf_token() }},
},

Related

communication between PHP and JS when a row is added in JS

I have a php code as shown below:
Php code:
<?php
$output['house_sitting_date_yes_no']=$_POST['house_sitting_date_yes_no'];
if(file_exists('../feeds/ptp-ess_landing_house.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_house.json'));
}
?>
<?php if($data) { ?>
<form>
<!-- Sitting Days START -->
<div class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
<!-- Yes/No START -->
<div class="yes-no">
<h4 style="text-align:center;">Yes/No</h4>
<select name="house_sitting_date_yes_no" id="house-yes-no" style="height:24px;">
<option value="nada" <?php if($data->{"house_sitting_date_yes_no"}=="nada"){echo 'selected';}?>>Please choose an option</option>
<option value="yes" <?php if($data->{"house_sitting_date_yes_no"}=="yes"){echo 'selected';} ?>>Yes</option>
</select>
</div>
<!-- Yes/No END -->
</div>
<!-- Sitting Days END -->
</form>
<? } else {
echo 'Cannot read JSON settings file';
}
?>
The above php code corresponds to the following fiddle. In the fiddle, its adding a new row on click of a button in Javascript.
I haven't included JS code in the above php code. Add new row button lets us add as many rows as we want. After adding we can enter Yes in the input box and then Save.
Problem Statement:
I am facing one issue at this moment. When I am adding new rows, form do get saved but newly added rows get deleted leaving back only one row (Date and Yes/No).
I am wondering what changes I should make in the php code above so that when we add new rows, it should have some values associated with it so that when we save the form newly added rows should stay
there with their respectibve values.
When there is one row (when I am not adding new row), everything is pulled from the JSON and its working perfectly fine.
You'll need to make some alterations to both your HTML, JS and PHP for it to work properly. No communication is needed from JS to PHP. The form submission already works, right?
Modify the name attribute value.
Because you have multiple select and input elements in your code you'll want to be able to send all of the values of these elements to the server. But because they all have the same name attribute values you'll need to make a modification to these values.
Add a [] to the end of the name. This enables PHP to read every house_sitting_date_yes_no as an array. That means that every, in this case, select field value on the page will be send to the server in the global $_POST variable.
Check the example below.
<select name="house_sitting_date_yes_no[]">
...
</select>
The name has a [] at the end to indicate that there will be multiple values under the same name of house_sitting_date_yes_no.
<?php
$_POST[ 'house_sitting_date_yes_no' ] // array( 'yes', 'no', 'nada' )
?>
On the serverside you can access these values like you normally would do. But in this case it is not a string but an array with multiple strings. One string for each, in this example, select field.
An ID can only be used ONCE. Use classes instead.
Your newRow function creates a new row. Which is a perfect way to do it but the function also outputs elements with id's. ID's have to be unique and cannot be on the page more than once.
Wherever the id's can be removed, remove them and use a class instead. Or make them unique like they should be.
Storing the values in JSON
You were already on your way with this one with opening and decoding the JSON file. I assume you want your JSON to be updated with more data instead of overwriting the current data.
Since the data will be stored in associative array that is encoded to JSON it's possible to use array_merge_recursive to combine these arrays and their values.
After combining the values encode the array back to JSON and use file_put_contents to save your file again.
$output = array();
$output['house_sitting_date'] = $_POST['house_sitting_date'];
$output['house_sitting_date_yes_no'] = $_POST['house_sitting_date_yes_no'];
$file_url = '../feeds/ptp-ess_landing_house.json';
if (file_exists($file_url)) {
// Get current file.
$current_data = json_decode(file_get_contents($file_url));
// Combine data if possible, or create a new data.
if (is_array($current_data)) {
$new_data = array_merge_recursive($current_data, $output);
} else {
$new_data = $output;
}
// Update the file with new data.
$updated_data = json_encode($new_data);
file_put_contents($file_url, $updated_data);
}
I hope this helps you out.
Ok from what I see in your code is the old way I used to do things when working with PHP
I used to mix PHP with HTML and Javascript which on a big projects makes things a lot harder to maintain and debug especially many years down the line .You end up with many if else statements that could complicate your code
As well as if the PHP server is hanging because of shared hosting traffic or latency at least the clients browser does not hang. XHR and Rest API's were the Aha moment for me...
So I changed the way I worked with the web technologies and started working with rest API clients and separating my front end and back end technologies
Here is my suggestion
HTML Forms, XHR and Jasvascript posts to the rest PHP server for
every onclick event (this keeps the browser fast and wont hang like a php page sometimes does when working with background service)
The server handles each request reads the JSON from the file and
slots the new entry in then saves the file (PHP ONLY in the background)
Javascript then refreshes the JSON cache. At the end of the XHR request display the dates page (do this by adding keywords like async and await )
Here is the start..
Call this file post.PHP
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
if($_POST)
{
echo json_encode($_POST);
//Open your Existing JSON file here and do the edits to append the new data
//Note weather your data passed or failed you have to respond back to the XHR request in the front end with json_encode...
}else{
echo json_encode(
array('message' => 'Post Created')
);
}
?>
Its the same as a rest client access point. This file is where you edit your json with the update ...
The snippet is the frontend with the XHR and a special technique to extract form data from a HTML form
function rowAdd(event) {
document.getElementById("rows")
.insertAdjacentHTML('beforeend', newRow());
}
// Iterator to get allow unique for ID;s
let i =0 ;
function newRow() {
i++;
return `
<div id="default-node" class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
<div class="select-date" style="margin-right:30px;">
<input type="date" id="house-sitting-date`+i+`" name="house_sitting_date`+i+`" value="">
</div>
<div class="yes-no">
<select name="house_sitting_date_yes_no`+i+`" id="house-yes-no`+i+`" style="height:24px;">
<option value="nada" selected>Please choose an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
`
}
let xtart = document.getElementById('xhrStart');
xtart.addEventListener('click',function(){console.log('Xstarted')
// First iterate over the form and get all the form Values
var element = {};
var data = new FormData(theForm);
// Display the key/value pairs
for(var pair of data.entries()) {
// console.log(pair[0]+ ', '+ pair[1]);
element[ pair[0].toString() ] = pair[1];
}
console.log(element);
// Time to send the control over to PHP to do its magic
let xhr = new XMLHttpRequest();
xhr.open('POST', 'post.php');
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.responseType = 'json';
xhr.send(JSON.stringify(element));
//xhr.send();
// the response is {"message": "Hello, world!"}
xhr.onload = function() {
let responseObj = xhr.response;
alert(responseObj.message); // Hello, world!
};
});
<h3 style="text-align:center;margin-top:45px;">Sitting Days</h3>
<div class="add-new-row-button">
<input type="button" id="addRow" value="Add New Row" onclick="rowAdd()" />
</div>
<form id='theForm'>
<div id="rows">
<div class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
<div class="select-date" style="margin-right:30px;">
<h4 style="text-align:center;">Select Date</h4>
<input type="date" id="house-sitting-date" name="house_sitting_date" value="">
</div>
<div class="yes-no">
<h4 style="text-align:center;">Yes/No</h4>
<select name="house_sitting_date_yes_no" id="house-yes-no" style="height:24px;">
<option value="nada" selected>Please choose an option</option>
<option value="yes">Yes</option>
</select>
</div>
</div>
</div>
<input type='button' value='Submit' id='xhrStart'>
Note I gave the form an ID and created and iterator so each new element in the form is unique
Here is the snippet ...
PHP leaves you also slightly in the dark about the weather data was received or not and using XHR allows you to easily see server responses with Google debugging tools ... Node JS , react and and all the other great technologies have used the same principals of rest api because it allot simpler and it makes debugging on chrome a breeze
Here is an image of the debug
Trust this helps and allows you to work far more efficiently
<?php
echo "<div id='demo'></div>";
?>
<script type="text/JavaScript">
// Function is called, return
// value will end up in x
var x = myFunction(11, 10);
document.getElementById("demo").innerHTML = x;
// Function returns the product of a and b
function myFunction(a, b) {
return a * b;
}
</script>

How to pass input text value to another page using javascript

I am building a management system in which the admin can select an item from the database table and update the details. To achieve this I have two forms on two pages. The first form is to select the item from table and pass it's ID to the second page where I will use the ID to fetch the details from the table using php. I want to do this with javascript so it will not refresh the page. My question is how to pass this value? I am using the following code, but it is not working.
HTML
<div id="result"></div>
<form action="update_item.php" id="update" method="post" >
<select name="selected" class="form-control" id="myItem" required>
<option>Select item</option>
<?php
<!-- PHP script to select the item -->
?>
</select>
<button id="submit">Select</button>
</form>
JAVASCRIPT
$(document).ready(function() {
$("#submit").click(function() {
var chat = $('#myItem').val();
if(chat=='')
{
alert("Please select an item!");
}
else{
$.ajax({
type: "POST",
url:"update_item.php",
data:{
data:chat,
},
success: function (msg) {
//alert(msg):
$('#result').html(msg);
},
error: function(){
alert('error');
}
});
}
});
});
PHP
Second page
$item_id = $_POST['data'];
$get_item = "select * from items where item_id='$item_id'";
<--PHP script continues-->
You can add a hidden field and send this input back to your server:
<input type="hidden" name="something" value="<?= $_SERVER['id'] ?>" />
And then access it with via:
$_SERVER['id']
If you are not changing the page between forms you should be able to just create a variable on the client side that stores the necessary data. Since the second form is loading into the same environment, any variables you have from the first form will still exist.
From your example, I'm guessing chat is the data you're trying to use in the second form. Right now it is local to the click function (once that function completes the variable disappears). You could either move the declaration of that variable into the global scope (outside of document.ready), or use it as intended inside the success callback. (From your example it is unclear what you are trying to do with this data)

Submit form on same page without reloading and use POST variable

I need to get the value of a post variable from a form and transform this to a PHP variable to use it on the same page without reloading it
Actually I got this :
$(function() {
$("#submit_post").click(function() {
var select = $("select").val();
$.post("process.php",{select:select},function(result){
$('#result').append(result);
});
});
})
And
<form method="post">
<select name="select" id="select">
<option value="1">Test</option>
</select>
<input type="submit" id="submit_post" value="Envoyer" onclick="return false;"/>
</form>
<div id="result"></div>
When I do :
<?php var_dump($_POST["select"]); ?>
I got : null
But on div result I got : 1
...
I need to lake this "1" a php variable
Your code runs fine on my server. Maybe you aren't totally clear on the function of the superglobals.
If the "result" div contains "1" after you press the button, then that means process.php is correctly receiving your POST request and echoing back the value of $_POST["select"]. You will get "NULL" if you try to just navigate your browser to process.php, because when you do so you are making a separate request which doesn't contain any POST variables. The superglobal arrays don't persist between different calls to process.php unless you create that functionality using $_SESSION, a DB, or some kind of text/json/xml storage system. The following changes to your PHP will allow you to click your button and then separately navigate to process.php and see your data:
<?php
session_start();
if ($_POST["select"]) {
$_SESSION["data"] = ($_POST["select"]);
}
var_dump($_SESSION);
?>
Please correct me if I have made the wrong assumptions and this is not helpful.
-Ben

how to receive selected option on the same php page

I need to display the content(per page) based on the option(per page) selected by the user
for which i need the selected option value in the same php page to display the content
but i cannot receive the value in php code ,Kindly give some solution to this problem
I've tried
Pass Javascript variable to PHP via ajax
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_option_value
HTML Code for selecting option :
<select id="page_count" >
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
JavaScript when option changed :
var total_items;
$(document).ready(function(){
$("#page_count").change(function(){
var x = document.getElementById("page_count").selectedIndex;
total_items=document.getElementsByTagName("option")[x].value;
alert(total_items);
AJAX for posting the selected option :
$.ajax({
type : "POST",
url : "start_landing_page.php",
data : {total_items: total_items},
success : function(data){
alert("sucess!");
}
});
received via AJAX in php :
<?php
if(isset($_POST['total_items'])){
$uid = $_POST['total_items'];
var_dump($uid);
}
>
The POST request should send data like this:
data : 'total_items='+encodeURIComponent(total_items),
I feel you can use many options to get and pass the value, following is the simplest way you can access the selected value and pass it in your ajax function:
$("#page_count").change(function(e){
total_items = $(this).val();
....
...
});
Full Example: Jquery Receive selected option and Passing it in Ajax by using $.param()

How can i refresh form after submit?

i have form like
<form id="abc">
<div>
<select >
<option id= "1"> ha1 </option>
<option id= "1"> ha2 </option>
<option id= "1"> ha3 </option>
<option id= "1"> ha4 </option>
</select>
<input type="submit">
</div>
</form>
for form submit i have used like
$(document).ready(function() {
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
$('#abc').reset(); //(this).reset();
});
return false;
});
});
Here reset is not working. Any problem with reset i am not getting.
After form submit, i want to refresh form with db values (to display values selected just now).
how can i refresh page after submit or either div refresh.
$(document).ready(function() {
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
window.location.href=window.location.href;
});
return false;
});
});
reloads the page by setting the href to the actual one :)
or you can also use this:
parent.document.getElementById("abc").reload();
by the way: i dont see your serverside code, you have to render the selected values, of course, i am assuming that you are returning them, my answer doesnot cover the serverside scene. my code is only for the case that you are returning the selected values from server after saving them into db.
Reset form fields using Pure JavaScript.
document.getElementById("formid").reset();
If you own server side code, you can return the values in the response and then fill the fields with these values in the callback.
Let's say this is your response JSON:
{
data: [{
"username": "john doe"
}]
}
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
$('#abc').reset(); //(this).reset();
$('input#username').val(data.username);
});
return false;
});
As said in the answer by doniyor, you can use window.location.href to refresh the page, but this will not populate your form with the values you just wrote to your database.
you have two options available for populating your form with the database, implementing both might be desirable in your case (up to you).
The first is to populate the form when you first load your html. This can be done server side by making a query to your database and getting the values, and then setting the correct radio button based on the value like so:
<input type="radio" selected="selected" />
The other option is to set the checkboxes async with jquerys .prop() method. This requires that your tags have unique ID's (which they should have anyways). Example:
$("#yourIDHere").prop('checked',true);
In the latter case, you could have the script you post to output the correct ID to use. This is up to your discretion, and is dependant on your case, but hopefully this answer points you in the right direction.
Best regards
Try to use this,
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
$('#abc').find('input:text, input:password, input:file, select, textarea').val('');
$('#abc').find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
});
return false;
});

Categories

Resources