CakePHP 4.x Ajax request with CSV-file - javascript

I am developing a responsive user interface in CakePHP 4.x which occasionally uses Ajax requests.
My Ajax requests are performing just fine but I am having a lot of trouble incorporating a CSV-file in the request so my controller can handle the data. What I want to accomplish is that that I can choose a CSV-file, press submit and that the Ajax-request sends the file to the controller and uses the independent rows to update the database.
My code:
Javscript:
function importProducts() {
/* Getting form data */
let form = document.getElementById('importProductsForm');
let formData = new FormData();
let file = $(form.products_file).prop('files')[0];
formData.append("csv_file", file);
/* Moving product stock */
ajaxRequest('Products', 'importProducts', formData, processImportProducts);
}
function ajaxRequest(controller, action, data = null, callback = null) {
$.ajax({
url : "<?=$this->Url->build(['controller' => '']);?>" + "/" + controller + "/" + action,
type : 'POST',
data : {
'data': data
},
dataType :'json',
/*processData: false,*/
/*contentType: false,*/
success : function(dataArray) {
let response = dataArray.response;
if (typeof response.data !== 'undefined') {
data = response.data;
if (callback != null) {
callback(data);
}
} else if (response.success == 0) {
data = null;
giveError(response.errorTemplate);
} else {
data = null;
if (callback != null) {
callback(data);
}
}
},
error : function(request,error)
{
console.error(error);
}
});
}
At the moment the controller function does not do anything special but receiving and setting the data:
public function importProducts() {
$this->RequestHandler->renderAs($this, 'json');
$response = [];
if($this->request->is('post')) {
$data = $this->request->getData();
$response['test'] = $data;
} else {
$response['success'] = 0;
}
$this->set(compact('response'));
$this->viewBuilder()->setOption('serialize', true);
$this->RequestHandler->renderAs($this, 'json');
}
After some research I discovered I could use the FormData object to send the file. The error I then received was 'illegal invocation'. After some more research I discovered this had to with automatic string parsing by Ajax. According to some other StackOverflow posts I could resolve this by setting the processdata and contenttype properties to false. This fixed the problem but resulted in an Ajax request which always would be empty (that does not contain any data). I tested this without the CSV-file with a regular data object that contains a variable with a string but also resulted in a empty request (no data send to controller).
So my problem is that without the processdata property as false I get the 'illegal invocation' error, otherwise with processdata as false I literary do not receive any data in my controller. I am looking for solution to resolve this problem so I can send my CSV-file or at least the data within the file to my controller.
Other solutions than using the FormData are also welcome, for example I tried to read the CSV-file in Javascript and turn this into another object (with the jquery csv api) to send to the controller, sadly without success until now.

Related

Returning variable value from controller to view

I'm new at Laravel and I'm actively trying to code better, but I'm currently stuck with problems I don't know how to solve.
The controller :
public function sendGiving($contents){
$redirectURL = $contents->redirectURL;
var_dump($redirectURL); // the variable is available, logged in network section
return View::make('giving/giving')->with('redirectURL', $redirectURL);
}
The view (on AJAX) :
function submitForm() {
if (is_personal_data_complete() == true && is_offering_filled() == true && isreCaptchaChecked() == true) {
var base_url = window.location.origin;
//send ajax request
$.post("{{ route('send_giving') }}",
{
_method: 'POST',
_token: '{{ csrf_token() }}',
name: $('#txtName').val(),
email: $('#txtEmail').val(),
phone_number: $('#txtnohp').val(),
thanksgiving_offerings: total_thanksgiving,
tithe_offerings: total_tithe,
firstborn_offerings: total_firstborn,
build_offerings: total_build,
deacon_offerings: total_deacon,
mission_offerings: total_mission,
paud_offerings: total_paud,
dataType: "jsonp",
async : false,
success: function($redirectURL){
alert($redirectURL);
},
});
}
else if (is_personal_data_complete() == false) {
alert("Please fill in your data form");
}
else if (is_offering_filled() == false) {
alert("Please fill in your offerings");
}
else if (isreCaptchaChecked() == false){
alert("Please check the captcha");
}
return false;
}
The alert always returns undefined though, what am I missing?
Please try this:
return response()->json($redirectURL)
When you use Laravel and write API, you need to use this command to reponse JSON for frontend
The view() function just creates an instance of the View class. Not just an HTML string. For that you should call render():
$returnHTML = view('giving/giving')->with('redirectURL', $redirectURL)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));
When you return in your controller return View::make('giving/giving')->with('redirectURL', $redirectURL);
You are returning a VIEW file, which will be return as the body of the HTTP request.
and you are also passing to Your view file redirectUrl which will be accessible in your view file.
And when you perform your AJAX request, you are getting a response with a body which contain HTML/TEXT Content not JSON.
SO YOU CAN'T HAVE ACCESS TO redirectURL VARIABLE
So what you should do by the way is to return simple a JSON body by returning in your Controller something like
return response()->json([
'redirectURL' => $redirectURL
]);
No need to return a VIEW FILE
You can't return in the same controller JSON data in the body and a VIEW FILE
The main issue is here that you try to send a POST with JSONP data type.
There are a lot of explanations on this on SO, e.g https://stackoverflow.com/a/18934048/8574551
Try to remove it and use smth like the next:
...
contentType: "application/json",
dataType: "json",
...
On another hand, you can omit these 2 parameters (check https://api.jquery.com/jquery.post/)
To return the data from the controller action you can use response()->json(..) (as described in other answers)
the problem is on the ajax request, as after changing the format it works nicely

Spring MVC back end ajax validation

For my current project Java/Spring project I have to validate a form. The webpage is a freemarker template file.
The <form> has no special attribute to send the data to the controller. The project uses Ajax to send the request. The controller doesn't receive the form at all.
When the user submits the data, a JavaScript function is called to receive all the data by collecting the elementID's. The data is put in a variable, like this (short version);
var userId = document.getElementById('input_id').value.toLowerCase();
var width = document.getElementById("width");
var height = document.getElementById("height");
The function then puts all the data into a JSON. This JSON is put in the Ajax, and then Ajax calls the right controller.
**Ajax code **
$.ajax({
url: url,
type: "POST",
dataType: "json", // expected format for response
contentType: "application/json", // send as JSON
Accept: "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8",
data: data,
success: function (response) {
// we have the response
if (response.status == "SUCCESS") {
console.log("succes");
//Redirect to the right page if the user has been saved successfully
if (type === "setupuser") {
window.location = "/setup/user/" + userId;
} else if (type === "simulatoruser") {
window.location = "/simulator/user/" + userId;
}
} else {
errorInfo = "";
for (i = 0; i < response.result.length; i++) {
errorInfo += "<br>" + (i + 1) + ". " + response.result[i].code;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
}
},
error: function (e) {
alert('Error: ' + e);
}
});
The following controller is called by the Ajax request:
#RequestMapping(method = RequestMethod.POST, value = "/adduser/{userType}")
#ResponseBody
JsonResponse addUserMapping(#ModelAttribute(value="user") User user, BindingResult result, #RequestBody String jsonString, #PathVariable String userType) {
def json = new JsonSlurper().parseText(jsonString)
String userId = json.userId
String userName = json.userName
user.setId(userId)
user.setName(userName)
log.warn("User id..... "+user.getId())
log.warn("User name..... "+user.getName())
JsonResponse res = new JsonResponse();
ValidationUtils.rejectIfEmpty(result, "id", "userId can not be empty.");
ValidationUtils.rejectIfEmpty(result, "name", "userName can not be empty");
if(!result.hasErrors()){
userService.addUser(jsonString)
res.setStatus("SUCCESS");
}else{
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
As you can see, Ajax sends a JSON to the controller. The controller unpacks the JSON and puts the data into the user object. Then the user object is being validated using "rejectIfEmpty()" method...
Now I've been reading about making a userValidator class extending Validator, or simply putting Annotations in the bean class like:
#Size(min=1, max=3)
I prefer these annotations since you don't have to write special code for checking certain simple things (like the field not being empty .. #NotEmpty)
But that doesn't work because the controller doesn't take a user object the second it's called, instead it takes the JSON and then unpacks it (Validating is too late..)
TL:DR
Controller takes a JSON as a parameter instead of an Object. The JSON has to be unpacked and then validated in the controller as a java object using rejectIfEmpty as an example. I don't want a full page reload, but I still want to keep Ajax.
BTW: I want to validate the data against more things like regex etc. But the rejectifEmpty is a simple example.
Does anyone have an idea how to handle this?
I fixed the validation by parsing the JSON in the controller and setting it in the user object. The user object is then put in my UserValidator class and validated.
Link for more info using the validator:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/validation.html

$http GET URL changes and looks for wrong resource

I'm developing a single page application. I am making use of Angularjs.v1.2.28. I'm making a HTTP GET request to the backend using this code.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http.get(req);
},
I make use of the promise object that is returned from service in controller.
var categoryPromise = categoryService.getCategories(sessionid,terminalid,tableno,section);
categoryPromise.then(function(payload){
var categories = payload.data;
if(categories.status.code == "1"){
if(Object.prototype.toString.call(categories) === '[object Array]') {
$scope.categories = categories;
categoryService.setCategories(categories);
$scope.pax = tableService.getPax();
$scope.tablechair = tableService.getChoseTableChair();
}
}
else{
$location.url("/login");
$scope.errorMsg = categories.status.desc;
}
},function(errorPayload){
$location.url("/login");
$scope.errorMsg = "Server error while processing the request.Please contact system administrator";
});
It's always the errorCallback is getting called due to the URL getting changed to the browser application URL appended with some malformed characters. The URL which i give is
http://localhost:8080/CafexRestful/menucategories
But, it gets changed to the browser application URL below
http://localhost:8080/CafexMobile/[object%20Object]
I have been debugging in Chrome and Firebug. I couldn't resolve it. It may be something which is happening under the hood. The same code is working with another controller and service, where i fetch a different data. Please let me know if you need anymore information. Thanks.
$http.get in angularjs needs an url string. You should use url string instead of an object
Using $http.get function:
return {
getCategories : function(){
return $http.get("/menucategories"); // using $http.get function.
},
Using $http function.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http(req); //using $http function only.
},
Please see the document: https://docs.angularjs.org/api/ng/service/$http

Fetch data on different server with backbone.js

I can't see what the problem with this is.
I'm trying to fetch data on a different server, the url within the collection is correct but returns a 404 error. When trying to fetch the data the error function is triggered and no data is returned. The php script that returns the data works and gives me the output as expected. Can anyone see what's wrong with my code?
Thanks in advance :)
// function within view to fetch data
fetchData: function()
{
console.log('fetchData')
// Assign scope.
var $this = this;
// Set the colletion.
this.collection = new BookmarkCollection();
console.log(this.collection)
// Call server to get data.
this.collection.fetch(
{
cache: false,
success: function(collection, response)
{
console.log(collection)
// If there are no errors.
if (!collection.errors)
{
// Set JSON of collection to global variable.
app.userBookmarks = collection.toJSON();
// $this.loaded=true;
// Call function to render view.
$this.render();
}
// END if.
},
error: function(collection, response)
{
console.log('fetchData error')
console.log(collection)
console.log(response)
}
});
},
// end of function
Model and collection:
BookmarkModel = Backbone.Model.extend(
{
idAttribute: 'lineNavRef'
});
BookmarkCollection = Backbone.Collection.extend(
{
model: BookmarkModel,
//urlRoot: 'data/getBookmarks.php',
urlRoot: 'http://' + app.Domain + ':' + app.serverPort + '/data/getBookmarks.php?fromCrm=true',
url: function()
{
console.log(this.urlRoot)
return this.urlRoot;
},
parse: function (data, xhr)
{
console.log(data)
// Default error status.
this.errors = false;
if (data.responseCode < 1 || data.errorCode < 1)
{
this.errors = true;
}
return data;
}
});
You can make the requests using JSONP (read about here: http://en.wikipedia.org/wiki/JSONP).
To achive it using Backbone, simply do this:
var collection = new MyCollection();
collection.fetch({ dataType: 'jsonp' });
You backend must ready to do this. The server will receive a callback name generated by jQuery, passed on the query string. So the server must respond:
name_of_callback_fuction_generated({ YOUR DATA HERE });
Hope I've helped.
This is a cross domain request - no can do. Will need to use a local script and use curl to access the one on the other domain.

ASP.NET MVC JsonResult return 500

I have this controller method:
public JsonResult List(int number) {
var list = new Dictionary <int, string> ();
list.Add(1, "one");
list.Add(2, "two");
list.Add(3, "three");
var q = (from h in list where h.Key == number select new {
key = h.Key,
value = h.Value
});
return Json(list);
}
On the client side, have this jQuery script:
$("#radio1").click(function() {
$.ajax({
url: "/Home/List",
dataType: "json",
data: {
number: '1'
},
success: function(data) {
alert(data)
},
error: function(xhr) {
alert(xhr.status)
}
});
});
I always get an error code 500. What's the problem?
Thank you
If you saw the actual response, it would probably say
This request has been blocked because
sensitive information could be
disclosed to third party web sites
when this is used in a GET request. To
allow GET requests, set
JsonRequestBehavior to AllowGet.
You'll need to use the overloaded Json constructor to include a JsonRequestBehavior of JsonRequestBehavior.AllowGet such as:
return Json(list, JsonRequestBehavior.AllowGet);
Here's how it looks in your example code (note this also changes your ints to strings or else you'd get another error).
public JsonResult List(int number) {
var list = new Dictionary<string, string>();
list.Add("1", "one");
list.Add("2", "two");
list.Add("3", "three");
var q = (from h in list
where h.Key == number.ToString()
select new {
key = h.Key,
value = h.Value
});
return Json(list, JsonRequestBehavior.AllowGet);
}
While JustinStolle's answer solves your problem, I would pay attention to the error provided from the framework. Unless you have a good reason to want to send your data with the GET method, you should aim to send it with the POST method.
The thing is, when you use the GET method, your parameters gets added to your request url instead of added to the headers/body of your request. This might seem like a tiny difference, but the error hints why it's important. Proxy servers and other potential servers between the sender and the receiver are prone to logging the request url and often ignore the headers and/or body of the request. This information is also often regarded as non important/secret so any data exposed in the url is much less secure by default.
The best practice is then to send your data with the POST method so your data is added to the body instead of the url. Luckily this is easily changed, especially since you're using jquery. You can either use the $.post wrapper or add type: "POST" to your parameters:
$.ajax({
url: "/Home/List",
type: "POST",
dataType: "json",
data: { number: '1' },
success: function (data) { alert(data) },
error: function (xhr) { alert(xhr.status) }
});

Categories