Jquery ajax is not able to send data to mvc3 controller action - asp.net-mvc-3

I am working with MVC3. I have a javascript function which makes an ajax call to mvc3 controller action. When i send null in the data, it calls the controller action. but when I try to send location in data it gives javascript error i.e. 'this is not defined'.
function getPictureContent(location)
{
var pictures = getLocationPictures(location);
var content = "<div id=markerpictures></div>";
return content;
}
function getLocationPictures(location) {
var pics;
$.ajax({
type : "POST",
url : "/Home/GetLocationPictures",
data : {'location' : location},
contentType : "application/json; charset=utf-8",
dataType : 'json',
async : false,
success : function (data) {
pics = data;
}
});
return pics;
}
Here is the controller action:
public JsonResult GetLocationPictures(string location)
{
List<string> pictures = new List<string>();
return Json(pictures);
}

Try this.. Location should be string.Be sure that will string.
function getLocationPictures(location) {
var pics;
$.ajax({
type : "POST",
url : "/Home/GetLocationPictures",
data : JSON.stringify({'location' : location}),
contentType : "application/json; charset=utf-8",
dataType : 'json',
async : false,
success : function (data) {
pics = data;
}
});

Related

Accessing of Web API response object in another partial view (cshtml / cshtml.cs file) in Visual Studio 2022

On click of a button will from a partialview 1 below js function will be called and get the data from the controller and will be redirected to another partialview. Since it the controller is in another project and hosted separately, controller is not returning the partialview hence I am redirecting it if the ajax call is success.
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(paramObj),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
var userObject = response.internalObject;
window.location.href = url2;
},
error: function (response, status, error) {
if (response.responseText != undefined) {
const obj = JSON.parse(response.responseText);
fnShowMessage(obj.DisplayMessage);
}
}
});
I have the data in "userObject" from the ajax call which needs to be displayed in partialview, but I cannot access it or not sure how to access it.
The assigned value in OnGet() method in "partialview2.cshtml.cs" is able to retain in "partialview2.cshtml" file. But how to get the values which I got from the ajax call in partialview 1 in code behind of partialview 2.
public class UserModel : PageModel
{
[BindProperty]
public UserObject UserObject { get; set; } = new();
public void OnGet()
{
UserObject.UserName = "man";
}
}
You can try to return JsonResult in OnGet:
ajax:
$.ajax({
type: "POST",
url: "/Home/Test",
data: JSON.stringify(paramObj),
contentType: "application/json; charset=utf-8",
traditional: true,
dataType: "json",
success: function (response) {
var userObject = response;
window.location.href = url2;
},
error: function (response, status, error) {
if (response.responseText != undefined) {
const obj = JSON.parse(response.responseText);
fnShowMessage(obj.DisplayMessage);
}
}
});
OnGet handler:
public class UserModel : PageModel
{
[BindProperty]
public UserObject UserObject { get; set; } = new();
public JsonResult OnGet()
{
UserObject.UserName = "man";
return new JsonResult(UserObject);
}
}

AJAX sending data to laravel controller and it is not working

I am trying to send user slug to my laravel controller and its not working
here is my html code :
<a class="card" onclick="chat_send($data = '{{$user->slug}}');">
here is my script :
function chat_send(){
var data = $data;
var action_url = '{{ route('chat.show','data')}}';
$.ajax({
type : "POST",
url : action_url,
data : {data:data},
dataType : "json",
success:function(data){
if(data.errors){
alert('Message Field is Empty.');
}
if(data.success){
alert('Success');
}
}
});
};
controller code :
public function show(Request $request)
{
$slug = $request->get('data');
return view('chat',compact('slug'));
// return view('test');
}
this is the error I got :
Console log
Just do this error will be resolved.
<a class="card" onclick="chat_send('{{$user->slug}}');">
And in script:
function chat_send(data){
var action_url = '{{ route('chat.show','data')}}';
$.ajax({
type : "POST",
url : action_url,
data : {data:data},
dataType : "json",
success:function(data){
if(data.errors){
alert('Message Field is Empty.');
}
if(data.success){
alert('Success');
}
}
});
};
try like below:
<a class="card" id="card" data = '{{$user->slug}}'>
Use JQuery for sending ajax:
$(document).ready(function(){
$('#card').click(function(){
var data = $(this).attr(data)
var action_url = '{{ route('chat.show','data')}}';
$.ajax({
type : "POST",
url : action_url,
data : {data:data},
dataType : "json",
success:function(data){
if(data.errors){
alert('Message Field is Empty.');
}
if(data.success){
alert('Success');
}
}
});
};
})
})

Passing Dictionary<string, List<string>> from ajax to mvc controller not working

While passing dictionary values from ajax to MVC controller I couldn't get the "value" from the dictionary but "key" value is available. This is what I have tried.
function makeCall() {
var data = {};
data['one'] = [];
data['one'].push("1");
data['one'].push("2");
data['two'] = [];
data['two'].push("1");
data['two'].push("2");
var name = "panelData";
$.ajax({
url: '#Url.Action("AjaxSample", "Home")',
data: { complexObject: data},
//contentType: "application/json; charset=utf-8", //sending type
//dataType: "json", //expected type
success: successFunc,
error: errorFunc
});
}
If I pass Dictionary<int,int> or Dictionary<string,int> it's working.

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

Resources