Answer the question
In order to leave comments, you need to log in
Why after ajax request redirects to another page?
Hello. There are three questions that I would like you to help sort out.
1) Because of what success can work first, and immediately after it error? For the sake of the test, success and error indicated alert, which worked one after another.
2) After executing the ajax code below, redirects to another page. the console says "Navigated to cms/admin/edit/post/3 ". What could be causing this?
3) Why does ajax with datatype: "JSON" work if Response::json(['success' => 'good']) is passed to it, but if json_encode(['success' => 'good']) is passed, then Nothing happens. What is the difference and why is this happening?
Read that Response::json() additionally passes Content-Type
form class="form-newCat" action="{{route('categoryStore', $post->id)}}" method="post">
<label for="">Название новой рубрики</label>
<input type="text" name="nameCategory">
{!! csrf_field () !!}
<button class="newCat" type="submit">Добавить новую рубрику</button>
</form>
$('.newCat').click(function () {
var data = $('.form-newCat').serializeArray();
$.ajax({
url: $('.form-newCat').attr('action'),
data: data,
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
datatype: "JSON",
success: function (html) {
if (html.success) {
$('.wrap_result').
text('Заявка отправлена!')
}
},
error: 'Ошибка'
})
Route::group(['prefix' => 'admin'], function () {
Route::get('/adminPanel', function (){
return view('admin/adminPanel');
});
Route::get('/posts', 'admin\[email protected]')->name('posts');
Route::get('/edit/post/{id}', 'admin\[email protected]')->name('post');
Route::get('/delete/post/{id}', 'admin\[email protected]')->name('delete');
Route::post('/edit/post/{id}', 'admin\[email protected]')->name('categoryStore');
});
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use App\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class CategoriesController extends Controller
{
public function store ()
{
return Response::json(['success' => 'good']);
}
}
Answer the question
In order to leave comments, you need to log in
before var data = $('.form-newCat').serializeArray(); write event.preventDefault();
You have a standard submit that works and redirects to the route that is specified in the form action
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question