Laravel API call form validation not working - laravel

I'm working with Laravel API and calling an API method in two different way. In one-way form validation working but in second-way form validation not working. But I really need second-way of API call.
saveMember: function () {
let that = this;
let formData = new FormData();
formData.append('member_info', that.member_info);
// member_info is a Json Object
// This is First way , form validation working good while calling Api
axios.post('/api/member/save_member', that.member_info)
// This is second way, form validation not working
axios.post('/api/member/save_member', that.formData)
.then(function (response) {
console.log("response Here: " + response.data.success);
that.errors = response.data.success;
// location.reload(true);
})
.catch(function (error) {
that.errors = error.response.data.errors;
console.log("Error Here: " + error.response.data);
});
}
Doing form validation in Laravel Request Controller.

Look like Json Object can send to API.
I missing your error when request call to fixed.
But i think you need convert FormData to Json Object:
var obj = {};
that.formData.forEach(function(val, idx){
obj[idx] = val;
});
var json = JSON.stringify(obj);
and then resend:
axios.post('/api/member/save_member', json)
...

Related

Meteor call for sending image through api

Is it is possible to send image through meteor call to the API?
Client js
var r = {image : image};
Meteor.apply('callToServer', r, function(error, result){
console.log(result);
});
Server js
Meteor.methods({
uploadAndSaveToDB: function(data){
var result = Meteor.http.post(apiUrl, {
params: { image : data['image']}
});
var result = JSON.parse(result.content);
return result;
},
});
If your question is about how to get the image data and send it to your api, it depends on a couple factors:
How are you getting the image's data in the first place from your app (a submission form, a URL, some drawing library...)
In what format does the API you are calling expects the image data to be sent (URL, raw data, encrypted...)
If you are simply asking if it is doable, then yes, definitely. You will just need to add the http package for this:
meteor add http
You can then make requests to your api pretty much like you wrote it. Just make sure to give the right name to your method call (also use call and not apply if you are not submitting an array of arguments):
Client js
var r = {image : image};
Meteor.call('uploadAndSaveToDB', r, function(error, result){
console.log(result);
});
Server js
Meteor.methods({
uploadAndSaveToDB: function(data){
var result = HTTP.post(apiUrl, {
params: { image : data['image']}
});
var result = JSON.parse(result.content);
return result;
},
});

How I can catch and save to file data from form sended by AJAX in ColdFusion

I have the followign JavaScript code:
function upload(blob) {
var xhr = new XMLHttpRequest();
var url = "test.cfm";
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("randomname",blob);
xhr.open("POST",url,true);
xhr.send(fd); }
How can I catch it on server side by ColdFusion and Save blob object to File?
Can someone please some code sample. Thx.
PS. I am pretty new in CF.
Since you are using formdata, you can access the form variable with ajax, just like you would with normal http requests.
#form.randomname#
#form['randomname']#
So you could save the content in a file with
<cfscript>
fileWrite( 'c:\myfile.txt', form.randomname );
</cfscript>

Cannot submit form with supertest and mocha

I am using supertest and mocha to test a nodejs application. One of the things users can do is to submit a very simple form, which is picked up by the node server and parsed using formidable.
Here is the mocha test code:
var should = require('should'),
express = require('express'),
app = require('../app.js'),
request = require('supertest'),
csrfToken,
sessionId,
cookies = [];
describe('Post Handler', function(){
it('Uploads new post', function(done){
var req = request(app).post('/post?_csrf=' + csrfToken);
req.cookies = cookies;
req
.type('form')
.send({fieldTitle: 'autopost'})
.send({fieldContent: 'autocontent'})
.send({contentType: 'image/png'})
.send({blobId: 'icon_23943.png'})
.expect(200)
.end(function(error, res){
console.log('here');
done();
});
});
csrfToken retrieves a csrf token from the server, since I am using the csurf module and every POST method requires a csrf token. cookies stores the session cookie that is provided by the node server so I can persist the session between requests.
The form is processed by the following code:
//Takes HTTP form posted by client and creates a new post in the Db
exports.postPostUpload = function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
console.log(err);
if (err) res.redirect(303, '/error');
else {
var new_post = new post_model.Post().createNewPost(fields);
new_post.setUserId(req.session.passport.user.userId);
new_post.uploadPostToDb(function (error, result) {
if (error) return res.status(500).end();
else {
if (new_post.media.contentType.indexOf('video') !== -1) {
addMessageToEncodingQueue(new_post, function (error, result, response) {
if (error) {
errorHelper.reportError({
stack: new Error().stack,
error: error
});
res.status(500).end();
}
else res.status(200).send(new_post.cuid);
});
}
else return res.status(200).send(new_post.cuid);
}
});
}
});
}
My current problem is, that once the form handler executes the line form.parse(req, function (err, fields, files) {, nothing happens. Formidable does not return error, it just does not return anything. Consequently, the mocha test never receives a reply from the server, and eventually the socket hangs and the test crashes. Needless to say, the form is successfully submit if you do it manually via the website.
There must be an error in the way supertest/mocha are executing this test, but I have not been able to find it. Any pointers are highly appreciated.

dojo ajax request to spring mvc,getting http 400

before starting let me say that I am new to dojo and this is my first project in dojo:
when I am trying to send json data from rest client (some chrome ext) it working for me,I mean to say that my spring mvc part is working, but when i am trying to send the same json from dojo code I am getting http 400 exception
my dojo code:
postCreate : function() {
this.inherited(arguments);
var form = dom.byId("contactSubmit");
on(form, "click", function(evt) {
var box0 = registry.byId("inputEmail");
var box1 = registry.byId("inputName");
var box3 = registry.byId("message");
alert("values are: " + box0.get("value"));
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
request.post("/pool/conta", {
data: jsonData,
handleAs: "json",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
}
}).then(function(text){
alert("values are send"+text);
});
});
}
the jason data that I am sending from rest client is which is working:
{"email":"some#gmail.com","inputName":"some name","message":"some msg"}
my spring mvc method is below:
#RequestMapping(value="/conta", method = RequestMethod.POST)
public #ResponseBody Contact getShopInJSON(#RequestBody Contact contact2) {
Contact contact = new Contact();
contact.setEmail("pro#gmail.com");
contact.setInputName("pro");
contact.setMessage("msg");
System.out.println("***********************"+contact2.getEmail());
return contact;
}
pool is name of application
The json data as passed in post request requires string to be crypted with "\" so that the javascript can handle the double codes as is within string(double quoted string).
Thus, the line
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
would work if written as below
jsonData = " {\"email\":\"some#gmail.com\",\"inputName\":\"some name\",\"message\":\"some msg\"} " ;
Its working now, I have used toJson from dojo/_base/json" utility before passing it to request.post

jquery template not rendered from ajax data

Below code works if I hardcode the json string, however if I pass the json string returned from ajax call to render the template, it does not work. Please help me to find the issue.
function getData(orgId){
$.template("EmployeeTemplate","<tr><td colspan='2'>${name}</td>
<td colspan='2'>${id}</td> <td colspan='2'>${jobTitle}</td></tr>");
var gUrl = "/JQueryMobileApp/HRServlet?action=employee&orgId="+orgId;
// Do the ajax call
$.ajax({
url: gUrl,
dataType:'json',
// Callback (onsuccess)
success: function(d){
var jsonData = eval( d);
var nameText=jsonData.empNames;
//nameText=[{name:"abc",id:"1"},{name:"pqr",id:"2"}];
$.tmpl( "EmployeeTemplate", nameText ).appendTo( "#employeeList" );
alert(nameText);
},
// Error handler
error: function(req, status, err){
alert('error getting name');
var group_list = document.getElementById("orgTree");
}
});
}
code on the server side:
PrintWriter out = response.getWriter();
response.setContentType("application/json");
JSONObject obj1=new JSONObject();
if(request.getParameter("action").equals("employee")){
String orgId=request.getParameter("orgId");
List<EmployeeVO> name=access.getEmployeeListInOrganization(orgId);
Gson gson = new Gson();
String json=gson.toJson(name);
obj1.put("empNames",json);
out.print(obj1);
out.flush();
}
I am using the same approach to fill a text box with the name of employee returned from ajax call and I am seeing that its being populated. However if the return type is a json array I am not able to display it. Display logic is correct as if I hardcode the json array I am able to see the list and table. Response code is success, the logic is not going in to error condition.
resolved the above issue by using var obj = jQuery.parseJSON(nameTex);

Resources