How to configure Parsley remote validator to handle my API response - parsley.js

I have tried all the possible approaches found, but I am struggled to get the default remote validator working.
I'm just trying to achieve to check if the mail for a registration page of a user is duplicated. Thus, I declare the input as follows:
<input type="email" name="email" required
placeholder="Dirección de correo"
data-parsley-trim-value="true"
data-parsley-trigger="change"
data-parsley-remote-options='{ "type": "POST", "dataType": "jsonp" }'
data-parsley-remote="checkmail.php"
data-parsley-remote-message="Mail duplicated"
class="form-control">
The checkmail.php code is:
require_once("../functions/mysqli_connect.php");
if (empty($_POST['email'])){
$errors[] = 'No llega el parametro de mail';
}else {
$email = trim($_POST['email']);
$q = ("select * from register where email ='" . $email . "'");
$r = mysqli_query($dbc, $q);
if ($r) {
if (($r->num_rows) > 0) {
echo json_encode(404);
} else {
echo json_encode(200);
}
}
}
I've tried multiple combinations for echo response, I've read all the messages on stackoverflow but couldn't find the solution because I've always get the message :
This value seems to be invalid.
As I read on another's user question I've tried:
data-parsley-remote-message="Mail duplicated"
but with no luck either.
The PHP code works as expected, so no errors there, but Parsley always treats the json_encode responses as it is was an error.
Any help would be vey appreciated.
Thanks in advance.

Parsley remote validator looks for HTTP response code not for the body content itself. In your example you're returning json data with probably always HTTP 200 status code.
Maybe look here http://php.net/manual/en/function.http-response-code.php or here Set Response Status Code to see how you could change the response status code.
Best

Related

Laravel 8 Request Filled Method Not Working

I am trying to use 'filled' on a POST request using Laravel 8 to determine if a field is blank or not.
<input type="text" name="msg" value="">
The POST array when sent contains data for this or no data, so the POST is working fine.
['msg' => 'data here..']
For a test, I am evaluating the request as follows:
if ($request->filled('msg')) {
echo 'OK';
} else {
echo 'Empty';
}
This always returns OK, regardless of whether the field has data or not. If I log the request array, the fields does indeed contain nothing.
Log:info(print_r($request->all(), true));
So, I guess my question is, how does the 'filled' method work? Am I missing something?
Many thanks.

Error 400 when POST'ing JSON in angularjs + Spark Single Page Application

I'm new to Single Page Application area and I try to develop app using angularjs and Spark framework. I get error 400 bad request when I want to post JSON from my website. Here is code fragment from client side:
app.controller('PostTripCtrl', function($scope, $http) {
$scope.newTrip = {};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:4567/trips/add',
data : $scope.newTrip,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log("ok");
}).error(function(data) {
console.log("error");
console.log($scope.newTrip);
});
};
});
Values that are to be assigned to newTrip are read from appropriate inputs in html file. Here is server-side fragment:
post("/trips/add", (req, res) -> {
String tripOwner = req.queryParams("tripOwner");
String startDate = req.queryParams("startDate");
String startingPlace = req.queryParams("startingPlace");
String tripDestination = req.queryParams("tripDestination");
int tripPrice = Integer.parseInt(req.queryParams("tripPrice"));
int maxNumberOfSeats = Integer.parseInt(req.queryParams("maxNumberOfSeats"));
int seatsAlreadyOccupied = Integer.parseInt(req.queryParams("seatsAlreadyOccupied"));
tripService.createTrip(tripOwner, startDate, startingPlace, tripDestination, tripPrice, maxNumberOfSeats,
seatsAlreadyOccupied);
res.status(201);
return null;
} , json());
At the end I obtain error 400 bad request. It is strange for me that when I want to see output on the console
System.out.println(req.queryParams());
I get json array of objects with values written by me on the website. However, when I want to see such output
System.out.println(req.queryParams("tripOwner"));
I get null. Does anyone have idea what is wrong here?
I think the main problem is that you are sending data to your Spark webservice with the 'Content-Type' : 'application/x-www-form-urlencoded' header. Try sending it as 'Content-Type' : 'application/json' instead, then in your Java code declare a String to receive req.body(), you'll see all your data in there.
Note: When you try to acces your data like this req.queryParams("tripOwner"); you're not accessing post data, but you're seeking for a get parameter called tripOwner, one that could be sent like this http://localhost:8080/trips/add?tripOwner=MyValue.
I would advise using postman to post a request to your server and see if it works. Try a different content type too. Try using curl and play with the various headers you are sending. 400 suggests the wrong data is being sent or expected data is missing or the data is the wrong type but based on your code you've provided I can see nothing wrong (but see below).
When your server receives a request log all request headers being received and see what changing them does. If it works in postman then you can change your client code to mirror the headers postman is using.
Does your spark server validate the data being sent before your controller code is hit? If so ensure you are adhering to all validation rules
Also on looking at your code again your client is sending the data in the post data but your server is expecting the data in the query string and not in the post data?
What happens if your server just sends a 201 response and does nothing else? Does your client get a 201 back? If so it suggests the hook up is working but there is something wrong with the code before you return a 201, build it up slowly to fix this.
Ok, I managed to cope with that using another approach. I used Jackson and ObjectMapper according to Spark documentantion. Thanks for your answers.
You can see more about that here: https://sparktutorials.github.io/2015/04/03/spark-lombok-jackson-reduce-boilerplate.html
You're probably just needed to enable CORS(Cross-origin resource sharing) in your Spark Server, which would have allowed you to access the REST resources outside the original domain of the request.
Spark.options("/*", (request,response)->{
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if(accessControlRequestMethod != null){
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
Spark.before((request,response)->{
response.header("Access-Control-Allow-Origin", "*");
});
Read more about pre-flighted requests here.

cakephp hidden field issue

I have a problem with an input field in a view called add.ctp. When the input type is set to 'text', the program sequence is normal. But when I change the input type to 'hidden', the following error is displayed:
The request has ben black-holed. Error: The requested address was not found on this server.
mod-rewrite seems activated. Any ideas, what can be the reason for this?
There is no error with your code. CakePHP's Security component checks hidden form fields to prevent tampering by end users:
By default SecurityComponent prevents users from tampering with forms. It does this by working with FormHelper and tracking which files are in a form. It also keeps track of the values of hidden input elements. All of this data is combined and turned into a hash. When a form is submitted, SecurityComponent will use the POST data to build the same structure and compare the hash.
Use FormHelper::unlockField to make a field exempt from this feature:
$this->Form->unlockField('User.id');
This means there is an error with your code. Here is how to create hidden textbox
echo $this->Form->input('field_name', array('type'=>'hidden'));
I think It's because you are using SecurityComponent.
THe component monitor the form integrity, the hidden field shouldn't change from the user and because of that the security component "decide" that the something malicious has been done with the form for example CSRF attack and it prevent the submit. And I believe you are having some JavaScript which change the field value for some reason.
CakePHP 3
Please do not unlock fields/disable CSRF security component for any
particular action. This is important for the form security.
for those who are getting "The request has been black-holed."
,"form tampered error", "you are not authorized to access
that location." or "unexpected field in POST data". It is
mainly due to the CSRF component working as expected.
Disabling or modifying it is not a solution. Instead of disabling, please follow the right approach.
The right way should be as below:
On the Form, Add a hidden field as below.
<?= $this->Form->text('TPCalls.ID',['label' => false, 'class' => 'hidden']); ?>
before AJAX add the field
$("input[name='TPCalls[ID]']").val(event.id);
Then serialise it
var el = $("#xyzForm");
var ajaxTPCalls = el.serializeArray();
$.ajax({
type: el.attr('method'),
async: true,
url: el.attr('action'),
data: ajaxTPCalls,
dataType: "json",
cache: false,
success: function (data) {
toastr.success(data.message, data.title);
},
error: function (jqXHR) {
if (jqXHR.status == 403) {
$("body").html(jqXHR.responseText);
}
}
});
This way you do not disable CSRF or unlock any field. Any suggestions welcome.

Backbone not sending PUT to server

I am having trouble with trying to get backbone to send a PUT request out to my rails server on save. I am not sure what I am doing wrong here, it is fine with GET requests just not PUT..
Here is the code that is in my view that I use to save my model.
e.preventDefault()
$(#el).find('#error_explanation').html ""
data = Backbone.Syphon.serialize(this)
setError = false
#model.set(data, error: (model, error) ->
setError = true
)
#model.save()
Any help would be greatly appreciated.
Thanks,
-do
Stupid me....
Here is what was in my model.
validate: ->
console.log "validating"
console.log "options: #{options}"
errors = []
if(!#.validateEmail(#.get('email')))
errors.push("Email can't be blank")
if(!#.validateName(#.get('first_name')))
errors.push("First name can't be blank")
if(!#.validateName(#.get('last_name')))
errors.push("Last name can't be blank")
return errors
This was actually being called when I was trying to save it which I was just trying to call manually. Since I wasn't returning the correct data saying that it was valid/invalid it just was always invalid.
ooops...
-do

CakeEmail: no render Flash Message

In CakePhp 2.0, using CakeEmail new Component seems to not output flash message:
In my controller I put:
$email = new CakeEmail(array('log'=>true));
$email->transport('Debug');
and in my view
echo $this->Session->flash('email');
But nothing is printed out.
Has that function (flash) been removed in 2.0?
none of the cake email libs or components or transport classes touch the session or write any such flash content. they never did as far is I know.
but they return the email content as array for the DebugTransport.
so you would want to fetch the returned array and log it away:
$res = $this->Email->send();
$this->Session->setFlash($res ? 'Email sent' : 'Email not sent');
or sth like that.
Of course there is flash function in cakephp 2.0 for details check it here: http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html
If you want to get ur flash message in your view you have to first set it in your Controller action.
//controller
$this->Session->setFlash('email');
//view
echo $this->Session->flash();
// The above will output.
<div id="flashMessage" class="message">
'email'.
</div>
In Cake 2.x the debug transport doesn't set the email content in session. Just check the return value, $contents = $email->send();. $contents will contain the headers and message so use them as required.
$response = $Email->send();
$response['headers']; // headers as string
$response['message']; // message body with attachments
$this->Session->setFlash($response['headers'].$response['message']);
Make sure you have the following in your layout file.
echo $this->Session->flash();

Resources