Using Jquery inside of Razor - javascript

I'm trying to pass a string from javascript to a razor ActionLink
string filtering =$("#Hello").val();
#Html.ActionLink(Name, ControllerName, new { sort = columm, order = orderby, filters = filtering })
but I'm not able to access to this variable, I already try #:filtering or "#filtering" but doesn't work anyway,
How can I pass the variable to the controller?

If you want to send or post the data to Controller's Action then you may try this...
<input type="submit" id="btnFilter" value="Filter" name="btnFilter" />
$('#btnFilter').click(function () {
var sort = sortValue;
var order = orderValue;
var filter= filterValue;
$.ajax({
type: 'POST',
url: '#Url.Action(ActionName, ControllerName)',
data:'{"sort":"' + sort+ '","order":"' + order+ '","filter":"' + filter+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function () {
}
});
});
then.... in controller action
public ActionResult ActionName(string sort ,string order , string filter)
{
// do Something here....
}

You'd have to add the parameter to the URL yourself manually using jQuery to assign the href attribute of the anchor tag.
First, let's take off the filter parameter off your ActionLink and give it an ID (so we can reference it in jQUery):
#Html.ActionLink(Name, Controller, new { sort = columm, order = orderby }, new { id = "myLink" })
Then do the following jQuery:
$(function () {
var newLink = $("#myLink").attr("href") + "?filter= " + $("#Hello").val();
$("#myLink").attr("href", newLink);
});

the way that I could do it was passing the Url to the controller
window.location = window.location.protocol + "//" + location.host + "/Name/Controller/" + "?sort=sort" + "&order=order" + "&page=page" + "&filters=" + filter;

Related

How to update SharePoint 2010 Column with SharePoint Username via OnClick?

Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");

ASP.NET execute WebMethod with Jquery/AJAX

I have one WebMethod that will execute some DB search and return it's data in some HTML template. I need to execute this method using jquery to populate an area of the website but the problem is that my website URL/URI is dynamic.
My URL is http://site/school-name/home. The school-name will always change to indicate wich school i'm accessing.
I have accomplished so far:
$.ajax({
type: "POST",
url: "/Default.aspx/BuscaEquipe",
data: { 'pIndex': pIndex, 'pLimite': 4, 'pUnidadeCE': codigoEmitente },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
failure: function(response) {
alert(response.d);
}
});
and the WebMethod:
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
var objEquipe = new Equipe { EquipeUnidadeCE = pUnidadeCE, EquipeAtivo = 1 };
var CaminhoImagem = Configuracoes.CaminhoVirtual + "Controles/Redimensiona.ashx?img=" + Configuracoes.CaminhoVirtual + "images/equipe/" + pUnidadeCE + "/";
if (!objEquipe.Listar(objEquipe)) return "";
var depoimentos = objEquipe.lstEquipe.Skip(pIndex).Take(pLimite);
var objJson = new JavaScriptSerializer().Serialize(depoimentos.Aggregate("", (current, equipe) =>
current + ("<div class='col-lg-3 col-md-3 col-sm-3'><img src='" + CaminhoImagem + equipe.EquipeImagem + "&w=400&h=400' alt='" + equipe.EquipeNome + "' class='img-circle img_perfil'><div class='nome_perfil text-center'>" + equipe.EquipeNome + "</div></div>")));
return objJson;
}
Using like this i get a 401 Not Authorized and if i try to use my full URL http://site/school-name/Default.aspx/BuscaEquipe i get a 404.
P.S. I have already used this same method in another project and it worked fine but i can't figure out what's wrong in this one, i think it might be related to the URl but i'm not sure.
the problem is with your URL
Use the ResolveClientUrl() method
<%= ResolveUrl("~/Default.aspx/BuscaEquipe") %>
And you must Have [WebMethod] attribute before your static server function
[WebMethod]
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
//Code
}
Your data:
var requestData= JSON.stringify({
pIndex: pIndex,
pLimite: 4,
pUnidadeCE: codigoEmitente
})
and then
data:requestData

Laravel 4, Pass a variable to route in javascript

How Can I pass the variable (stock.id) return from Ajax response to the route to generate the url to edit a stock
$.ajax({
url: 'sectors/stocks/' + $(this).data('sector-id'),
dataType:'json',
beforeSend:function() {
$('.stocks_list').html('Loading...');
}
})
.done(function(data) {
$('.stocks_list').html('<ul>');
$.each(data, function(index, obj_data) {
$.each(obj_data.stocks, function(indx, stock) {
$('.stocks_list').append('<li>' + stock.symbol + ' </li>');
});
});
})
You can first use a placeholder to generate the URL with and then replace that in javascript.
var url = '{{ route("admin.stocks.edit", ":id") }}';
url = url.replace(':id', stock.id);
$('.stocks_list').append('<li>' + stock.symbol + ' </li>');
In my opinion the simplest way is by concatenating javascript variable with blade string as follows.
Case 1: Route paramter is required
In this case pass the empty string in place of route parameter to by pass the required validation.
var url = "{{route('admin.stocks.edit', '')}}"+"/"+stock.id;
Case 2: Route paramter is optional
In this case you do not have to pass the empty string.
var url = "{{route('admin.stocks.edit')}}"+"/"+stock.id;
Best way to use route in ajax.
Add route in hidden input or take as a attribute into the button or link. Like below.
This will save the other jquery code like get id and pass into the url. It's simple just get the url from input and pass as a URL. That's it.
<a data-url="{{ route('delete.PendingPatient',['id' => $u->id]) }}" class="btn btn-xs btn-danger btn_delete"> Delete </a>
Route
<?php
Route::delete('/pending_patient/{id}','PatientController#pending_patient'])->name('delete.PendingPatient');
jQuery
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(document).on('click','.btn_delete',function(){
var current = jQuery(this);
var url = current.data('url');
$.ajax({
url: url,
dataType:'json',
beforeSend:function() {
$('.stocks_list').html('Loading...');
}
})
.done(function(data) {
$('.stocks_list').html('<ul>');
});
});
});
});
</script>
Thanks lukasgeiter, you make my day. It works. Only must to change the replace method because laravel scape ":" to "%3A"
var url = '{{ url("/admin/solicitud", ":id") }}';
url = url.replace('%3Aid', data.datos[i].id);
dhtml+='<td>Ver más...</td>';
or simple let the id string only
var url = '{{ url("/admin/solicitud", "id") }}';
url = url.replace('id', data.datos[i].id);
dhtml+='<td>Ver más...</td>';
let calculatedId = e.currentTarget.id.split("_")[1];
let url = '{{route('queryToggleStatus', ':queryId')}}';
url = url.replace(':queryId', calculatedId);
$.get(url, function(data, status) {
console.log (data);
})

How can I access the element ID from a class, within an ajax function in jQuery?

I'm trying to use the typeahead script for Bootstrap. It's working great, but I'd like it to be a bit more dynamic. I'd like to run several auto-complete inputs on the same page without duplicating code.
HTML:
<input type="text" class="typeahead" name="person_name" id="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search">
Basic jQuery:
$('.typeahead').typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_script.php'
+ '?source=' + ###[HOW CAN I PUT ELEMENT ID HERE?]###
+ '&q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
The above doesn't work (obviously). But if I set the class name to .typeahead-person-search and then create a new typeahead function that manually adds the source person-search, and another function entirely for .typeahead-city-search, then everything works fine. I'd like to avoid having two functions when it's really just a variable that separates the two.
How can I put the element ID of the active .typeahead class into the $.ajax function?
Ok, I've gone up on something else, I couldn't test it directly with the .typeahead librairy, but I've done the same thing with another librairy I amusing.
How bout doing
$('.typeahead').each(function(){
var self = $(this);
self.typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_script.php'
+ '?source=' + self.attr('id')
+ '&q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
});
EDIT :: try my second answer it should work, I've been using that with another librairy that had the same problem
try something like
var id = $(this).attr('id');
then
var url = 'blahblah' + id + 'blablahblah);
and put the var url in your ajax query at the url: spot
You could add a data attribute to each input that contains the dynamic portion of the URL.
<input type="text" class="typeahead" name="person_name" id="person-search" data-source="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search" data-source="city-search">
You can then grab that using jQuery and pass it into the URL.
$('.typeahead').typeahead({
source: function(typeahead, query) {
var source = $(this).data('source');
return $.ajax({
url: '/ajax_lookup_directory/'+source+'.php?q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
You can try the following
$('.typeahead').typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_directory/' + $(this).attr('id') + '.php?q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});

Using Ajax callback variable values in JQuery dynamic click handlers

I'm doing a simple ajax query which retrieves a variable-length list of values as JSON data. I'm trying to make a list based on this data which has click-functions based on the values I got from the JSON query. I can make this work just fine by writing the onClick-methods into the HTML like this:
function loadFooList() {
var list_area = $("#sidebar");
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' onClick='alert(\"" +
link_id + "\");'>" +
item.name + "</a></li>");
});
list_area.html(list_area.html() + "</ul>");
}
});
}
I don't like writing the onClick-function into the HTML and I also want to learn how to create this same functionality via JQuery click-function.
So the problem is obviously variable-scoping. My naive attempt here obviously won't work because the variables are no longer there when the click happens:
function loadFooList2() {
var list_area = $("#sidebar");
var link_ids = Array();
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' id='" + link_id + "'>"+item.name+"</a></li>");
link_ids.push(link_id);
});
list_area.html(list_area.html() + "</ul>");
for (link_index=0; link_index<link_ids.length; link_index++) {
$("#" + link_ids[link_index]).click(function() {
alert(link_ids[i]);
});
}
}
});
}
Obviously I'd like to do something else than just alert the value, but the alert-call is there as long as I can get that working and move forward.
I understand that I'll have to make some kind of handler-function to which I pass a state-variable. This works for a single value (I can store the whole link_ids array just fine, but then I don't know which of them is the right value for this link), but how would I do this for arbitrary-length lists?
Here is an example from JQuery docs which I'm trying to copy:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
function handler(data) {
//...
}
// add click handler and pass foobar!
$('a').click(function(){
handler(foobar);
});
// if you need the context of the original handler, use apply:
$('a').click(function(){
handler.apply(this, [foobar]);
});
And I quess the last example here, "if you need the context of the original handler..." would probably be what I want but I don't know exactly how to get there. I tried to store the current link_id value into this, use it from this in the applied function (using apply()) but I didn't succeed. The necessary values were still undefined according to FireFox. I'm using JQuery 1.3.2.
So what's the right solution for this relatively basic problem?
Use append instead of html():
function loadFooList() {
var ul = $('<ul>');
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
var a = $('<a>').attr('href','#').bind('click', function(e) {
alert(link_id,item_name);
e.preventDefault();
});
$('<li>').append(a).appendTo(ul);
});
ul.appendTo('#sidebar'); // this is where the DOM injection happens
}
});
}
So the problem appears to be getting the link id associated with the link so that your click handler has access to it. Note that if it's alphanumeric it will qualify for the id attribute and you can extract it from there. If it is purely numeric, it will be an illegal id attribute. In that case, you can either use an attribute, like rel, or the jQuery.data() method to store the link id with the link. You can also simplify by using append. I'll show both examples.
var link = $("<li><a href='#' id='" + link_id + "'>" + item.name + "</a></li>";
link.click( function() {
alert( $(this).attr('id') );
});
list_area.append(link);
or (if numeric)
var link = $("<li><a href='#'>" + item.name + "</a></li>";
link.data('identifier', link_id )
.click( function() {
alert( $(this).data('identifier') );
});
list_area.append(link);
Try this:
function loadFooList() {
var list_area = $("#sidebar");
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
var out = '<ul>';
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
out +="<li><a href='#' id='" + link_id + "'>"+item.name+"</a></li>";
});
out +="</ul>"
var $out = $(out);
$out.find('a').click(function(){
var link_id = this.id;
var item_name = $(this).text();
alert(link_id);
alert(link_name);
})
list_area.html($out);
}
});
}
Using multiple appends causing the browser to redraw multiple times in a row. You only want to modify the dom once.

Categories

Resources