Execute a controller action from jQuery/javascript - javascript

I have a ListBox in my view - when I select an item from the list box, I want to call a controller method, execute a lookup on that value, then redraw the page with those values.
My listbox code and my jQuery code looks like this:
#using (Html.BeginForm())
{
...
<h3>Environments</h3>
#Html.ListBox("Environment",
new SelectList(Model.Environments),
new {#id="environmentsListbox"})
...
}
<script>
$(document).ready(function () {
$('#environmentsListbox').click(function () {
var selected = $('#environmentsListbox').find(":selected").text();
$.ajax({
url: '#Url.Action("Index")',
data: { selectedEnvironment: selected },
success: function(data) {
---- What to do here?
}
});
});
});
</script>
The controller method looks like this:
public ActionResult Index(string selectedEnvironment)
{
// code omitted for brevity...
var frameworkConfig = GetInfo(selectedEnvironment);
return View(frameworkConfig);
}
The call works correctly, the selected text does make it to the controller method....however what do I do with the result? I'm looking for something comparable to #Html.Action("Index", selectedEnvironment) that you would use in a normal MVC context (non-js). I have the returned View code in the data variable, is there a way to reload the page with that value?
I've seen the answer in this post: How to call URL action in MVC with javascript function? and is very close to what I need to do, however the resulting view code from that controller method is pushed into a contained div tag, not the current view.

You can use jQuery's .html() function. Inside your success callback, do something like this:
<script>
$(document).ready(function () {
$('#environmentsListbox').click(function () {
var selected = $('#environmentsListbox').find(":selected").text();
$.ajax({
url: '#Url.Action("Index")',
data: { selectedEnvironment: selected },
success: function(data) {
$('#container').html(data);
}
});
});
});
</script>
You want to make sure that the view you are returning from your controller has the markup that you need (without any layout code etc). Access that url directly in the browser to see what it returns.

Related

passing data from laravel view to controller via ajax onchange event

I have a dropdown list in a blade view. I want to send the value of the selected item to the controller immediately onchange. I have 2 routes in web.php:
Route::get('/plots', 'PlotController#index');
Route::get('/plots/{testId}', 'PlotController#getData');
The first one populates the dropdown list. The second one is supposed send the value of the dropdown list to the controller, which pulls stuff from mysql and sends the data back to the view, which draws a chart. I can get the dropdown to populate ok, but I can't figure out how to send the selected value to the controller. I'm trying to use ajax to do it like this:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
console.log("testId=" + testId);
$.ajax({
url: 'plots/' + testId,
type: 'get',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
});
});
The testId output to the console is correct but it never makes it to the controller. The error I see in the console is:
GET http://homestead.test/plots/1 500 (Internal Server Error)
I'm pretty new to laravel and find it extremely confusing. Can anyone explain the correct way to do this?
EDIT:
After testing and confirming Rian's answer as correct, I then tried to implement the real code, which of course is much more complicated. Instead of the controller returning the input test_id:
return $request->test_id;
It actually returns a more complex structure:
return view('plot')
->with('measurements',json_encode($result))
->with('events',json_encode($timeline))
->with('limits',json_encode($limits));
When I uncomment the original controller code, including the return section above, it seems to affect the ability of the controller to return anything at all. Here is the first few lines of the PlotController getData method:
public function getData(Request $request) {
Log::debug("made it to PlotController.php#getData");
Log::debug("test_id="+$request->testId);
And here is the log output:
[2020-02-23 16:43:52] laravel.DEBUG: made it to
PlotController.php#getData
The second line does not output anything. Here is what I see in the javascript console after I select an item from the dropdown list:
testId=49 jquery.min.js:2 GET
http://homestead.test/get-data-by-id?test_id=49 500 (Internal Server
Error)
Any ideas?
The easiest way is to get the data in Laravel Request. At least that's how I do it.
So your route shouldn't contain any parameter for that.
Your route will look like this:
Route::get('get-data-by-id', 'PlotController#getData')->name('get.data.by.id');
Your ajax should be like this:
$(document).on('change', '#sel_test',function(){
var testId = $(this).val();
$.ajax({
type:'GET',
url:"{{ route('get.data.by.id') }}",
data:{'test_id':testId},
success:function(data){
console.log(data);
}
});
});
In your controller's getData() function just use Laravel Request to fetch the data.
public function getData(Request $request)
{
// You can return the ID to see if the ajax is working
return $request->test_id;
}
Make it post from Get for easier
At Web.php
Route::post('/list/plots', 'PlotController#getData')->name('getData');
At Blade file Ajax Request :
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
var url = '{{ route("getData")}}';
var token = "{{ csrf_token()}}";
$.ajax({
method:"post",
url: url,
data:{testId:testId,_token:token}
dataType: 'json',
success: function(response) {
console.log("success",response);
}
});
});
});
At Controller :
public function getData(Request $request){
$testId = $request->testId;
// Write your logic here
}
Try this. Hopefully work for you

Updating a div based on a select event from KendoUI Widget

I have a KendoUI search bar that has a drop down of autocompleted items based on what I type. When I type into I get a drop down menu. When I click on an item in the drop downlist, I want two things to happen. One which works, and that is loading a partial view. But, the other thing deals with updating a div element that is also in that partial view.
The partial view
#{
ViewBag.Title = "Client";
}
<div id="update">#ViewBag.name</div>
<p id="ahhh"></p>
External Javascript function
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
alert("IT WORKED");
},
error: function (result) {
alert("FAILED");
}
})
}
In the HomeController there is a method called someStuf. I am sending that item that is clicked on the event into the someStuf method.
Now here are the two controller methods that I'm working with.
Secretary s = new Secretary();
public ActionResult Client()
{
ViewBag.name = s.Client;
return PartialView();
}
[HttpPost]
public JsonResult someStuf(String n)
{
s.Client = n;
return Json(n, JsonRequestBehavior.AllowGet);
}
So then I update a class with that value that was passed from javascript. I then add that new value to the viewbag for the partial view Client.
Sorry for the misleading variables. Client is a type of model. Then I always have a partial view that is called client.
When I try this. The ViewBag is not showing the result that I would like. I can get the client side to send to the server. But I can't get the server to send to the client.... I bet it's something simple. But I'm trying to understand this step so I can use the same method to update id and class elements.
<p class="CompanySearchBar">
#(Html.Kendo().AutoComplete()
.Name("companyComplete") //The name of the AutoComplete is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("company") //Specify which property of the Product to be used by the AutoComplete.
.BindTo(Model)
.Filter("contains")
.Placeholder("Company name")
.Events(e => { e.Select("onSelect"); })
)
</p>
The above code allows for a search bar with autocomplete. While typing for an item a drop down list shows up with results having the same substring. When clicking one of the results the onSelect method is activated.
you can give like this and on change event just assign a value using jquery like
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
$('#ahhh').text(result.NAME); //the object which you returns from the controller
},
error: function (result) {
alert("FAILED");
}
})
}
<label id=ahhh></label>

How to use jQuery to reload Partial with new parameter

I have a partial view that I load in a page passing in a parameter. When the page loads, I setup two parameters helpMember and helpAnonymous.
{
var helpMember = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(0);
var helpAnonymous = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(1);
}
<div id="contextual-help-partial" >
#Html.Partial("ContextualHelp", helpMember)
</div>
With jQuery, how can I reload the Partial and pass helpAnonymous to it?
You have to create one method in controller and call that action using this. Suppose created action as loadhtml. return partialview from that action.
Controller action as
public ActionResult loadhtml(string helpMember){
ViewBag.helpMember = helpMember;
return PartialView("ContextualHelp");
}
jquery code as
$.ajax({
type: 'GET',
url: "/loadhtml?helpMember=#helpMember",
datatype:"html",
success: function (data) {
$("#contextual-help-partial").empty().html(data);
},
error: function (err) {
}
});

submit a form with jQuery function

i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.

Telerik MVC Grid - Pass Value to New Controller Action

Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.

Categories