How do i pass data from blade to blade file - javascript

I try to pass two value from javascript to another blade file after click button to redirect to new window ...Here is my code
ReportCreate.blade.php js
$("#state").on("change", function() {
var id = $(this).val();
console.log(id)
var cuid = document.getElementById("cu").value;
console.log(cuid)
});
</script>
Click button to open new window which is carry two value from javascript
onclick="openNewWindow('{{ route('sla.slaCategoryTreeListScreen') }}')"
slaCategoryTreeListScreen.blade.php
<!DOCTYPE html>
<script>
// how do i retrieve two value from another blade file
</script>
</html>

First, You'll need to send those values when making the request. You can do this with query params passing a second argument on the route() helper:
onclick="openNewWindow('{{ route('sla.slaCategoryTreeListScreen', ['id' => 123, 'cuid' => 456]) }}')"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Then, you get those values in your controller to finally return them to the second blade file:
# MyCoolController.php
public function toMySecondView(Request $request)
{
$id = $request->get('id');
$cuid = $request->get('cuid');
return view('my_cool_second_view', ['id' => $id, 'cuid' => $cuid]);
}
Just then you'll be able to use them in your second view:
# my_cool_second_view.blade.php
<span> ID: { $id } </span>
<span> CUID: { $cuid } </span>

Related

Laravel - JS : search function without reloading page, return html

on a small project using laravel and javascript, I would like to implement a search functionality
For this, I would like that once the search is submitted, the page content changes without reloading
So I have a first method in my controller, which renders the page view complete with my data
In the page template, I included a file of partials, containing only my foreach loop and the associated html
Here is the controller method
public function __invoke(MyService $myService)
{
return view('posts.index', [
'posts' => $myService->getAll(),
]);
}
and my partials present in posts.index
#foreach($posts as $post)
<div class="">
{{ $post->name }}
<p class="my-4">
{{ str($post->data)->limit(150) }}
</p>
</div>
#endforeach
So, in my posts.index, I add this JS
var search = document.getElementById("search");
var by = document.getElementById("by");
var form = document.getElementById("form");
form.addEventListener("submit", function(evt) {
evt.preventDefault();
fetch('/search?search=' + search.value + '&by=' + by.value)
.then(response => response.json())
.then(data => {
var elem = document.querySelector('#result');
elem.innerHTML = JSON.stringify(data.html)
});
});
The #result element is where I'm including the partials
There is my search function
public function search(Request $request){
$by = $request->input('by');
switch ($by){
case 'name':
$service = new MyService();
$result = $service->getPostsForName($request->input('search');
$html = view('partials.list', ['posts' => compact('result')])->render();
return response()->json(compact('html'));
break;
}
}
The two methods of the controller return me an Array of Post (my model)
But when I run a search I always get the following error
attempt to read property "url" on array in file
I can't understand why, could you help me please ?

Variable returned by Symfony controller always undefined

Ok, so I have a text field in which I type a string and I have a button next to it.
<div class="sidebar-search">
<div class="input-group custom-search-form">
<<label for="riot-summoner-input">Search a Summoner</label><br>
<input type="text" id="riot-summoner-input" class="form-control" placeholder="Type summoner name..." style="margin-bottom: 20px">
<button type="button" id="valid-summoner">Search</button>
</div>
</div>
By Clicking on this button, the following script gets executed
let res = {{ summoner.summonerLevel }}
$(document).ready(function() {
// Get value on button click and pass it back to controller
$("#valid-summoner").click(function () {
const summoner_input = $("#riot-summoner-input").val();
console.log(summoner_input)
let url = `/coach/?summonerName=${summoner_input}`
history.replaceState(summoner_input, 'Coach Index', url);
console.log(url)
function loadXMLDoc()
{
document.getElementById("display-summonerLevel").innerHTML = `Summoner Level: <h2>${res}</h2>`
}
loadXMLDoc();
});
});
Now as far as I can understand this will change my page url to include the value inserted in the text field and will send it back to my controller without refreshing the page, which it does.
Now in my Controller I'm using that value to do some logic with it
/**
* #Route("/", name="app_coach_index", methods={"GET"})
*/
public function index(CoachRepository $coachRepository, riotApi $callRiot, Request $request): ?Response
{
$value = $request->request->get('summoner_input');
if($value != null){
$this->debug_to_console($value . "Hi");
return $this->render('coach/index.html.twig', [
'coaches' => $coachRepository->findAll(), 'summoner'=> $this->showSummoner("$value")
]);}
else{
$this->debug_to_console($value);
return $this->render('coach/index.html.twig', [
'coaches' => $coachRepository->findAll()
]);
}
}
Now it's interesting to note that I'm doing this in the index function.
Here's the function I'm calling within the index function which is actually the one that gets the value from the script
/**
* #Route("/?summonerName={summoner_input}", name="show_summoner", methods={"GET"})
*/
public function showSummoner($summoner_input)
{
$call = new ApiClient(ApiClient::REGION_EUW, 'API-KEY-HERE');
return $call->getSummonerApi()->getSummonerBySummonerName($summoner_input)->getResult();
}
Now that I'm seeing this I can see that the issue is I'm getting the value in the showSummoner() function but trying to use it in the index function. Which is why I'm not getting a value when I print it to console and the variable is undefined.
Honestly I can't think of any logic I can do to overcome this issue.
EDIT!!!!!!!
Okay, so I know where the problem is arising, the issue is when I'm calling showSummoner($value) within index function. I'm using $value = $request->query->get('summoner_input');
I thought I was getting that value in the index function when in fact I'm getting it in the showSummoner() function. You can tell by the annotations
For index I don't have a parameter in its url, whereas in showSummoner() I have a parameter in the annotations as such.
/**
* #Route("/?summonerName={summoner_input}", name="show_summoner", methods={"GET"})
*/
This is indeed the fact because I'm using that url in the script as such
let url = `/coach/?summonerName=${summoner_input}`
The reason for this is I can't use the parameter in the index url because then I would have to provide the parameter in all the other places I'm using index in even when I don't have a parameter meaning I didn't search for anything.
I hope this gives more clarification
You're trying to get a value from $_GET global, not $_POST.
You can replace :
$value = $request->request->get('summoner_input');
by:
$value = $request->query->get('summoner_input');
You are trying to access the GET parameter using the wrong name ('summoner_input').
$value = $request->request->get('summoner_input');
When you are setting it as summonerName here:
let url = `/coach/?summonerName=${summoner_input}`
You will also want to pass a default value to check for, as the second parameter.
Try this:
$value = $request->request->get('summonerName', false);
if(false !== $value){
/* the parameter is in the url */
}

how to get a value from a form blade index to jquery from blade edit?

i want to edit from one annonces, then the form of balde edit changes according to souscotegory_id, me i want to know souscategory_id comes from blade index to jquery from blade edit, in my case it gives me null.
index.blade.php
<span class="fa fa-edit"></span>
AnnonceController.php
public function edit($id)
{
$annonce = Annonce::find($id);
return view('annonces.edit')->with([
'annonce' => $annonce
]);
}
edit.blade.php
let souscategory_id = window.sessionStorage.getItem('souscategory_id');
alert(souscategory_id);

How to pass JS variable to Modal route

im trying to update data from modal so that i want pass id to my form route how can i do here
$("body").on("click",".edit-item",function(){
var id = $(this).parent("td").data('id');
console.log(id);
var description = $(this).parent("td").prev("td").prev("td").text();
var log_time = $(this).parent("td").prev("td").text();
var url = '{{url('calls/'.$call->id.'/sub_calls/'.$subCall->id.'logs')}}}'
$("#edit-item").find("input[name='description']").val(description);
$("#edit-item").find("textarea[name='log_time']").val(log_time);
$("#edit-item").find("form").attr("action",url + '/' + id);
});
i want pass this var id to modal route here next to $subcall->id
{!! Form::model(['route' => ['calls.sub_calls.logs.update',$call->id,$subCall->id],'class'=>'form-horizontal','role'=>'form']) !!}
my route
Route::model('logs','App\Models\SubCalls\SubPortLog');
Route::resource('calls.sub_calls.logs','SubPortLogController');
You need to pass it in the routing file (it's wher you define routes) like this:
Route::post('calls/sub_calls/logs/{id}/update/{subId?}', ['uses' => 'SomeController#upddate']);
if you have derfined this route with Route::resource method then you should put my example from above just in front of this declaration like this:
Route::post('calls/sub_calls/logs/{id}/update/{subId?}', ['uses' => 'SomeController#upddate']);
Route::resource('calls/sub_calls/logs','SubPortLogController');
And then in your controller metyhod do it like this:
public function update($id, $subId = null)
UPDATE:
Try this:
Define form with a shortcode as a secound parameter i.e. :subId:
{!! Form::model(['route' => ['calls.sub_calls.logs.update',$call->id, ':subCallId'],'class'=>'form-horizontal','role'=>'form']) !!}
and then just replace it with the value that you want:
$("body").on("click",".edit-item",function() {
var id = $(this).parent("td").data('id'),
action = $('form').prop('action').replace();
$('form').prop('action', action);
(...)
}

use jquery variable in # block razor

I'm strugling with a jquery script inside a cshtml page. For short my question is how to use a var inside a # statement in a cshtml page?
below an example of what I'm trying:
<select id="DefaultText">
<option value="-1">-- select --</option>
#foreach( var d in Model.DefaultTexts )
{
<option value="#d.Id" >#d.Name</option>
}
</select>
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
var text = #Model.DefaultTexts.First( t => t.Id == id );
$('#CustomProductText').val(text);
});
</script>
I can't reach the var id. It's out of scope. I've also tryed it with a for loop and a if statement. But in the if statement I get the same error: out of scope.
The full story is this:
On my page I've a dropdown list. The items to select are short names for default text parts. Based on the id or name, I want to show the default text part in a textbox.
#CustomProductText is my textbox where the content should be placed (code not posted).
I've also tryed it with #: and statement but that did not work.
What am I doing wrong or maybe its not even possible what I'm trying to do.
As an alternative I've added a action to my controller to get the text form there. Below the code:
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
$.post("Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
//$('#CustomProductText').val(text);
});
</script>
controller code:
[HttpPost]
public ActionResult GetDefaultText(int id)
{
using( var context = new MyContext() )
{
var text = context.DefaultText.First( d => d.Id == id ).Text;
return this.Content( text );
}
}
This doesn't work. The action doesn't get hit in debug mode.
regards,
Daniel
The $.post that is not working for you, you should prefix the url with / sign and it will be hit as expected:
$.post("/Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
As for the razor solution, you can't use javascript variables in the razor code as it's not a scripting language. What razor does is simply rendering the strings (be it html or javascript or anything) into the page.
To do what you want you either need to request the server to pass the text to your page or render all the texts you have in the page and then access this rendered content in your javascript.

Categories