Dropbox API: Sending Data Via Ajax to Controller - javascript

I am using the Dropbox API JavaScript Chooser and want to return the data from the response into my Controller
The Javascript Options for the Dropbox API
options = {
success: function (files) {
$.ajax({
url: '/FileTransfer/FileData',
type: "POST",
dataType: "json",
//data: JSON.stringify(files[0]),
data: files,
success: function (result) {}
});
},
cancel: function () {},
linkType: "preview",
multiselect: true
};
Controller Action
My controller action currently doesn't do anything at the moment but will eventually cache the output data into a model once i can get data to be passed into it, which is hence my problem.
public JsonResult FileData(string model)
{
return Json(new { success = true });
}

ADyson`s hints have helped me solve my problem, thank you
Altered code below, note the change to data: and then deserialised in the Controller
Javascript
options = {
success: function (files) {
$.ajax({
url: '/FileTransfer/FileData',
type: "POST",
dataType: "json",
data: { result : JSON.stringify(files) },
//data: files,
success: function (result) {
$("#FileList").load('/FileTransfer/Cloud');
console.log(result);
},
error : function (jQXHR, textStatus, errorThrown) {
//alert("An error occurred: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
});
},
cancel: function () {},
linkType: "preview",
multiselect: true
};
Controller
public JsonResult FileData(string result)
{
var convertedResult = JsonConvert.DeserializeObject<List<DropboxFile>>(result);
CacheEntity(convertedResult);
return Json(new { success = true });
}

Refactored code following suggestion
Javascript
options = {
success: function (files) {
$.ajax({
url: '/FileTransfer/FileData',
type: "POST",
dataType: "json",
data: { result : files},
success: function (result) {
$("#FileList").load('/FileTransfer/Cloud');
},
error : function (jQXHR, textStatus, errorThrown) { }
});
},
cancel: function () {
},
linkType: "preview",
multiselect: true
};
Controller
public JsonResult FileData(List<DropboxFile> result)
{
CacheEntity(result);
return Json(new { success = true });
}

Related

How to avoid repeating the same $.ajax() call

I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work

ReferenceError: response is not defined on autocomplete jquery ajax call in singleton design pattern

I am trying to implement jQuery autocomplete in my solution but I got an error ReferenceError: response is not defined
Here is my code
(function ($) {
$.SupportArticleObj = function (p) {
var SupportArticle = {
config: {
isPostBack: false,
async: false,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { data: '' },
dataType: 'json',
baseURL: "Modules/SupportArticle/Services/SupportArticleWebService.asmx/",
url: "",
method: "",
ajaxCallMode: 0,
PortalID: PortalID,
UserModuleID: UserModuleID,
SecureToken: SecureToken,
UserName: UserName
},
init: function () {
$("#searchSupport").autocomplete({
source: function (request, response) {
searchTerm = request.term;
SupportArticle.getSearchData(searchTerm);
}
});
},
getSearchData: function (searchTearm) {
SupportArticle.config.method = "SearchSupportArticle";
SupportArticle.config.url = SupportArticle.config.baseURL + SupportArticle.config.method;
SupportArticle.config.data = JSON2.stringify({
searchTerm: searchTerm,
portalID: SupportArticle.config.PortalID,
userModuleID: SupportArticle.config.UserModuleID,
userName: SupportArticle.config.UserName,
secureToken: SupportArticle.config.SecureToken
});
SupportArticle.ajaxCall(SupportArticle.config);
},
ajaxSuccess: function (data) {
response(data);
},
ajaxFailure: function () {
jAlert('Somethings went wrong', 'Support Article');
},
ajaxCall: function (config) {
$.ajax({
type: SupportArticle.config.type,
contentType: SupportArticle.config.contentType,
cache: SupportArticle.config.cache,
url: SupportArticle.config.url,
data: SupportArticle.config.data,
dataType: SupportArticle.config.dataType,
success: SupportArticle.ajaxSuccess,
error: SupportArticle.ajaxFailure,
async: SupportArticle.config.async
});
}
};
SupportArticle.init();
};
$.fn.callSupportArticle = function (p) {
$.SupportArticleObj(p);
};
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
What I am trying to do here is, I am calling a webservice which will search the records on database and return as a list and I want to bind that list on textbox as a autocomplete. But the problem is while running the solution in browser I got an error ReferenceError: response is not defined.
I was trying http://www.c-sharpcorner.com/UploadFile/da55bf/Asp-Net-autocomplete-textbox-using-jquery-json-and-ajax/ as reference.
How can I solve the issue of ReferenceError: response is not defined
Write your script like below:
AutoDemoDataBase: function () {
$("#lytA_ctl29_txtSearchName").autocomplete({
source: function (request, response) {
var param = JSON.stringify({
userModuleID: UserModuleID,
portalID: autoComplete.config.portalId,
prefix: $("#lytA_ctl29_txtSearchName").val(),
userName: autoComplete.config.UserName,
secureToken: SageFrameSecureToken
});
$.ajax({
type: autoComplete.config.type,
contentType: autoComplete.config.contentType,
cache: autoComplete.config.cache,
url: autoComplete.config.baseURL + "GetNames",
data: param,
dataType: autoComplete.config.dataType,
async: autoComplete.config.async,
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (response) {
jAlert(response.responseText);
},
failure: function (response) {
jAlert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfId").val(i.item.val);
$('#test').text(i.item.val);
},
minLength: 1
});
}
Your ajax success function is out of response scope.

C# How to call MVC Controller function by using javascript or jquery

I have this at my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteUser(UserViewModel viewModel)
{
}
I have this at my cshtml:
<input type="button" id="btnDelete" value="Delete" />
I have this at my js file:
$('#btnDelete').click(function (e) {
});
How do I call controller function from js file?
$.post("Controller/CreateUser", dataToPost)
.done(function(response, status, jqxhr){
// this is the "success" callback
})
.fail(function(jqxhr, status, error){
// this is the ""error"" callback
});
or
var data = {
username: $('#username').val().trim(),
password: $('#password').val()
};
$.ajax({
type: "POST",
url: "Controller/CreateUser",
content: "application/json;",
dataType: "json",
data: JSON.stringify(data),
success: function(d) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
ps: compose the data object according to the UserViewModel properties.
Inside the button click, execute ajax request
$('#btnDelete').click(function (e) {
$.ajax({
type: "POST",
url: 'controller/DeleteUser',
dataType: "json",
success: function(data){
//html content
},
});
}
It's very easy to access any controller method using ajax post method.
As here I'm getting states as per selected country using
'RegionesController' method name 'GetStates' also here I'm passing
CountryId to get states as per this id.
EX:
function GetStates() {
$.ajax({
type: "POST",
async: false,
url: abp.appPath + 'Regiones/GetStates?CountryId=' + $("#ddlCountry").val(),
success: function (result) {
//return data or object
},
error: function (err) {
abp.notify.info(err.statusText);
}
});
}

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

I have the following controller method:
public JsonResult CreateGroup(String GroupName)
{
ApplicationUser user;
var userName = User.Identity.Name;
using (DAL.GDContext context = new DAL.GDContext())
{
user = context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null)
{
var group = new Group();
group.GroupName = GroupName;
group.Members.Add(user);
context.Groups.Add(group);
context.SaveChanges();
}
}
string result = userName;
return Json(result, JsonRequestBehavior.AllowGet);
}
with the following ajax call:
$(function () {
$('#CreateGroup').on("click", function () {
var groupName = $('#groupname').val();
if (groupName != '') {
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: JSON.stringify({ 'GroupName': groupName }),
dataType: "json",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
}
});
The CreateGroup function fails saying "Uncaught ReferenceError: data is not defined"
Do i have to use another Json request - type post - to get the username?
you can do the call without using JSON.stringify. Also your controller method has a cache attribute that may yield more control. Personally, I would use the controller cache control. You are probably getting a cached version of the controller call prior to returning data.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult CreateGroup(string GroupName)
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: { 'GroupName': groupName },
dataType: "json",
traditional: true,
success: function (data, status, xhr ) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
NOTE: Update success callback.

AJAX post data is null in controller mvc

I try to send a JSON object back to the server. This is my AJAX call:
$.ajax({
url: '/Home/NewService',
async: false,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCES");
}
});
The evaluation of JSON.stringify(props) in the browser's debugger is
"[{"name":"firstName","value":"firstValue"}]"
This is the method in the controller which is being called:
[HttpPost]
public void NewService(dynamic json)
{
Response.Write(json);
}
The problem I have is that always the json variable from above is an empty object.
The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong.
Thank you.
I don't think you can bind to a dynamic type the way you're trying to. You can try to create a class that maps your data, something like:
public class Content
{
public string Name { get; set; }
public string Value { get; set; }
}
Now in your action:
[HttpPost]
public ActionResult NewService(Content[] data)
{
// sweet !
}
And in your js like Olaf Dietsche said you need to specify your contentType:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '/Home/NewService',
contentType: "application/json",
async: true,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
According to jQuery.ajax(), the default content type is is application/x-www-form-urlencoded. If you want to send the data as JSON, you must change this to
$.ajax({
url: '/Home/NewService',
contentType: 'application/json',
...
});
Use the following code to solve this problem
Ajax Call
function SaveDate() {
var obj = {};
obj.ID = '10';
obj.Name = 'Shafiullah';
$.ajax({
url: '/Home/GetData',
dataType: "json",
type: "Post",
contentType: 'application/json',
data: JSON.stringify({ ID: obj.ID, Name: obj.Name }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data.id + ' , ' + data.name);
},
error: function (xhr) {
alert('error');
}
});
}
My controller action method
[HttpPost]
public IActionResult GetData([FromBody] Employee employee)
{
return Json(employee);
}

Categories