First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<a href=# id=favorite class=bookmark><img align=right src={{ asset('/img/icon_add_fav.png')}}></a>
<input type=hidden name = idUser id=idUser value={{Auth::user()->id}}>
<input type=hidden name = idArticle id=idArticle value={{$docinfo['attrs']['sid']}}>
<input type=submit id=test value=Ok>
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:post,
url:{{ url('addFavorites') }},
dataType=json,
data:$('#ajax').serialize(),
success: function(data){
alert(Data Save: + data);
}
error: function(data){
alert(Error)
}
});
});
Also in my web.php
I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {status:success,idUser:15,idArticle:343970}
... It actually inserts into the db, but I want the page not to reload. Just to display alert box.