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.
Related
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
I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});
I'm trying to use a button to perform an API Call to Flickr, like so:
$(document).ready(function (){
$('#goButton').click(function (){
makeAPICall();
});
});
This works as expected, but the communication between the client and the Flickr API takes a while to execute, so the page appears like it is hung. I would like to add a "Working Notice" that is displayed immediately on button click to let the user know that their action is processing.
To do this, I added an H1 tag:
<h1 id="notice"></h1>
and a function that changes the inner HTML to display a notice:
function workingNotice() {
document.getElementById("notice").innerHTML="I am getting your results";
}
But when I try to edit the code for the button to something like this:
$(document).ready(function (){
$('#goButton').click(function (){
workingNotice();
makeAPICall();
});
})
The Working Notice is never displayed until the API Call has completed, which defeats the purpose.
I then tried using:
$(document).ready(function (){
$('#goButton').click(function (){
$.when(
workingNotice()
).then(
makeAPICall()
);
});
})
This gives the exact same results, where the Working Notice is not called until the API Call completes. Is there any alternative that I can try to force the order of these functions to comply?
UPDATE/EDIT:
While I found the solution to the initial problem in another answer, I know there's a reasonable chance the delay in the API Call processing is due to some mistake in this function. Here is the code for makeAPICall:
//call Flickr api and look for tags matching user search term
function makeAPICall(){
//get value tag from team 1 search box
var searchTag1 = escape(document.getElementById("searchTag1").value);
//get value tag from team 2 search box
var searchTag2 = escape(document.getElementById("searchTag2").value);
//build api call url with searchTag1
var url1 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag1 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//build api call url with searchTag1
var url2 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag2 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//make call to flickr api
$.when(
$.ajax({
dataType: "json",
url: url1,
async: false,
success : function(callReturn1) {
callData1 = callReturn1;
numResults1 = parseInt(callData1.photos.total);
}
}),
$.ajax({
dataType: "json",
url: url2,
async: false,
success : function(callReturn2) {
callData2 = callReturn2;
numResults2 = parseInt(callData2.photos.total);
}
})
).then(
drawChart()
);
}
Note "callData1", "callData2", "numResults1" & "numResults2" are all global.
If your makeAPICall is not async - call it out of bounds:
workingNotice();
setTimeout(makeAPICall, 1);
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.
an answer from a previously question I asked here has posed another problem for me, as I am learning more and more about async calls I still can not figure out how to accomplish (as the previous answer showed me) a list which allows me to store and use data from a selected list item.
$('#home').live('pageshow', function(){
// creating object
var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
});
with js fiddle http://jsfiddle.net/amEge/3/
This code works excellent and will allow me to accomplish what I want but fist I need to populate the customerList from a ajax call. But from the "success" function I cannot seem to get the code to work.
$.post(postTo,{id:idVar} , function(data) {
customerList = data;
//alert(customerList);
})
When I move the code inside the ajax function it dose not work. I was just wondering if anyone could help me and maybe show me how to deal with this from asynchronous calls ?
Many Thanks
You need to change your page as below.
// I assume this is your dot net web service url
var webServiceURL = 'customer.asmx/GetCustomer';
// here home is your page's ID
$('#home').live('pageshow', function(){
getCustomerList();
});
function getCustomerList(){
param=JSON.strigify({id:'2'});
callWebService(param, webServiceURL, onGetCustListSuccess, onGetCustListFailed)
}
function onGetCustListFailed(){
alert("service request failed");
}
function onGetCustListSuccess(data, status){
// creating object
// replace previous line with below
// var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
var customerList = JSON.parse(data.d);
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
}
function callWebService(param,url,successFunc,errorFunc){
if(errorFunc=='undefined'){
errorFunc=OnDataError;
}
$.ajax({
type: "POST",
url: url,
data: param,
contentType:"application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc,
beforeSend:function(){$.mobile.loading( 'show' );},
complete:function(){$.mobile.loading( 'hide');}
});
}
Hope this would help you out. If you have problems asks me here.
Correct me if I'm wrong, but I'll hazard a guess that your "live" code looks something like this:
$('#home').live('pageshow', function(){
// creating object
var customerList;
$.post(postTo, {id:idVar}, function(data) {
customerList = data;
//alert(customerList);
});
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// and all the rest...
If so, then your problem is that the code that's depending on your customerList variable being filled in ("all the rest...") runs immediately, rather than waiting for the response from your HTTP request to come back from the Web server. That $.post() doesn't wait around (or "block," as we say in the computer software programming game) while the HTTP transaction makes its way to the Web server and back. Instead, the rest of your code runs immediately, and then later, when that response comes back to the browser, the JavaScript engine dutifully executes your success function (or "closure," as we hm hmm hmmmm).
So what you'll want to do is put all this other code (the stuff that's dependent on customerList) into a separate function, then call that function from within your success closure. You won't even need your customerList variable then; you can just pass the new response data as an argument to your new function.