I lovely update a document with values(Maps coord) from clienside (under privileges). MongoDB use javascript in some internals functions and for MapReduce but is not clear for me if i can use client side scripts to update my repository with values. I searching to pass values from client side to an updater Db.Repository.Updater(item). It's possible to make this using javascript or need a webservice or a rest function.
Can some expert clarify this point and suggest the way.
Many thanks.
There is http interface in mongodb, so you can send direct update request to mongodb through $.ajax for example, or you can send ajax requests to yours handlers/pages/controllers and use mongo-csharp driver as usual for updates. Make your choise...
Include jquery at page first. In 'Update' button click handler paste code like this(to send ajax request):
$.ajax({
type: "POST",
url: "SomePage.aspx",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
In page(but it seems to me that better to use http hadlers ajax handling):
public void Page_Load(object sender, EventArgs e)
{
var name = HttpContext.Current.Request["name"];
var location = HttpContext.Current.Request["location"];
var item = new Item(){Name = name, Location = location};
//here update or insert your item, do what you want
Db.Repository.Updater(item)
}
Related
I have a situation where I'm required to encrypt data in flight from a JavaScript based application (Chrome Extension popup.html) to an API hosted in a .NET MVC website(C#).
I can run the request as a GET but project requirements make it necessary to encrypt the parameters I'm sending. For example if I was searching for all people named 'John' I need to encrypt 'John' in flight.
My JavaScript application is using jsencrypt and a RSA (public) key provided by the website in other APIs that work quite well to return counts.
If my GET version of the link looks like this:
<span class="person" id="personList">Person: '+ query +'</span>
On the .NET website end, this request is processed into a view that generates a table using a database call. As you can see in my link the results are populated onto a new tab in the browser.
How would you recommend changing it to calling a POST method and getting the same result as a GET?
EDIT
I tried to employ an AJAX function to make the POST but it doesn't like the data element:
event.preventDefault();
$.ajax({
url: repurl + 'Persons/Search',
timeout:30000,
type: "POST",
data: {body: encryptedmsg},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
alert('ok');
}
else
{
alert('some thing went wrong, plz try again');
}
}
});
});```
I have an Inbox with internal messages from my clients. When I click on the list over the name I'm requesting using jQuery $.ajax so:
$.ajax({
url: 'messages/retrieve/' + client_id,
}).done( function(data) {
$('.messages-dialog').html(data);
});
My controller should return a variable with json data? I understand it should dump it on a view and I should treat it there but how to do it if is client side?
I don't know if is better to treat and create the html structure into controller and than just load it in .messages-dialog with jQuery.html();
Sorry I'm a little lost on that issue.
You can use jQuery.ajax() method, as in the example above. Also see the official documentation with examples http://api.jquery.com/jquery.ajax/.
Besides you can use jQuery.get() and jQuery.post() methods depending on how and what you will send. You can use this methods as shown below:
var url = 'messages/retrieve/' + client_id;
$.post( // for example
url,
function( data ) {
$('.messages-dialog').html(data);
});
See official documentation with examples here: http://api.jquery.com/get/, http://api.jquery.com/jQuery.post/.
Server handler should be like as below:
use JsonResponse; // you must specify the exact component (I use this)
/**
* Change message in dialog // for example
*/
public function changeDialogMessageAction(Request $request) {
// request data processing
$response = new JsonResponse();
$response->setData(array(
// new data for returning to client
));
return $response; // your data, which will be handled in callback
}
You shouldn't create HTML structure in the controller. It's bad style! JavaScript has asynchronous event model, and you should use it. Controller must handle / transform data, which were passed by you and then return back. jQuery callback must embed received handled / transformed data in DOM.
I am passing a javscript variable to a java class. I am not sure if this is consider a proper way, if so is my syntax correct and how can i make sure that the variable has passed successfully to my java class?
var key = record.getKey();
$.ajax({
type: "POST",
url: "apps/APP/src/Test.java",
data: {id : key},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
A simple Java Class cannot handle an Ajax request (or any web request for that matter) You should be having a Java Web application/ Dynamic Web Application, either written with vanilla Servlets and JSP or using any frameworks like spring to handle web requests.This application must be deployed on a Servlet Container like Tomcat or Jetty.
This tutorial should get you started as its too broad to be covered in a SO answer. Do get back with a new question if you face any issues.
Updated as per your comment:
Since you have a Dynamic Web Application It should have a Servlet, and as your Ajax request is using POST method, override the doPost() and get the data from request object. Note: Use POST only if you are mutating some data in the backend else use GET.
Please see the below code.
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
request.getParameter("id"); //use the key of the json data you need
}
}
I need to call a JavaScript function that shows a Bootstrap modal. I have the following code:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void execModal(string groupname, int zw) {
//need to generate the data first
StringBuilder sb = new StringBuilder();
Generate gen = new Generate();
sb = gen.generateDeeperTable(zw, groupname);
//insert into my placeholder
//Append the HTML string to Placeholder.
fillPH(sb);
//run javascript function <showModel> to show the modal
}
Here is how I call the execModal method form JS:
<script type="text/javascript>
function callGenDeeperTable(zw, groupname) {
PageMethods.execModal(groupname, zw);
}
</script>
The function execModal is called from a javascript function in the .aspx site.
How can I call the javascript function showModal?
Your execModal method is on the server. You have not specified where you want to invoke (call) it from, but since you've decorated it (added attributes to the method defining it...) as a WebMethod, chances are you're trying to invoke it from a (HTML) page running in a client's browser. To make this call you need a line of communication between the client that wants to run the method, and the server that holds the method. You will also notice that execModal is defined as a static method. That means that when it is invoked it will not have the instance members of the Page class, including things like fillPH (unless fillPH is static). I don't know if you're working with ASP.NET WebForms (trying to make the call from an .aspx page), or this is a service consumed by some application (method resides in an .asmx), or I guess this could even be ASP.NET MVC.
Assuming ASP.NET WebForms
Let's deal with the simplest case since there have been almost no details provided. If we assume that this method, execModal, lives in an .aspx.cs file, and you're trying to call it from the corresponding .aspx page, and this is part of an ASP.NET WebForms application...
You need to initiate the call to execModal. This requires an AJAX call from your client to your server. You can create your own AJAX framework, but there are many open source frameworks available. I will give an example below using jQuery.
You need to do the work on the server statically, or you need to use the HttpCurrent.Context to get the instance of the Page, Session, etc. The Page can be retrieved via the HttpCurrent.Context.Handler as Page.
Once the method finishes on the server, the result (success or failure), and optionally any data you want to return to the client, is sent back to the client's browser. The client portion of the application should be able to process this response with an event handler. The event handler should be associated with the XMLHttpRequest object's onreadystatechange event and process the response when the state changes to 4 (done). Frameworks, like jQuery, take care of this overhead by providing parameters in your AJAX call to specify the success/failure callbacks. Do not confuse the result (sucess/failure) of this communication process with the result of your application's processes (actual work of execModal).
Your client side (success) callback function would then just call your desired js function showModal.
Your client side AJAX call (if you were to use jQuery) would look something like this...
$.ajax({
type: "POST",
url: "Default.aspx/execModal",
data: '{groupname: "' + groupname + '", zw: ' + zw + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
showModal();
},
failure: function(response) {
alert("AJAX request failed");
}
});
This is a very basic example. You might want the server to decide what happens on success, but returning a JSON data, or a string with the name of a js function that can be executed on the client - these are just examples to get your thinking about what is possible.
Edit - account for OP's addition of PageMethods.execModal() to question
You say you're calling your server code from this...
<script type="text/javascript>
function callGenDeeperTable(zw, groupname) {
PageMethods.execModal(groupname, zw);
}
That implies that you're using ASP.NET's ScriptManager with EnablePageMethods=true. Is that correct?
That would inject the script with the PageMethods type, and define functions for each of your WebMethods. So you are using an AJAX framework - the one provided by MS. All that work of making the AJAX call is being hidden from you with PageMethods.execModal(groupname, zw). However, each of the functions generated for you (on the PageMethod object) take additional parameters for OnSuccess and OnFailure callbacks. Here is a SO answer detailing how to use the ScriptManager's PageMethod object.
The signature for any function generated on the PageMethod object corresponding to a WebMethod is...
function foo(param1, param2, param3, etc., OnSuccess, OnFailure)
In your case, you have two parameters being passed to the WebMethod, so after those two parameters you would want to supply callback functions for success and failure. showModal would be your success handler probably...
PageMethods.execModal(groupname, zw, showModal, function() { alert('failed!') });
this is what i did and worked like charm
javascript part
function buyproduct(productId)
{
PageMethods.checkifvalid(productid, OnSuccess);
}
function OnSuccess(response, userContext, methodName)
{
this[response]();
}
function functionToCallAfterwebmethod()
{
alert("Javascript Function called successfully!!");
}
Aspx.cs part
[System.Web.Services.WebMethod]
public static string checkifvalid(int productId)
{
--your any logic to check
-- pass the javascript function as return parameter
return "functionToCallAfterwebmethod"
}
I have the web service:
[WebMethod]
public void SendMail(string _name, string _email, string _message)
{
//Create Mail Message Object with content that you want to send with mail.
MailMessage MyMailMessage = new MailMessage("gglebati#example.com", "gglebati#example.com", "This is the mail subject", "Just wanted to say Hello");
MyMailMessage.IsBodyHtml = false;
//Proper Authentication Details need to be passed when sending email from gmail
NetworkCredential mailAuthentication = new NetworkCredential("myxxxxx#gmail.com", "xxxxxxxxx");
//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
//Enable SSL
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
mailClient.Send(MyMailMessage);
}
and i have a html page. How can i call this function from my html page? (This function must send the message to email)
Use jQuery library. It makes ajax calls piece a cake. Then follow these items:
Add an HTML button to your page, so that people can start the ajax process by clicking it
Use jQuery to hook into the click event of that button (or span, or a div, or anything else)
Make sure you have ScriptService attribute on your web service (this attribute means that you can call your service from JavaScript)
Send items to your web service method
$('#buttonId').click(function(){
// Validating input
$.ajax({
type: 'POST',
url: '/your-web-service-path.asmx/your-method-name',
data: {}
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(r){},
error: function(e){}
});
});
Just note that you have to make a JSON object out of your parameters and the name of the JSON properties should match the name of the web service parameters. Also note that the return value of the web service would be available to you as r.d object passed to success callback of ajax call.
If it's an aspx page, you can add a ScriptManager with EnablePageMethods="true"attribute, and then call PageMethods.sendMail(name, email, message, onSuccess, onFail);
Maybe you want to take a look at jQuery's ajax capabilities.
You need to do something very important: Add the ScriptService attribute the class so that it can be called from a Javascript as in this example:
[ScriptService]
public class SimpleWebService : System.Web.Services.WebService
{
// ...
}
http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptserviceattribute.aspx
You have to pass the three parameters from the cs code page, by calling like this way,
service.SendMail(name, email, message);