Laravel 5.2 : How to post and delete data Using Ajax? - javascript

I want to post some data using Ajax and I also want to delete some data using Ajax.
But the problem is while inputting the data, data posted in database. But My UI faces some problem, after saving the data, my save Button always clicked. But as I'm using Ajax, it shouldn't load or previous data should automatically vanish.
Same as for deleting also, while deleting data get deleted, but it's redirecting to another page?
How do I solve the problem?
Here is my UserController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Http\Response;
use App\User;
use App\Post;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller {
public function postSignUp(Request $request) {
$this->validate($request, [
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'password' => 'required|min:4'
]);
$user = new User();
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
if ($request->ajax()) {
return response()->json();
}
}
public function delete(Request $request, $id) {
$user = User::find($id);
$user->delete($request->all());
}
}
?>
Here is my Post data View page:
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity = "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin = "anonymous">
</head>
<body>
<script src = "https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div class="container">
<h2>Register Form</h2>
<div class="row col-lg-5">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="Email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="send(event)" class="btn btn-default" >Submit</button>
</div>
</div>
<script type="text/javascript">
function send(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "{{route('signup')}}",
data: {name: $("#name").val(),
email: $("#email").val(),
password: $("#password").val(),
_token: '{!! csrf_token() !!}'
}
});
}
</script>
</body>
</html>
Here is my delete data view page:
<html>
<head>
<title> User Details </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container">
<h3> User Details </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>User Name</td>
<td>User Email</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach($user as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->email}}</td>
<td>
Edit
<div id="deleteTheProduct">
{!! Form::open([
'method' => 'POST',
'action' => ['UserController#delete',$row->id],
'style'=>'display:inline'
]) !!}
{!! Form::hidden('id',$row->id)!!}
{!! Form::submit('Delete',['class'=>'btn btn-danger deleteUser','id' => 'btnDeleteUser', 'data-id' => $row->id]) !!}
{!!Form::close()!!}
</div>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$('.deleteUser').on('click', function (e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url(' / delete') }}'
+ '/' + dataId,
method: 'POST',
data: inputData,
success: function (data) {
console.log(data);
}
});
});
</script>
</body>
</html>

to prevent redirect problem just make .delete button as button not submit, I think this will fix your problem, if not please inform me,
to delete row please make following changes on your script code... first is yours code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
}
});
});
have some changes in above code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
// added code is
$object=$(this);
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
//if success status is successful and below code removes the parent row from the table
$($object).parents('tr').remove();
}
});
});

But as I'm using Ajax, it shouldn't load or previous data should automatically vanish
You will have to control that yourself, ajax is like a request to web server without reloading the page (or navigating) but the browser doesn't know what action to make after the ajax request. as you are using jQuery you can update your UI after Ajax request in success callback.
try for example returning the id of deleted object and in ajax success function.
success: function(data) {
jQuery('#'+data.id).remove();
}

Related

ajax is not working in Laravel showing page not found

I want to send OTP with Laravel and ajax but when i'm calling ajax it shows error page not found...
HTML:
`
<div id="first_step">
<div class="col-md-4">
<input value="+91" type="text" placeholder="+1" id="country_code" name="country_code" />
</div>
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
`
script:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
var host = "{{URL::to('/')}}";
alert(host);
$.ajax({
type: "POST",
url: host+"/send_otp",
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
}); });
Route in web.php:
Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function');
//Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function'); also try this
Controllers:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response);
}
Welcome to SO. As far as I understand and according to jQuery.ajax documentation you have forgotten to set datatype='json' in your ajax request. Your request should be:
$.ajax({
type: "POST",
url: host + "/send_otp",
datatype: 'json',
data: {
name: phone_number
},
success: function(msg) {
alert(msg);
},
error: function(request, status, error) {
alert(request.responseText);
}
});
I see a few things that could be throwing the error.
You are prepending the ajax url to post to with the variable host. It's not needed, you should try it this way:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
As per Laravel documentation (https://laravel.com/docs/5.8/responses), you can return json responses like the below:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return response()->json($response);
}
You should be sending the csrf token with your post:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {
_token: {{ csrf_token() }}, //csrf token
name:phone_number
},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
HTML :
<!DOCTYPE html>
<html>
<head>
<title>Ajax Dynamic Dependent Dropdown in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
.box{
width:600px;
margin:0 auto;
border:1px solid #ccc;
}
</style>
</head>
<body>
<div id="first_step">
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" id="phone_number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
{{ csrf_field() }}
</body>
</html>
<script>
$(document).ready(function(){
$('#send_otp_button').on('click', function(e) {
var select = $('#phone_number').val();
alert(select);
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, _token:_token},
success:function(result)
{
alert(result);
}
})
});
});
</script>
Web.php(Route File)
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/dynamic_dependent', 'DynamicDependent#index');
Route::post('dynamic_dependent/fetch', 'DynamicDependent#fetch')->name('dynamicdependent.fetch');
?>
//DynamicDepdendent.php (Controller)
<?php
//DynamicDepdendent.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$response = $request->get('select');
echo $response;
}
}
?>

Adding data to database using ajax jquery in laravel

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class categorycontroller extends Controller
{
public function display()
{
$cat=Category::all();
return view ('category',['cat'=>$cat]);
}
public function add(Request $request)
{
Category::create([
'Name' =>$request->name
]);
return response()->json(['success'=>'Data is successfully added']);
}
}
Route::get('/category','categorycontroller#display');
Route::get('/category/add','categorycontroller#add');
#extends('layout1')
#section('content')
<form id="myform">
<div class="form-group">
<!--<label for="name">Name :</label>-->
<table class="table table-bordered">
<thead><tr><th>Category</th><th colspan="2" align="center">Action</th></tr></thead>
<tbody>
</div>
#foreach($cat as $c)
<tr id='cat_{{$c->id}}'>
<td><input type="text" class="form-control" id="name_{{$c->id}}" value="{{$c->Name}}"></td>
<td><button class="btn btn-primary" id="btnupdate_{{$c->id}}" onclick="updatecat({{$c->id}})">Update</button></td>
<td><button class="btn btn-primary" id="btndelete_{{$c->id}}" onclick="deletecat({{$c->id}})">Delete</button></td>
</tr>
#endforeach
</tbody>
<tr><th colspan="2">New Category</th></tr>
<tr><td>
<div class="form-group">
<input type="text" class="form-control" id="name_0" value="">
</div>
</td>
<td>
<button class="btn btn-primary" id="btnadd">Add</button>
</td>
</tr>
</table>
</form>
<script type="text/javascript" src="{{asset('js/jquery.js')}}"></script>
<script>
$(document).ready(function(){
$("#btnadd").on('click',function(e){
e.preventDefault();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN':$('meta[name="_token"]').attr('content');
}
});
$.ajax({
url:"{{url('category/add')}}",
method:'get',
data:{
name:$('#name_0').val()
},
success:function(result)
{
$('.alert').show();
$('.alert').html(result.success);
//$('#tbcat').append(result.row);
}
});
});
});
</script>
#endsection
I write this code to display categories in the table from the database, it worked successfully. then I added ajax jquery code to add category to the database and display it after added to the table in the form. I wrote my codes in a blade.php and in the route and I used class category and category controller but when I click add button it's doesn't work successfully. Please can anyone help me to correct the error
h
In your resources/views/layouts folder, the main layout file should have those two elements to prevent CSRF attacks.
<!DOCTYPE html>
...
<meta name="csrf-token" content="{{ csrf_token() }}"/>
...
</head>
<body>
...
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
});
</script>
...
</body>
Also you need to remove this second part ($.ajaxSetup) from your onclick event handler. so it looks like this:
<script>
$(document).ready(function(){
$("#btnadd").on('click',function(e){
e.preventDefault();
$.ajax({
url:"{{url('category/add')}}",
method:'get',
data:{
name:$('#name_0').val()
},
success:function(result)
{
$('.alert').show();
$('.alert').html(result.success);
//$('#tbcat').append(result.row);
}
});
});
});

VerifyCsrfToken Exception on form submit after AJAX response

I have AJAX action which renders a form which contains several input fields and submit button.
This is AJAX call:
<script type="text/javascript">
$('#call_filter').click(function() {
$.ajax({
url : 'brandSpendingsFilter',
type: 'POST',
data: {company: $('#company').val(), country: $('#country').val(), dateFrom: $('#dateFrom').val(), dateUntil: $('#dateUntil').val(), media: $('#media').val(),
products: $('[id^=products_]').serialize()},
beforeSend: function() {$('#search_result').empty(); $("#loading-image2").show(); },
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
},
success : function(data) {
$("#loading-image2").hide();
$('#search_result').append(data);
}
});
});
</script>
And my form:
{!! Form::open(['url' => 'brandSpendingsCSV', 'method' => 'POST', 'id' => 'csv']) !!}
{{ csrf_field() }}
<input type="hidden" name="campaignID" value="#foreach($campaignID as $c){{$c}},#endforeach">
<input type="hidden" name="dateFrom" value="{{$dateFrom}}">
<input type="hidden" name="dateUntil" value="{{$dateUntil}}">
<input type="hidden" name="media" value="{{$media}}">
<input type="hidden" name="country" value="{{$country}}">
</tr>
</table>
#if(Auth::user()->isAdmin())
<div class="row" style="float: right;"><button type="submit" onclick="submitForm()" class="btn btn-warning">CSV EXPORT</button></div>
#endif
<br>
<br>
{!! Form::close() !!}
This onclick function is simple submit code:
<script type="text/javascript">
function submitForm(){
$('#csv')[0].submit();
}
</script>
As you can see from the form code I have already included the csrf field. But still after this I am getting an error VerifyCsrfException.
Another thing that I have tried is to include AJAX headers:
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
</script>
But still error remains. Any suggestions?
EDIT
I changed route type to GET and added this
<button class="btn btn-warning">CSV EXPORT</button>
It works at the moment, but I'll keep the question open since this is temporary solution. I need to have POST method.
You are creating token in page by usign {{ csrf_field() }}, so you can use as
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
or add an element named _token to post data
var _token = $('input[name="_token"]').val();
data: {_token:_token,company: $('#company').val(),
Also calculate value campaignID before textbox or at the top of page
Add to rest of data the token:
data: {
"_token": "{{ csrf_token() }}"
}
Cheers!
With the jQuery serialize() method the token posted with all others form data.
data: $(this).serialize(),

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

Laravel 5.2:How to show validation errors when submitting form with ajax?

I am using laravel 5.2,my question is:
How to show validation errors when submitting form with ajax ?
For example:
When ajax is not used,if the title field is not filled in, when submitting,there is an information :
"The title field is required."
And, when ajax is used,how to show the information above.
View:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/tether/1.1.1/css/tether.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form id="formArticle" class="form-horizontal" role="form">
<fieldset class="row form-group">
<label class="col-xs-2 control-label">Title:</label>
<div class="col-xs-10">
<input id="title" name="title" type="text" class="form-control"
value="{{ old('title') }}">
<span class="help-block"><strong></strong></span>
</div>
</fieldset>
<fieldset class="row form-group">
<label class="col-xs-2 control-label">Content:</label>
<div class="col-xs-10">
<input id="content" name="content" type="text" class="form-control"
value="{{ old('content') }}">
<span class="help-block"><strong></strong></span>
</div>
</fieldset>
<fieldset class="row form-group">
<label class="col-xs-2 control-label" for="photo">Photo:</label>
<div class="col-xs-10">
<input id="photo" name="photo" type="file" class="form-control-file">
<span class="help-block"><strong></strong></span>
</div>
</fieldset>
<fieldset class="form-group">
<div class="col-xs-12">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
<div class="alert alert-success" role="alert" hidden>
upload successfully
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/tether/1.1.1/js/tether.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>
</body>
</html>
Javascript:
<script>
$(function () {
var articleData = new FormData($('#formArticle')[0]);
$(document).on('submit', '#formArticle', function (e) {
e.preventDefault();
$('input+span>strong').text('');
$('input').parent().parent().removeClass('has-error');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{ url('article/') }}",
dataType: 'json',
processData: false,
contentType: false,
cache: false,
data: articleData
})
.done(function (data) {
$(".alert-success").prop("hidden", false);
})
.fail(function (data) {
$.each(data.responseJSON, function (key, value) {
var input = '#formArticle input[name=' + key + ']';
$(input + '+span>strong').text(value);
$(input).parent().parent().addClass('has-error');
});
});
});
});
</script>
Controller:
public function store(Requests\StoreArticleRequest $request)
{
$article = new Article;
$article -> user_id = \Auth::id();
$article->title = $request->title;
$article->content = $request->content;
$photo = $request->photo;
$destinationPath = 'uploads/';
$extension = $photo->getClientOriginalExtension();
$photoName = \Auth::user()->id . '_' . time() . '.' . $extension;
$photo->move($destinationPath, $photoName);
$article -> photo = '/'.$destinationPath.$photoName;
$article->save();
}
StoreArticleRequest:
public function rules()
{
return [
'title'=>'required',
'content'=>'required',
'photo'=>'required'
];
}
Form data can be saved to database successfully if inputs are filled in completely.
But, when they are not filled in completely,or filled in nothing,
json message is shown in Chrome debugger's Preview and Response tags, like this:
{
"title":["The title field is required."],
"content":["The content field is required."],
...
}
But, the message can not be shown in html.
And ,at this time,".alert-success" is shown.
I don't know where the problems are in my code.
I think my understanding to done() and fail() is not right.
done() and fail() mean that ajax request is done or failed,
but not validation successful or failed,
no matter validation of laravel is successful or failed,
ajax request is done,
so,
even though I don't complete the inputs,
div class="alert alert-success" always appears .
You're getting the success message because done() is fired when a "good" response is received. While you're getting error messages, the actual response from the server is still a 200.
You'd want to check the data in done() to make sure it isn't an error. If title === "The title field is required.", you'd want to run the code that is currently in your fail().
.done(function (data) {
if(data.title[0] == 'The title field is required.' ) {
alert('Title is required');
}
else {
$(".alert-success").prop("hidden", false);
}
})
.fail(function (data) {
alert('The server failed somewhere');
});
Obviously, you'd want to do something other than alerts, and you'd want to check both fields, but that's the gist of it.

Categories

Resources