What is the best way to send values from JavaScript (client-side) to the server (asp.net) without refreshing the page?
I want to insert the data into a database but I don't want to refresh the page or change any data on it.
Simple way :
1- Import jquery into your page
2- create ur function in the cs file of the page like this
[WebMethod]
public static string Save(string param1,string param2)
{
string result;
//your code must return somthing string
return result;
}
3- in your aspx page create your function
function save(){
var param1 = 'value 1 you need to send to the server should be string';
var param2 = 'value 2 you need to send to the server should be string';
$.ajax({
type: "POST",
url: "pagename.aspx/Save",
data: "{param1: '"+ param1 +"' , param2 :'"+ param2 +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function(result){
//Successfully gone to the server and returned with the string result of the server side function do what you want with the result
}
,error(er)
{
//Faild to go to the server alert(er.responseText)
}
});
}
4- Call this function on the button click
for more questions or descriptions of my code and script i'm here :)
An easy way is to use a page method or static methods on a page and use jquery to send or get data from the server side code. This link has a good walkthrough
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Ypu have to use Ajax techniques, JQuery, Asp.net, YUI, and the rest of api and libraries that let you use Ajax techniques.
The easiest one in Asp.net is using builtin Asp.net Ajax functionalities by adding a ScriptManager and UpdatePanel to your page
The technique is called Ajax and there are no shortage of tutorials and libraries (not to mention support in the big libraries such as YUI or jQuery).
No one actually answered this question. As, "Import jquery" "use ajax" etc. all negate the fact that the OP asked for a javascript solution. This is a one-liner in javascript / very easy to do.
In your javascript you just call the method:
PageMethods.SomeMethod('test');
Your "SomeMethod" would be a code behind method like this:
[WebMethod]
public static string SomeMethod(string param1)
{
string result = "The test worked!";
return result;
}
Rules:
You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:
<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />
Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.
Related
So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.
is there an easy way to use the g:message functionality in a dynamic way in Javascript, e.g.
function get_i18n( myAttr ) {
return "${message(code:'" + myAttr + "')} ";
}
so that I can perform the function call
pl_get_i18n( "xyz" )
for the predefined i18 attribute xzy ?
Like here, but dynamic: https://stackoverflow.com/a/8296812/1779814
PS: The JS code is included in the GSP file.
The short answer is "no". GSP tags can only be executed on the server-side, not by the browser (i.e. JavaScript).
However, I would expect there is at least one Grails plugin that does the following:
creates a JavaScript object containing the messages defined in your messages*.properties file(s)
provides a JavaScript function that enables you to resolve messages from this object
So although it's not possible to execute GSP tags in the browser, it doesn't seem terribly difficult to provide equivalent functionality in JavaScript. I would be amazed if there isn't already a Grails plugin that does this.
Here is a very simplistic example of how you can use AJAX to fetch a message code from the server.
// AjaxMessageController.groovy
package example
import grails.converters.JSON
class AjaxMessageController {
def index() {
render [message: message(code: param.code)] as JSON
}
}
Then within your page you can just use an ajax call (jQuery based) in this example to look up a message code:
var someMessageCode = 'something.you.want';
$.ajax({
dataType: 'json',
url: '${createLinK(controller: "ajaxMessage", action: "index"}',
data: {code: someMessageCode},
success: function(data) {
window.alert(data.message);
}
});
My app is using the play framework mvc setup. In the controller I am passing a parameter while rendering the template, like this:
public static void scenario(){
...
render(active_brands);
}
Now in my HTML page "scenario.html", I can access the parameter using the play framework tags like this:
#{list items:active_brands, as:'c'}
...
#{\list}
Or using JQuery inside an HTML table like this:
<td>${active_brands.get(1)}</td>
Just for reference, the passed in parameter is a List.
However, I am trying to access the parameter "active_brands" from a javascript function and I am not sure how to do that.
I thought using Jquery to access the variable would work and I tried to access the variable like this:
function update_brands(active_scenario_ids){
...
alert('Reached: '+ ${active_brands});
}
but that does not work. It seems to me that the HTML attribute is out of scope for the javascript function. Is that true?
It would be great if someone can help me with this. Thanks.
This works for me using Play 2.2.0:
Application.scala (controller):
def index = Action { implicit request =>
val message = "This is a test."
Ok(views.html.test(message))
}
test.scala.html (view template):
#(message: String)
<script type="text/javascript">
$(document).ready(function(){
console.log("#message");
});
</script>
Console output:
This is a test.
The root of the problem was that my template variable, which is accessible in client side HTML, was of type java.util.List, which is not accessible by client side code ie. javascript. However, it is recognized in the play tags because play tags are server side code written in client side. So the only solution I could find for reading Objects inside java collections is returning a JSON object.
Therefore I had to change my code such that instead of returning a Java List as a template variable, I retrieve the data as a JSON object through an ajax call.
$.ajax({
url: '/getBrands/',
type: 'POST',
data: {active_scenario_ids: active_scenario_ids},
dataType: "json",
success: function(data){
console.log(data);
},
error: function(req, status, error){
alert("R:"+req+"S:"+status+"E:"+error);
}
});
}
I'd like to create my own JS widget, which it must be dinamic.
I mean, for example, the html generated from the downloaded script :
<script src="www.mywebsite.it/widget/?ID=2&Category=4" type="text/javascript"></script>
must be different from :
<script src="www.mywebsite.it/widget/?ID=1&Category=5" type="text/javascript"></script>
and the Data into HTML should be taken from Database, on my server. So, I need to call an aspx page that create javascript that will create html? Or which could be the solution?
The better way is to use generic handler with .ashx, if you want retrieve data from server and send data in JSON or XML.
Next, the data will be inserted in page with javascript.
So, if I understand well, you do generate an .aspx that contains your template and a javascript that hold the code to navigate in Category as this if you use JQuery :
$.ajax({
url: 'data.ashx?ID=2&Category=5',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Server behind (ashx) :
private readonly JavaScriptSerializer _js = new JavaScriptSerializer();
public void ProcessRequest(HttpContext context)
{
//Do logic and retrieve data here
Categorys c = GetFooById(context.Request["id"]);
context.Response.Write(_js.Serialize(c));
context.Response.ContentType = "application/json";
}
It seems that you'd want to use AJAX.
The script source shouldn't be dynamic (it can't be cached if it is), but the script itself could call whatever page you like to pull back data (say in JSON format) or raw markup to place in a pre-defined element.
Don't use the ASPX page to create javascript if you can help it.
Consider using a JavaScript library such as jQuery to help you.
simply, i have an ASP.net Textbox inside a webcontrol
it gets filled by a javascript function inside the same markup of the webcontrol
the problem is that i need to read that value from the serverside events of the webcontrol
tried page_load, page_unload... but they all fire before the javascript function is executed.
i even tried to move the JS code to a seperate Script file, and added a reference to it.
but again its just the same.
when i try to call that function to fill the textbox, using:
Page.ClientScript.RegisterClientScriptBlock //which calls it to early
Page.ClientScript.RegisterStartupScript //which calls it too late ;P
but again it's executed before the Script reference is included in the render of the control.
any suggestions except of Registering all the JS code using registerClientScriptBlock?
im sure im missing something important related to the life cycle of the web control, so please enlighten me and sorry for the long blablabla.
thanks in advance
As Tim implied, this is probably better done on the server, prior to output.
However, to answer your question, you could create a webservice which the client could call to notify the backend of the calculated value. Here's a very rough example:
NewWebService.asmx:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void SaveTextBox(string textValue)
{
<%-- Save the value here --%>
}
YourPage.html:
// Requires jQuery.
// Code can be refactored to use any library or none at all, if you like
<script>
$("#textBoxId").change(function() {
var textValue = this.value;
$.ajax({
type: "POST",
url: "NewWebSerivce.asmx/SaveTextBox",
data: textValue,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do nothing
}
});
});
</script>