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;
}
Related
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;
},
});
});
I would like to store a response result from an ajax call. This is because the ajax is the main API call used by several functions to extract information from an API.
I call callAPI function more than 8 times in my app.
Of course, I can duplicate the function callAPI 8 times to properly get information but this is not cool way to code.
var result = callAPI("GET",url,'');
$('#status').val(result.success);
$('#output').val(result);
function callAPI(method_input, url_input, body_input){
var urli = url_input;
var datai = body_input;
var method = method_input;
$.ajax({
url: urli,
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("some header","some value");
},
type: method,
data: datai,
})
.done(function(data,status) {
console.log("success");
console.log(data);
return JSON.stringify(data);
})
.fail(function(data,status) {
console.log("error");
console.log(data);
return JSON.stringify(data);
});
}
I tried to store the return value using
var result = ajax(value);
but the result is empty
is there any way to store return value of a function to a variable?
EDIT
I Solved this problem by using callback function like below
function callbackResult(result){
$('#status').val(result.success);
$('#output').val(result);
}
function callAPI(method_input, url_input, body_input, callback){
var urli = url_input;
var datai = body_input;
var method = method_input;
$.ajax({
url: urli,
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("some header","some value");
},
type: method,
data: datai,
})
.done(function(data,status) {
console.log("success");
console.log(data);
return JSON.stringify(data);
callback(data);
})
.fail(function(data,status) {
console.log("error");
console.log(data);
return JSON.stringify(data);
callback(data);
});
}
This was my first function to use a callback function and now I know what the callback function is.
Thank you guys all.
You need 'async': false, so:
var result = $.ajax({
url: "https://api.github.com/users",
'async': false,
type: 'GET'
})
.done(function(data,status) {
console.log("success");
})
.fail(function(data,status) {
console.log("error");
});
console.log("result: " + result.responseText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
A few things to note:
Instead of JSON.stringify() I think you want to use JSON.parse() to parse the JSON string that is probably been returned by your API.
You can use the $.ajax option dataType to automatically parse the JSON string into an object.
$.ajax() returns a promise which can be chained to add as many callbacks as needed.
A more elegant solution would be to return the promise from your function and chain your callbacks. Ex:
function callAPI(method_input, url_input, body_input) {
var urli = url_input;
var datai = body_input;
var method = method_input;
return $.ajax({
url: urli,
// Automatically parses JSON response
dataType: 'json',
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("some header", "some value");
},
type: method,
data: datai,
})
.done(function(data, status) {
console.log("success");
console.log(data);
})
.fail(function(data, status) {
console.log("error");
console.log(data);
});
}
callAPI('GET', '').then(function(result){
// Do something with my API result
});
If you plan on making all request at once, with this solution you can consider aggregating all the request into a single promise with $.when(). Ex:
$.when(
callAPI('GET', ''),
callAPI('GET', 'second'),
callAPI('GET', 'third')
).then(function(firstResult, secondResult, thirdResult){
// Do stuff with the result of all three requests
});
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.
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);
I am using spring MVC and JQuery ajax. In one of my ajax call it returns large amount of data it nearly takes 5 minutes.
In Ajax method shows error even though the response came i checked it through firebug.
my ajax coding is
jQuery(document).ready(function () {
jQuery("sampleSearch").click(function () {
jQuery("body").addClass("loading");
var formValues = jQuery('#sample-search-form').find(':input[value][value!=""]').serialize();
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
});
});
and in my controller
#RequestMapping(value = "/user-byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(HttpServletRequest request) {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
Integer page = Integer.parseInt(request.getParameter("page"));
String resultJson = getUserByName(firstName, lastName, page);
return resultJson;
}
You need to increase the timeout for the request.
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
timeout: 600000,
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
read more in the .ajax() documentation