user3732216 user3732216 - 18 days ago 6
Ajax Question

Laravel app with ajax json return issues error

My question is I have my page submitted however what I'm trying to do is have it submit back and display any errors that might have been from the validation underneath the proper form field. As of right now I am also getting this error in my console.

If you are willing to look through the little bit of code see if there's anythign suggested for a change to improve upon it.

"NetworkError: 405 Method Not Allowed - http://myapp.app/createorderfromform"
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

var err = JSON.parse(xhr.responseText);



$("#pageOneSubmission").click(function(event) {
event.preventDefault();
var email = $("input[name=email]").val();
var addons = [];
$('.addon-checkbox:checked').each(function() {
addons.push( $(this).val() )
});

$.ajax({
type: "POST",
url: '{{action('OrderProcessController@createUserAndOrder') }}',
data:
{
email: email,
addons: addons
},
dataType: JSON,
success: function(data) {
if (!data.success) {
console.log("Errors");
} else {
console.log("No Errors");
$("#user-created-confirmation").html(data);
}
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
$.each(err, function(key, value) {
$('input [name=key]').next().append("<p>Test</p>");
});
}
}, function(){
setTimeout(function() {

})
});
});


OrderProcessController

<?php

namespace App\Http\Controllers;

use App\Order;
use Illuminate\Http\Request;
use Sentinel;


class OrderProcessController extends JoshController
{
/*
* Create User After they complete the first part of the form.
*
*/
public function createUserAndOrder(Request $request)
{
$validation = $this->validate($request, [
'email' => 'required|confirmed|unique:users,email',
]);

$credentials = [
'email' => $request->input('email'),
'password' => $request->input('password'),
];

$user = Sentinel::registerAndActivate($credentials);

$user->role()->attach(5);

return response()->json([
'success' => true,
'errors' => null
]);
}
}


UPDATE:

I have fixed my route issue however I'm trying to figure out how to keep it from moving onto the next page in the form wizard if there is a validation error with one of the form fields that is being passed. Because when the user comes to the first page of the form and don't fill out any of the fields it should return with the errors. So I'm trying to figure out with the validation how to pass it back with the errors to the ajax request so that it can display the corresponding errors next to the input field.

Answer

405 Method Not Allowed exception indicates that a route doesn't exist for the HTTP method you are requesting.

Make sure your route is a post request.

Comments