Using a value from a dropdown list in a handler - javascript

I could really use some help if anyone can spare some time. I am trying to access the value of a dropdownlist (dropdownlist1) on the master page from my content page and then use the variable in a hanlder in a .ashx code page. To test it I was trying to display the varialble in a message box. Any ideas would be appreciated.
Content Page (dropdownlist is on master page)
$(document).ready(function $("#DropDownList1").change(function () {
location.reload;
alert($(this).val());
strTrail = $(this).val();
alert(strTrail);
});
Handler
Case "SearchByLocation"
Dim firstTime As Integer = 0
Dim latitude As String = "42.9901009" 'context.Request("Latitude")
Dim longitude As String = "-81.146698" 'context.Request("Longitude")
'Dim fromdate As String = context.Request("#DropDownList1").val
Dim strTrail As String = context.Request("#DropDownList1")
MsgBox("now")
MsgBox(strTrail)
'strTrail = context.Request("strTrail")
If firstTime < 1 Then
strTrail = "Lookout"
End If
Dim objCBL As New JParkinsonLookUP.JPLookUp
Dim objDS As System.Data.DataSet = objCBL.SearchByTrail(strTrail, latitude, longitude, 10)
'result = "{""Locations"":[{""ID"":""1"",""Latitude"":""28.537"",""Longitude"":""-81.380""}]}"
result = "{""Locations"":["
For Each dr As System.Data.DataRow In objDS.Tables(0).Rows
result += "{""ID"":""" & dr("ID").ToString() & """,""Latitude"":""" & dr("Latitude").ToString() & """,""Longitude"":""" & dr("Longitude").ToString() & """},"
Next
result = result.Substring(0, result.LastIndexOf(","))
result += "]}"
firstTime = 1
Case "SearchByDescription"
End Select
'second command
'third command
context.Response.Write(result)
End Sub

firt of all avoid msgbox coz it will throw in exception (not valid in an aspnet page contest)
Second one when you will go through document.ready you will have to make a ajax request as per your code you will return json object then you need to parse within javascript the object ad read value from it.
$.ajax(
{
type: "GET", url: url, data: qry,
success: function (msg) {
lat = msg.Locations[0].Latitude;
lng = msg.Locations[0].Longitude;
alert(lat +' ' + lat);
},
error: function (msg) {
$("#coor").html("errore durante l'elaborazione");
}
});
Another important stuff use this directive to set your response:
context.Response.ContentType = "application/json";
Take care to check via Chrome or Firefox your response and call via network call so you will able to have more info.
this is code is not test i use some working code at my end and make some changes to let you an idea.

Related

Pass parameters without using QueryString

I have an MVC application. On one page I have a partial view that displays a bootstrap-table. I have some javascript code that is triggered when a table row is double clicked. This code retrieves some values from the double clicked row and constructs a url then navigates to that url.
This works fine but the way I have created the url means that I have data visible as querystrings in the url. How can I achieve navigating without using querystrings. Oh and I need the navigation to a new window/tab if possible.
My javascript code for the double click is:
$mTable.on('dbl-click-row.bs.table', function (e, row, $element) {
var cod = $('#hdCOD').val();
var mv = mGetSelectedRow().CMonth;
var yv = mGetSelectedRow().CYear;
var diff_cv = moment.utc(cod).diff(moment.utc(yv + '-' + pad(mv, 2) + '-' + '24'), 'months', true);
var plcf = '';
switch(true) {
case (diff_cv >= 2):
plcf = 'past';
break;
case (diff_cv >= 1 && diff_cv < 2):
plcf = 'last';
break;
case (diff_cv >= 0 && diff_cv < 1):
plcf = 'current';
break;
case (diff_cv < 0):
plcf = 'future';
}
var url = 'ClaimMonth/ViewMonth?pn=' + mGetSelectedRow().Cpid + '&cm=' + mv + '&cy=' + yv + '&mt=' + plcf + '&cod=' + cod;
window.open(url, '_blank');
})
The partial view is called using razor syntax:
Html.RenderAction("GetSummaryForAdmin", New With {Key .pn = Model.PersonelNo})
I can't seem to find an equivalent function in javaScript that mimics the New With {Key .pn = Model.PersonelNo} I'm also unsure if this is the way to do this. I've thought about ajax call but I don't think I can make this open as a new window/tab.
Any help appreciated.
UPDATE
I've found the following ajax.post method that gives me the document I want... In Developer Tools (F12 in Chrome/IE) using the network tab I can see the call for the document and if I preview it, it displays the data. But the page is not displayed in the browser.
Opening in a new window/tab is not a requirement but would be nice to have.
My new code replaces...
//var url = 'ClaimMonth/ViewMonth?pn=' + mGetSelectedRow().Cpid + '&cm=' + mv + '&cy=' + yv + '&mt=' + plcf + '&cod=' + cod;
//window.open(url, '_blank');
with...
$.ajax({
type : "post",
url : "ClaimMonth/ViewMonth",
data : {pn: mGetSelectedRow().Cpid, cm: mv, cy: yv, mt: plcf, cod: cod },
success : function(response) {
window.open();
},
error : function(xhr) {
console.log("error"+xhr.status);
},
complete : function() {
}
});
and I changed my controller function to accept parameters instead of reading request.querystring
You will have to use a combination of postback and Session.
AJAX Post (as you have already) to send values back to the server.
In the MVC action method which handles that postback, save the values to Session:
Public Function ViewMonth(...) As JsonResult
Session("SavedMonth") = New MonthObj(pn, cm, cy, mt, cod)
Return Json(True)
End Function
When the AJAX Post returns successfully, open a new window with a different URL:
success : function(response) {
window.open('/ClaimMonth/AfterSave');
},
The MVC action method for that URL loads the saved data from session, then displays it.
Public Function AfterSave() As ViewResult
Dim model As MonthObj = TryCast(Session("SavedMonth"), ModelObj)
Return View(model)
End Function

Authenticating with Last.fm in Jquery - Invalid method signature supplied

I'm trying to auth a Last.fm session and am struggling to sign a request for a session key correctly.
I keep receiving Invalid method signature supplied However when I md5 hash what i believe the query should consist of outside of JS, I get the same signature. I must be including the wrong data in the string I guess, but can't figure out what.
I know there are a few other questions and i've ran through them all to see what's going wrong here, but I swear it looks right to me.
This is the signing algorithm and Ajax call. I've tried to leave enough sample data too.
// Set elsewhere but hacked into this example:
var last_fm_data = {
'last_token':'TOKEN876234876',
'user': 'bob',
'secret': 'SECRET348264386'
};
// Kick it off.
last_fm_call('auth.getSession', {'token': last_fm_data['last_token']});
// Low level API call, purely builds a POSTable object and calls it.
function last_fm_call(method, data){
// param data - dictionary.
last_fm_data[method] = false;
// Somewhere to put the result after callback.
// Append some static variables
data['api_key'] = "APIKEY1323454";
data['format'] = 'json';
data['method'] = method;
post_data = last_fm_sign(data);
$.ajax({
type: "post",
url: last_url,
data: post_data,
success: function(res){
last_fm_data[method] = res;
console.log(res['key'])// Should return session key.
},
dataType: 'json'
});
}
function last_fm_sign(params){
ss = "";
st = [];
so = {};
Object.keys(params).forEach(function(key){
st.push(key); // Get list of object keys
});
st.sort(); // Alphabetise it
st.forEach(function(std){
ss = ss + std + params[std]; // build string
so[std] = params[std]; // return object in exact same order JIC
});
// console.log(ss + last_fm_data['secret']);
// api_keyAPIKEY1323454formatjsonmethodauth.getSessiontokenTOKEN876234876SECRET348264386
hashed_sec = unescape(encodeURIComponent($.md5(ss + last_fm_data['secret'])));
so['signature'] = hashed_sec; // Correct when calculated elsewhere.
return so; // Returns signed POSTable object
}
Anything anyone can see that i'm missing here? I'm absolutely stumped why this isn't returning a correctly signed POSTable object in the format requested here. Thanks for your time.
Edit: can't thank anyone for their time if i don't get any advice! No one had any experience with last.fm?
After investigating your code and other posts related to last.fm api call, I found that #george lee in fact is correct. You don't need to provide format while generating the auth_sign.
Apart from that you need to apply $.md5() to auth_sign string after applying encodeURIComponent() and unescape() functions. Like this.
hashed_sec = $.md5(unescape(encodeURIComponent(ss + last_fm_data['secret'])));
Also while making ajax call you need to pass api_key, token & api_sig as data. But seeing your code, reveals that you are passing api_key, token, format, method & signature.
So you need to remove format, method & signature from the data field of ajax call.
Instead you need to pass api_key, token & api_sig to the data field.
So the final code after commenting the data['format'] = 'json'; line will look like this.
// Set elsewhere but hacked into this example:
var last_fm_data = {
'last_token':'TOKEN876234876',
'user': 'bob',
'secret': 'SECRET348264386'
};
// Kick it off.
last_fm_call('auth.getSession', {'token': last_fm_data['last_token']});
// Low level API call, purely builds a POSTable object and calls it.
function last_fm_call(method, data){
// param data - dictionary.
last_fm_data[method] = false;
// Somewhere to put the result after callback.
// Append some static variables
data['api_key'] = "APIKEY1323454";
//data['format'] = 'json';
data['method'] = method;
post_data = last_fm_sign(data);
$.ajax({
type: "POST",
url: last_url,
data: post_data,
success: function(res){
last_fm_data[method] = res;
console.log(res['key'])// Should return session key.
},
dataType: 'json'
});
}
function last_fm_sign(params){
ss = "";
st = [];
so = {};
so['api_key'] = params['api_key'];
so['token'] = params['token'];
Object.keys(params).forEach(function(key){
st.push(key); // Get list of object keys
});
st.sort(); // Alphabetise it
st.forEach(function(std){
ss = ss + std + params[std]; // build string
});
ss += last_fm_data['secret'];
// console.log(ss + last_fm_data['secret']);
// api_keyAPIKEY1323454formatjsonmethodauth.getSessiontokenTOKEN876234876SECRET348264386
hashed_sec = $.md5(unescape(encodeURIComponent(ss)));
so['api_sig'] = hashed_sec; // Correct when calculated elsewhere.
return so; // Returns signed POSTable object
}
Please refer to this link.
So on testing some of the responses, I found the solution. There were 2 issues.
EDITED see below (
The first was needing to remove
data['format'] = 'json';
as George Lee pointed out. Thanks George.
)
The other issue was that I'd named a variable incorrectly so was being POSTed with the wrong name. The line
so['signature'] = hashed_sec;
should have been
so['api_sig'] = hashed_sec;
I noticed this in Pankaj's answer but unfortunately the rest of his answer (i.e. including the method) was incorrect. Making these 2 changes resolved the call and signed it correctly.
Thanks for all the suggestions!
EDIT:
After some more playing, i've found that
data['format'] = 'json';
IS correct, however it DOESN'T get hashed with the signature.
Adding data['format'] = 'json'; to the POST object after hashing works, and in this instance will return JSON as opposed to XML - which was the preferred method. Adding after hashing is not documented anywhere that I can find, so there you go.
The new working code is as follows, and this shows the 2 lines indicated with --------------------
// Set elsewhere but hacked into this example:
var last_fm_data = {
'last_token':'TOKEN876234876',
'user': 'bob',
'secret': 'SECRET348264386'
};
// Kick it off.
last_fm_call('auth.getSession', {'token': last_fm_data['last_token']});
// Low level API call, purely builds a POSTable object and calls it.
function last_fm_call(method, data){
// param data - dictionary.
last_fm_data[method] = false;
// Somewhere to put the result after callback.
// Append some static variables
data['api_key'] = "APIKEY1323454";
data['method'] = method;
post_data = last_fm_sign(data);
// THEN ADD THE FORMAT ---------------------------------------
post_data['format'] = 'json';
$.ajax({
type: "post",
url: last_url,
data: post_data,
success: function(res){
last_fm_data[method] = res;
console.log(res['key'])// Should return session key.
},
dataType: 'json'
});
}
function last_fm_sign(params){
ss = "";
st = [];
so = {};
Object.keys(params).forEach(function(key){
st.push(key); // Get list of object keys
});
st.sort(); // Alphabetise it
st.forEach(function(std){
ss = ss + std + params[std]; // build string
so[std] = params[std]; // return object in exact same order JIC
});
// console.log(ss + last_fm_data['secret']);
// api_keyAPIKEY1323454formatjsonmethodauth.getSessiontokenTOKEN876234876SECRET348264386
hashed_sec = unescape(encodeURIComponent($.md5(ss + last_fm_data['secret'])));
so['api_sig'] = hashed_sec; // RENAMED THIS ----------------------------
return so; // Returns signed POSTable object
}

How to pass the value to URL from dropdown item?

I am asking this question again....because I am not getting correct answer...
answers which I get is incorrect.
I am developing MVC application and I am using razor syntax. I am trying to get the selected item from dropdown list value and to pass it to the controller method.
but I am getting error.
$("#btnForword").click(function(){
d = document.getElementById("HODList").value;
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "d" }))";
url2 = url2.replace("idValue",'#Model.Id');
url2 = url2.replace("d",'#d');
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
I think error in this line...
url2 = url2.replace("d",'#d');
Issue solved Issue solved
The problem in variable 'D' yes in "D".
I checked using inspect element property of Google chrome, when I saw it in console window....
When I click on the button , I can see the string formed in below way
http://localhost:54255/PaymentAdvice/SendPaymentAdviceForApproval?paymentAdviceId=304&nHO8=D
jquery-1.7.1.min.js:4
see the last character in the above link, it should not be come as a "=D" isnt it ?
I used the below code...and it works perfectly.
$("#btnForword").click(function(){
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "HODId" }))";
url2 = url2.replace("idValue",'#Model.Id');
url2 = url2.replace("HODId",$('#HODList').val());
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
Is this a bug in Jquery ?
Your variable d is not a server variable that can be called with "#" but a client variable set in javascript, so it should be user like :
$("#btnForword").click(function(){
d = document.getElementById("HODList").value;
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = Model.Id , nHOD = "d" }))";
url2 = url2.replace("d",d);
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
(and the "#Model.Id" can be called directly in the Url.Action method).
Yes it is. The problem is that the js replace function replaces every "d" character contained in the url2 string with your #d variable!!!
You need to replace the "d" identifier with something that does not appear twice (or more) in the url string. Besides, I think is better if you create the url directly using javascript and not the Razor helper. You can do this in one line of code instead of three. Regards.

fetch json object containing 3 arrays with ajax call and pass arrays to javascript

I have a page that creates the following output:
<script>
var JSONObject = { "groups":['1210103','1210103','1210103','1210405'],
"prices":['279,00','399,00','628,00','129,00'],
"titles":['','','','']
};
</script>
This page is called by an ajax call:
$.ajax({url:plink,success: function(result) { }
I now need to recieve the json arrays and pass them to ordinary javascript arrays.
How do I do that?
I have tried with:
result = jQuery.parseJSON(data);
mygroups = result.groups;
myprices = result.prices;
mylabels = result.titles;
Change your page so that it just produces JSON:
{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}
Note that in JSON, you must use ", not ', for quoting strings.
Have it return a Content-Type header of application/json. If for some reason you can't set the correct Content-Type header on the response, you can force jQuery to treat the response as JSON by adding dataType: 'json' to your ajax call, but it's best to use the correct content-Type.
Then in your ajax call's success callback, result will already be a deserialized object with three properties (groups, prices, titles), which will be JavaScript arrays you can work with.
Live Example | Source
You've said in the comments below that the page is a full HTML page with the embedded script tag and you have no control over it other than the contents of the script tag, because of the CMS you're using.
I strongly suggest moving to a more flexible CMS.
Until/unless you can do that, you can simply receive the page as text and then extract the JSON. Change your script tag to something like this:
<script>
var JSONObject = /*XXX_JSONSTART_XXX*/{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}/*XXX_JSONEND_XXX*/;
</script>
Note the markers. Then you can extract the JSON between the markers, and use $.parseJSON on it. Example:
(function($) {
$.ajax({
url: "http://jsbin.com/ecolok/1",
dataType: "text",
success: function(result) {
var startMarker = "/*XXX_JSONSTART_XXX*/";
var endMarker = "/*XXX_JSONEND_XXX*/";
var start, end;
start = result.indexOf(startMarker);
if (start === -1) {
display("Start marker missing");
}
else {
start += startMarker.length;
end = result.indexOf(endMarker, start);
if (end === -1) {
display("End marker missing");
}
else {
result = $.parseJSON(result.substring(start, end));
display("result.groups.length = " + result.groups.length);
display("result.prices.length = " + result.prices.length);
display("result.titles.length = " + result.titles.length);
}
}
}
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
Live Copy | Source

jquery autocomplete to fill a javascript array?

I wanted to add autocomplete to a text box I had on my form. I found an excellent SO thread that entailed this right here: https://stackoverflow.com/a/5973017/168703 This was exactly what I needed because it also only showed the autocomplete when someone typed an # symbol.
It was something to the effect of this:
$("#ucAddActionItemIssueActions_txtActionItem")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: 0,
source: function(request, response) {
var term = request.term,
results = [];
if (term.indexOf("#") >= 0) {
term = extractLast(request.term);
if (term.length > 0) {
results = $.ui.autocomplete.filter(
availableTags, term);
} else {
results = ['Start typing...'];
}
}
response(results);
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
var email = GetEmail(ui.item.value);
email = email + ";";
emails.push(email);
$("#ucAddActionItemIssueActions_hdnEmails").val(emails.join(""));
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
return false;
}
});
Pay close attention to the source portion as it forced me to declare something like this:
var availableTags = [
"jdoe",
"tsmith",
"mrighty",
"tstevens",
"ktripp",
"tram",
];
That is my autocomplete suggestions would be inside of the js file...but this is the only part I did not want. I have to load the data from a database. Unfortunately I am dealing with an ancient .net framework prolly pre 2.0 app. Its vb.net and there is no linq or lists or all the good stuff. Fine I thought..I could probably create a .asmx file that added strings to an array list, converted it back to a string array and returned it in the .asmx file. Something to this effect (this was just a test no pulling data just yet from a database):
Imports System.Web.Services
Imports System.Collections
<System.Web.Services.WebService(Namespace := "http://tempuri.org/myapp.com/GetLogins")> _
Public Class GetLogins
Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
Public Sub New()
MyBase.New()
'This call is required by the Web Services Designer.
InitializeComponent()
'Add your own initialization code after the InitializeComponent() call
End Sub
'Required by the Web Services Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Web Services Designer
'It can be modified using the Web Services Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
components = New System.ComponentModel.Container()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
'CODEGEN: This procedure is required by the Web Services Designer
'Do not modify it using the code editor.
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
#End Region
' WEB SERVICE EXAMPLE
' The HelloWorld() example service returns the string Hello World.
' To build, uncomment the following lines then save and build the project.
' To test this web service, ensure that the .asmx file is the start page
' and press F5.
'
'Public Function HelloWorld() As String
' Return "Hello World"
'End Function
<WebMethod()> _
Public Function GetLogins() As String()
Dim myList As ArrayList
myList.Add("jstevens")
myList.Add("jdoe")
Dim arr() As String = CType(myList.ToArray(Type.GetType("System.String")), String())
Return arr
End Function
End Class
As mentioned this was just a test so I'm just adding two items in a string array and returning it. Now I am pretty unsure how to change my jquery code to incorporate this....
I thought I would add something like this:
$.ajax({
url: "GetLogins.asmx/GetLogins",
data: "{ 'resName': '" + request.term + "' }",
datatype: "json",
type= "POST",
contentType: "application/json; charset=utf-8"
})
But I am not sure how to incorporate that in the original jquery as my jquery skills are zilch...
Can anyone help me understand this and put this together so it may actually work. Once I get the test working I can then modify it to pull data from the database. Am I on the right path?
EDIT
Here's what I have
$("#ucAddActionItemIssueActions_txtActionItem")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: 0,
source: function (request, response) {
//get client value
var c = $("#ucAddActionItemIssueActions_ddlClientAssignTo").val();
var params= '{"ClientID":"' + c + '"}';
$.ajax({
url: "GetLogins.asmx/GetLogins",
data: params,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
var email = GetEmail(ui.item.value);
email = email + ";";
emails.push(email);
$("#ucAddActionItemIssueActions_hdnEmails").val(emails.join(""));
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
return false;
}
});
But my app is throwing an internal server error 500. With the following exception:
System.InvalidOperationException: Request format is invalid:
application/json; charset=UTF-8. at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at
System.Web.Services.Protocols.WebServiceHandler.Invoke() at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
Here is my webservice:
Imports System.Web.Services
Imports System.Collections
<System.Web.Services.WebService(Namespace := "http://tempuri.org/quikfix.jakah.com/GetLogins")> _
Public Class GetLogins
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetLogins(ByVal ClientID As Integer) As String()
Dim myList As New ArrayList
myList.Add("jstevens")
myList.Add("jdoe")
myList.Add("smartin")
Dim arr() As String = CType(myList.ToArray(Type.GetType("System.String")), String())
Return arr
End Function
End Class
Again this is an old 1.1 .net application, do I need something in the web config file to represent this .asmx file? The parameters in the web method match the parameters of the ajax call so what could be causing this?
I think the problem here is that web services expect XML or text. JSON won't work.
You can try changing your content-Type (in your ajax call) to text and returning a string instead of a string array from your GetLogins method. That way you can serialize your string array to a JSON string using a JSON converter and return that.

Categories

Resources