I need to get some data from a controller into the JavaScript in a view.
I have the following method:
private JsonResult GetSection()
{
string orderId = (orderService.GetOrder(UserSEssion)).Id.ToString();
return this.Json(orderId);
}
I have the following in the view:
<script type="text/javascript">
lpAddVars('page', 'Section', + GetId()+);
function GetId() {
$.getJSON("/Checkout/GetSection", null, function (data) {
someThing = data;
});
}
</script>
I would appreciate any help in how to do this.
Thanks
Is the orderId already part of your model? You would be able to just access it in the view via the model. If you need the approach you are using I would start by making the method public and you may need to put the http verb attribute on it as well HttpGet
Related
Context: I am working on a Spring WEB MVC app using JSP for the view.
In my JSP page i have an input text field which in fact is a jquery daterange picker:
<input type="text" name="daterange" value="01/01/2017 - 01/31/2017" />
I thought in this ajax function I can retrieve the value of my input daterange and pass it to var daterange? like this:
function filterByDate() {
$.ajax({
url : 'outbatch',
data : ({}),
success : function(data) {
var daterange = document.getElementById("daterange").value();
}
});
}
And this is my Controller (i did not pase everyting it is too long don't look at the return null i just put it for showing) method who will update my batch and get the information from my model:
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public String updateEblnotif(Model model) {
String out_path = env.getProperty("notif_out");
List<Doc> doc_list = unmarshal(out_path, "LETTERS");
System.err.println("jbb*********" + doc_list.size());
Set<String> formname_set = new HashSet<>();
`......
return null`}
My question is: Where do I have to pass the variable in my Ajax function call to my Controller? I know that, if I am not mistaken there are several other option parameters that I can pass into an Ajax function like 'data' , 'datafilter' , 'datatype' ? Which is the best way for requesting Dates assuming in my model those are Java Date Objects
Note: I am a very Junior Developer this is my first project. My model uses a DAO with hibernate to map into the database.
Thanks to all of you for your help!
first of all you should get the value of the parameter in client side so to that you simple have to add id attribute to the tag so that your getElementById could be useful, try this :
<input type="text" name="daterange" id="daterange" value="01/01/2017 - 01/31/2017" />
now let's suppose that your function is responsible on retrieving the desired value and send it as parameter to the server side with AJAX, so it's simple :
function filterByDate() {
var daterange = document.getElementById("daterange").value();
$.ajax({
url : 'outbatch',
data : {"daterange":daterange}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
alert(data); //here you will see an alert displaying the callback result coming from your spring controller
}
});
}
now we sent the daterange to the controller , so we have to get it back there : to do that you simply can try the following approach :
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public #ResponseBody String updateEblnotif(Model model,#RequestParam("daterange") String daterange) {
//so here you're ahving the daterange parameter in controller , if you want to display it in the alert , you can send it in the return like this,
String date = "the daterange is "+daterange
return date;
}
i hope it was clearly for you.
I want to post three things to my MVC Controller: one image and two strings.
On the View, I've got a form that uses enctype="multipart/form-data" that automatically submits the form after an image file is selected. This is the submit handler for this form:
$("#PhotoUploadForm").on("submit", function (event) {
event.preventDefault();
var ImageData = $("#PhotoUploadFileInput").val();
var GuestNumber = $("#GuestID").val();
var TCSA_ID = vm.GetSelectedTreatmentAreaTCSA_ID(vm.Photographs.SelectedTreatmentArea());
var dto = {
ImageData: ImageData,
GuestNumber: GuestNumber,
TCSA_ID: TCSA_ID
}
$.ajax({
url: 'SaveImage',
type: "POST",
contentType: "multipart/form-data",
data: ko.toJSON(dto),
success: function (data) {
console.log(submitted);
}
});
});
The dto object is defined in my Model:
public class PhotoUploadDTO
{
public HttpPostedFileBase ImageData { get; set; }
public string GuestNumber { get; set; }
public string TCSA_ID { get; set; }
}
And in my Controller, I have an action that takes in dto as a parameter:
public ActionResult SaveImage(PhotoUploadDTO dto)
{
//etc.
}
When I try to post dto, everything gets posted as null. This problematic for me because I want to be able to post the image and two strings to the controller simultaneously.
I suspect that the issue is with var ImageData (which is set to the value of <input type="file" id="PhotoUploadFileInput"> on my View), and that it is being posted as C:/fakepath/etc. but not as the actual image file. It's frustrating because I know it wouldn't even be an issue if I had a form that just posted the image, but I need to use this submit handler and I don't know how to bring the actual image data into it.
Why is the data null when it hits the MVC Controller, and how can I post these three items while still being able to use a submit handler?
Uploading a file via ajax is a tricky thing. Some of the most modern web browsers handle this by using the File API which will indeed work for uploading a file via ajax. However, using this solution will not work with people on older browsers.
Your best bet is using a jquery plugin or something similar that will fall back on techniques such as uploading the file via an iframe or other workarounds.
I use MVC3.
I have `
function userLocation_change()
{
var text = $("#userLocation").val();
alert(text);
var url = '#Url.Action("GetAllLocations", "Home")';
var data = text;
$.post(url, data, function (result) {
});
}
`
Here is my controller action:
public JsonResult GetAllLocations(string userlocation)
{
///...some code...
return Json(..Something.., JsonRequestBehavior.AllowGet);
}
The problem is whenever the controller function is called "userlocation" parameter does have a NULL value. I want the data value would be passed to the controller action.
Could somebody plz tell me why this happens? Any update would be much appreciated.
Thanks.
You need to pass the parameter to the #Url.Action specifically via this overload method for Url.Action. You can use the RouteValueDictionary inline constructor with to instantiate.
Edit: realize now that you need that link to be populated at run time, but the Url.Action method generates the link at render time. I would suggest adding it to the query string and then reading it from the query string in your controller method. I suspect there is a more elegant way.. but I know this works.
something like: var url = '#Url.Action("GetAllLocations", "Home")?userlocation=' + $("#userLocation").val();
Modify your jQuery post function call as:
$.post(
url,
{ userlocation: text },
function(result){
....
});
This is because, you have to send data to the Controller's action method using JavaScript literal. You can view the full listing of different ways to call Controller's action using JavaScript here: http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
Your action has a string input parameter named userlocation, hence while sending the data to the action, you should specify this, like done in the code below.
Here I am using data: { userlocation: text},
function userLocation_change()
{
var text = $("#userLocation").val();
var url = '#Url.Action("GetAllLocations", "Home")';
$.ajax({
url: url,
type: 'POST',
data: { userlocation: text},
success: function (result) {
}
});
}
Hopes this solves your null problem.
I have an ajax call in my jquery to my MVC controller:
$.getJSON('/mysite/controller/dosomething', { postId: id }, function (data) {
The 'data' that I am returning is in the form of a JsonResult, and consists of a simple custom object with 1 property called 'Message' and another property called 'Count'. Both of these values are assigned and I am returning them as follows (edited for brevity):
[HttpGet]
public JsonResult DoSomething(int postId)
{
var response = new MyAjaxResponseModel {Message = "Hello world!", Count = 66};
return Json(response, JsonRequestBehavior.AllowGet);
}
In my jQuery, I then want to be able to look at both values in the Json response, but I don't know the proper way to get at these values?
data.Message, data.Count in the callback you're passing to $.getJSON()? To inspect the structure of your data object, you can use console.log(data) (also, in that callback)
I try to send data form ajax to cakephp cotroller
function loadtooltip(obj, $user_id) {
//AJAX
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
displaytooltip(obj, req.responseText);
}
}
};
req.open("POST", "http://127.0.0.1/cakeplate/tooltips/tooltip/", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send($user_id);
};
this controller
<?php
Class TooltipsController extends AppController{
var $name = 'Tooltips';
var $uses = array('Reply','User');
var $component = array('RequestHandler','Javascript','Ajax');
var $layout = 'tooltip';
function tooltip($user_id=NULL){
if(!empty($user_id)){
$tooltip = $this->Reply->User->findById($user_id);
$this->set('tooltip',$tooltip);
}
}
}
?>
I need somebody to help me to modified code
the way you're doing at the moment in the controller, you won't me able to get the user_id, because it is a var passed through GET method of http.
This variable would be accessible if you make a GET request for example for this url:
http://example.com/cakeplate/tooltips/tooltip/1 where 1 would be your $user_id.
If you send the request as POST, you can access the values in this var $this->data
This way you will be able to process the request based in the var that you pass to the controller.
Another problem that you will face that this controller will need to render a view, so i suggest that you take a look at http://book.cakephp.org/view/1238/REST, there you can see how you can create a route that will make the controller parse another view, it a different custom layout, like the json (the one i suggest in this case), and then you can show in this view only the json value.
Last, but important as well, i would suggest to that you use jQuery to do the javascript part, i think it will be easier, you can check it at http://api.jquery.com/jQuery.get