Angular Datatables use source object - ajax

With Angular Datatables I want to pre-load a JSON object with Ajax so that I can re-use the object elsewhere without doing another ajax request.
But how do I load this object into the datatable?
.controller('ResponsiveDatatableCtrl', function ($scope, $rootScope, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $state, $http) {
$scope.dataLoading2 = true;
var vm = this;
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.files.php"+data;
var headers = {'Content-Type': 'application/x-www-form-urlencoded'};
$http({
method: 'POST',
url: url,
headers: headers,
})
.success(function (response) {
$rootScope.globals.files = response;
$scope.dataLoading2 = false;
//console.log($rootScope.globals.files);
});
vm.dtOptions = DTOptionsBuilder.fromFnPromise($rootScope.globals.files)
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);
})

Ok I have attempted the following and it seems to call my code under success but then the table doesn't update?
vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: url,
type: 'POST',
headers: headers,
data: function(data, dtInstance) {
},
success: function(response) {
$rootScope.globals.files = response;
}
})
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);

Related

laravel - ajax formdata wont show in controller

I have tried many different combination for AJAX Setup in order to send the formData to controller. Somehow I cannot get the form input inside my controller despite trying to return it will all type of ways. May I know what did I miss that causing me not be able to get the input in controller?
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
console.log(Array.from(formData));
$.ajax({
url: url,
type: "PATCH",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
cache: false,
dataType: false,
contentType: false,
processData: false,
data:formData,
success: function (response) {
console.log(response);
return false;
},
});
});
public function update(Request $request){
$UserId = Auth::user()->id;
$Company = Company::where('id', Auth::user()->company_id)->first();
return $request->all();
}
use
<meta name="csrf-token" content="{{ csrf_token() }}">
in head
and jQuery code
$('#form_submit').submit(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var base = window.location.origin;
let formData = new FormData(this);
let my_url = base + "/article-store";
$.ajax({
type: 'post',
url: my_url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
},
error: function (data) {
}
});
});
After quite a bit of digging, since what I am doing is using the PATCH request, it's still not working as of now with FormData. To solve it, we need to spoof the method by appending the PATCH method to formData and our AJAX settings to be changed to POST. Then you'll receive all the request inside your controller.
Reference:
https://laracasts.com/discuss/channels/laravel/ajax-formdata-and-put-fails
https://laracasts.com/discuss/channels/javascript/axiosajax-http-patch-requests-with-file-not-working
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
formData.append('_method', 'PATCH');
console.log(Array.from(formData));
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: url,
data:formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
return false;
},
});
});

Why Is This AJAX Request Failing

this is my first time trying to implement AJAX and I haven't been able to figure out why its failing. Apologies, as it's probably easy enough spot for a seasoned AJAX user. I'd appreciate if you took a look.
JQuery File:
//declare variables
var friendSearch;
var csrfHeader = "[[${_csrf.headerName}]]";
var csrfToken = "[[${_csrf.token}]]";
$(document).ready(function(){
//give variables values
friendSearch = $("#friendSearchBox");
//call functions when
$(friendSearch).on('input', function(){
updateFriendsDisplay();
})
});
//functions
function updateFriendsDisplay(){
var jsonData = {searchString: friendSearch.val()}
$.ajax({
type: 'POST',
url: 'http://localhost:8080/friends/search',
beforeSend: function(xhr){
xhr.setRequestHeader(csrfHeader, csrfToken);
},
data: JSON.stringify(jsonData),
contentType: 'application/json'
}).done(function(data){
alert(data);
}).fail(function(){
alert("failed");
});
}
Controller:
#ResponseBody
#PostMapping("/search")
public List<UserAccount> getFriendsBySearch(#RequestParam("searchString") String text){
List<UserAccount> accountsList = uRepo.findByUserNamePortion(text);
return accountsList;
}

How submit captcha to the controller using ajax and form data

I have a form with some fields and file upload, rendering as a partial view using ajax in asp.net MVC. when submitting the form, I want to pass all the data to the controller. But if I use $("form").serialize(), it is not passing the selected file to the controller. So I am using formData() to pass the data to the controller. Till this point, everything works fine.
But after adding captcha using CaptchaMvc, it not reaching the controller. Even if I enter valid captcha, it is invalid in the controller.
This is how I send data to the controller using the ajax and formData
var data = new FormData();
var vidFile = null;
if ($("#FileUpload")[0].files.length > 0)
vidFile = $("#FileUpload")[0].files[0];
data.append("detail", $("#detail").val());
data.append("name", $("#name").val());
data.append("FileUpload", vidFile);
$.ajax({
url: "/home/submitData",
type: "POST",
contentType: false,
processData:false,
data: data,
success: function (response) {
if (response.success == true) {
} else {
}
}
});
Is there any way to pass the captcha as well to the controller?
Why can't you validate using different controller function, as follows:
At the time of submission, validate the captcha first, and depending on the result, call another controller function to submit data or show the error.
var submitData = function(){
var data = new FormData();
var vidFile = null;
if ($("#FileUpload")[0].files.length > 0)
vidFile = $("#FileUpload")[0].files[0];
data.append("detail", $("#detail").val());
data.append("name", $("#name").val());
data.append("FileUpload", vidFile);
$.ajax({
url: "/home/submitData",
type: "POST",
contentType: false,
processData:false,
data: data,
success: function (response) {
if (response.success == true) {
//Success
} else {
//Submission failed
}
}
});
}
var validateCaptcha = function(){
$.ajax({
url: "/home/validateCaptcha",
type: "POST",
data: $("form").serialize(),
success: function (response) {
if (response.success == true) {
submitData();
} else {
alert("Invalid Captcha entry");
}
}
});
}
$("form").submit(function(e){
validateCaptcha();
});

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.

post method not working phantomjs2

my header is
var headers = {
'Content-Type': 'application/json'
}
and data is
data = '{"mydata": "foo"}';
and code is
page.open('my site url', 'POST', data, headers, function (status) {
var jsonSource = page.content;
console.log(jsonSource);
phantom.exit();
});
but in onResourceRequest my method is 'GET'
what is problem ?

Resources