Consume php ajax POST call for registration
How to get all error responses like password dismatch or password not more than 6 chars. or email is invalid.
My ajax:
- // process the form
- $('#employer').click(function(e) {
- // get the form data
- // there are many ways to get this data using jQuery (you can use the class or id also)
- //Personal account
- var image = $("#avatar").val();
- var first_name = $('#first_name').val();
- var last_name = $('#last_name').val();
- var email = $('#email').val();
- var password = $('#password').val();
- var password_confirmation = $('#password_confirmation').val();
- var gender = $("#option:checked").val();
- //Business
- var logo = $("#logo").val();
- var business_name = $('#business_name').val();
- var business_email = $('#business_email').val();
- var business_phone = $('#business_phone').val();
- // process the form
- $.ajax({
- type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
- url : 'routes/signasemployer.php', // the url where we want to POST
- data: {
- //Personal account
- 'image' : image,
- 'first_name' : first_name,
- 'last_name' : last_name,
- 'email' : email,
- 'password' : password,
- 'password_confirmation' : password_confirmation,
- 'gender' : gender,
- //Business
- 'logo' : logo,
- 'business_name' : business_name,
- 'business_email' : business_email,
- 'business_phone' : business_phone
- },
- dataType:'JSON',
- success: function(data) {
- //data = jQuery.parseJSON(data);
- console.log(data);
- // here we will handle errors and validation messages
- if (data.success == false) {
- console.log(data.success);
- // handle errors for password ---------------
- if (data.data.password) {
- $('#password').addClass('has-error'); // add the error class to show red input
- $('#password').append('<div class="help-block">' + data.data.password + '</div>'); // add the actual error message under our input
- }
- // handle errors for email ---------------
- if (data.data.email) {
- $('#email').addClass('has-error'); // add the error class to show red input
- $('#email').append('<div class="help-block">' + data.data.email + '</div>'); // add the actual error message under our input
- }
- } else {
- console.log(data.data.password);
- // ALL GOOD! just show the success message!
- $('form').append('<div class="alert alert-success">' + data.message + '</div>');
- //window.location = 'home.php';
- }
- }
- });
- // stop the form from submitting the normal way and refreshing the page
- e.preventDefault();
- });
My api response: if password too short and if doesn't match:
- {
- success: "false",
- message: "Validation Error.",
- data: {
- password: ["The password must be at least 6 characters.", "The password confirmation does not match."]
- }
- }