Is there such a thing as listBox1_SelectedIndexChanged but in PHP ?
Nope, but you could use jQuery :)
$(document).ready(function() {
$("#selectList").change(function() {
var myVal = $(this).val();
alert(myVal);
});
});
If you need to send data to server and get back from it, use $.post() / $ajax() etc ...
Related
I've been trying to achieve the following:
Call my action (which returns json):
#{ var response = Html.Action("Login", "Auth"); }
And assign my json response to a global javascript variable:
<script type="text/javascript">
var response = #response;
user = response.details;
</script>
However I can't seem to get this to work the way I need it to. The response is not assigned appropriately. Is there an action call which returns json? I know I could use ajax for this, but that's not a valid option since i have to set the global variable before the document.ready is called.
Any tips appreciated...
Kind regards
You can use JavaScriptResult directly. See MSDN Doc
public JavaScriptResult Example()
{
return new JavaScript("var response = 10");
}
Useful liks related to
How to use Asp.net mvc JavaScriptResult practically
Working example for JavaScriptResult in asp.net mvc
Beware of ASP.NET MVC JavaScriptResult
But I would suggest you to Use $.getJSON() or $.Ajax() instead
Use $.getJSON(), $.post(), $.Ajax() instead, if you want JSON response back
Instead of trying to use Html.Action like a method call, use Html.RenderAction and use that action to dump any necessary JavaScript to your page. e.g.
AuthController.cs
public class Auth : Controller
{
/* snip */
[ChildActionOnly]
public ActionResult Login()
{
return View(/* model? */);
}
}
~/Views/Auth/Login.cs
<script>
var auth = #whateverinformation;
</script>
Original View
#{ Html.RenderAction("Login", "Auth"); }
<script>
user = auth.details;
</script>
Now /Auth/Login can be placed on any page and the content is included at a server level (instead of supplementary with AJAX)
And if that doesn't do it for you, think about making an HTML helper that displays the information instead of trying to use a controller action like a normal method. Something like:
public static IHtmlString Auth_Login(Htmlhelper htmlhelper)
{
String response;
/* assign response */
return new HtmlString(response); /* or maybe MvcHtmlString */
}
Implemented:
<script>
var response = #Html.Auth_Login();
user = response.details;
</script>
You may check the Channel9 discussion on Evolving Practices in Using jQuery and Ajax in ASPNET MVC Applications.
You may also check the SO question on asp.net MVC3 and jquery AJAX tutorial
You should use quotes
<script type="text/javascript">
var response = "#response";
...
I am not an expert in jQuery and I am trying to pass some variable values from C# to my function called on keyup and onclick events. So far I have something like this:
$('mydiv').bind('keyup click', function(event) {}
but what I need should be:
$('mydiv').bind('keyup click', function(event, UserId, ControlId) {}
, where UserId and ControlId are some ids I am getting in code behind from the query string. I am also using jQuery 1.6.4.
How can I do this, preferably without using hidden input fields?
Thank you.
Use on instead of bind
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
Passing values from the server to the client with razor (if youre using asp.net mvc):
$('mydiv').on('keyup click', function(event, #UserId, #ControlId) {}
or if its webforms:
$('mydiv')
.on('keyup click', function(event, <%= UserId %>, <%= ControllId %>) {}
I would use data-attributes:
$('mydiv').data({ userId: <%= UserId %>, ControllId: <%= ControllId %> })
then you can access those data in the on click event:
$('mydiv').on('click', function(event) {
var userId = $(this).data('userId');
var ControlId = $(this).data('ControlId');
});
declare the variable as public in code behind
public string userId="abc";
Access it on client side
var uid='<%=userId %>';
$('mydiv').bind('keyup click', function(event, uid, ControlId) {}
A js file cannot directly access C# objects so you need to do something like below.
Even if you want to write complete jQuery code in your view file, you can still follow same approach.
So you can pass variables in some Model which is passed to View and once you have those variables in Model you can do something like below:
<script type="text/javascript">
var myList= #Html.Raw(Json.Encode(#Model.UsersList));
</script>
So now you have a json object which can be accessed by any individual js file as well with in same view file with the help of variable "myList".
Javascript scopes are not like scopes in other languages
so if you write
var UserId = 5;
var ControlId = 5;
$('mydiv').bind('keyup click', function(event)
{
alert( UserId );
});
it will work
check out http://jsfiddle.net/FgYTL/1/
Is my mydiv a class, id or a jQuery variable? Looks like you need to do
$('div.mydiv') or $('div#mydiv')
I have a link like that. It's getting from instagram api.
http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b
How can I get this link from codebehind?
I can take it with js but i can't get it after assign to label. I mean:
<script>
function getURL(){
document.getElementById('lblAccessToken').innerText = location.href;
}
</script>
This js function is in body onload event. How can I reach this innerText value from codebehind?
If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this
Markup
<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token");
$("#lblAccessToken").html( myToken );
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things
Pass the hash value to a jQuery ajax method and store it there.
Grab the hash value and redirect to the same page after converting it to a querystring
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token") || "";
if(my_token !=== ""){
window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
}
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Now at Page_Load, grab it like
string token = Request.QueryString["access_token"];
Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.
How can i check in for a value in DB on blur event through jQuery.
I want to display a message if value exist in Data base.
I am using Asp.Net with csharp.
you can call C# function from your jQuery function like --
var isExist = <%=GetValueFromDB()%>;
GetValueFromDB in the codebehind should return a string result and you can check it in your jQuery. I hope this helps.
public string GetValueFromDB()
{
if(value is there)
return "your result";
return "emptystring";
}
Jquery runs on client, so you need to go to the server.
Ajax that calls a WebMethod might work for you
Do a webmethod and then do something along
$('#myInput').onblur(function()
{
$.get('myurl.aspx', {method : 'checkValue', mvalue : $(this).val()},function(data)
{
//handle your response
});
});
I am using ASP.NET 3.5.
In my code behind i have this code that i want to execute from my JavaScript.
Private Sub CreateName()
Dim Name as String
Name = txtName.text
End Sub
And this is my JavaScript Function
<script type="text/javascript">
function doSomething() {
document.elqFormName.action = 'http://now.eloqua.com/e/f2.aspx'
document.elqFormName.submit();
}
</script>
So what must I place inside my JavaScript function to execute my function in my code behind?
Thanks in advance!!
I'm not sure how VB works, but it's similar to C#. I've previously done this by making a WebMethod and using ajax.
Although you could do this using WebMethods as Jimmeh stated, another option would be to use a HTML generic handler. In this approach, your CreateName method wouldn't be in a ASPX page but in a ASHX page.
Check:
http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx
Inside your doSomething method in the javascript part you'd need to call the ASHX using Ajax.
Check:
http://docs.jquery.com/Ajax
I had this same issue, and I found the easiest way to handle it was with an AJAX call. In your ASPX page (javascript):
//======================================
/* This function creates a new instance of an XMLHttpRequest object,
based on the users browser, and returns it */
//======================================
var xmlhttp
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
//======================================
/* This function issues a request and specifies which function should handle the ajax response */
//======================================
function doSomething()
{
xmlhttp = GetXmlHttpObject();
xmlhttp.onreadystatechange=stateChanged;
var url = "CreateName.aspx"
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
}
//======================================
/* This function handles the ajax response text, places it in a label */
//======================================
function stateChanged()
{
if (xmlhttp.readyState==4)
{
var returned = xmlhttp.responseText;
document.getElementById("lbl_returnStatus").innerHTML = returned;
}
}
And then in the file CreateName.aspx:
<%
'Here is where you can do anything on the server side
Dim Name as String
Name = txtName.text
'This is what will be passed back and handled by the stateChanged function
Response.Write("Success!")
%>
You can also pass parameters through an AJAX call if you need to. Since the type of request we are making is a GET, you can just add the parameters to the URL in Javascript and access them server side with the Request.Querystring("paramName") function.
I wrote a more detailed post on starting AJAX on my blog, here, if you'd like to read that as well. Cheers!