I'm completely stuck trying to process a form submit using ajax instead of laravel to avoid page reload etc. But it isn't working and I don't know why. I've searched the wonderful web going through example after example but nothing seems to be working for me. This is the closest I can get. My knowledge is limited but my ambitions are high. Please take a moment and look through my code, beacuse I'm at the edge of mental breakdown right now.
Here is my jquery:
$(document).ready(function() {
$('#ajax').submit(function(event){
$.ajax({
type: 'POST',
url: 'comments',
data: $('form#ajax').serialize(),
dataType: 'json',
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
And here is my form in blade view:
{{ Form::open(array('url'=>'comments', 'id' => 'ajax')) }}
{{ Form::hidden('parent_id', null) }}
{{ Form::hidden('author', Auth::user()->username) }}
{{ Form::textarea('content', null, array('placeholder' => 'Enter your comment here:', 'onfocus' => 'this.placeholder=""')) }}<br/>
{{ Form::submit('Comment', array('class'=>'submit')) }}
{{ Form::close() }}
And here is my controller:
public function createComment() {
//fixa här så man inte kan kommentera tom kommentar
$validate = array('content' => 'required');
$validator = Validator::make(Input::all(), $validate);
if($validator->fails()) {
return Redirect::to('comments')->withErrors($validator)->withInput(Input::all());
}
else {
$comment = new Comment();
$comment->parent_id = Input::get('parent_id');
$comment->author = Input::get('author');
$comment->content = Input::get('content');
$comment->save();
}
}
public function postComment() {
if(Request::ajax()) {
$this->createComment();
return Response::json(Input::all());
}
}
public function getCommentsAndForm() {
$comments = Comment::orderBy('id')->get();
return View::make('comment')->with('comments', $comments);
}
And here is my routes:
Route::get('comments', array('uses' => 'CommentController#getCommentsAndForm'));
Route::post('comments', array('uses' => 'CommentController#postComment'));
When I submit the form it dissapears and nothing displays. If I remove if(Request::ajax()) the comments get posted but the form still dissapears and instead of an empty page I get the posted comment in JSON. And when I reload the page the comments shows as I want to.
What is the problem? What am I doing wrong? I only want the posted comment to display above my form without reloading the page, is there a solution?
$(document).ready(function() {
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'comments',
data: $('form#ajax').serialize(),
dataType: 'json',
})
.done(function(data) {
console.log(data);
});
//just to be sure its not submiting form
return false;
});
});
the important here is to prevent form from submiting. You can try to change submit to button.
Related
I'm following this tutorial: https://www.youtube.com/watch?v=D4ny-CboZC0
I've done everything, but at the time of testing I get the following error in the console:
jquery.min.js:2 POST
http://apr2.test/admin/posts/%7B%7B%20('autocomplete.fetch')%20%7D%7D
404 (Not Found)
One thing I'm doing different is that I want that search functionality inside my page of post creation, not an exclusive one, so my routes are like this:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'auth'], function () {
Route::get('/', 'AdminController#index')->name('admin');
Route::get('posts', 'PostsController#index')->name('admin.posts.index');
Route::get('posts/create', 'PostsController#create')->name('admin.posts.create');
Route::post('posts/create', 'PostsController#fetch')->name('autocomplete.fetch');
Route::post('posts', 'PostsController#store')->name('admin.posts.store');
});
My JS/jQuery code:
// A $( document ).ready() block.
$(document).ready(function () {
$('#country_name').keyup(function () {
var query = $(this).val();
if (query != '') {
var _token = $('input[name="_token"]').val();
$.ajax({
url: "{{ ('autocomplete.fetch') }}",
method: "POST",
data: {
query: query,
_token: _token
},
success: function (data) {
$('#countryList').fadeIn();
$('#countryList').html(data);
}
});
}
});
$(document).on('click', 'li', function () {
$('#country_name').val($(this).text());
$('#countryList').fadeOut();
});
});
What's going wrong?
I think the problem is coming from the blade where you are using the route name as %7B%7B in a url is translated to {{.
Please double check you're using the right code there, or in the action tag in your form element: {{ route ("autocomplete.fetch") }} and it's not being lost by some quotes.
im having problems trying to send a JSON file from javascript to Laravel controller, when i press my button from the view i didnt get any response.
This is my code, i appreciate any help or suggestion, thnks.
This is the the JS code:
var horarios= { Lunes: arrLunes, Martes: arrMartes, Miercoles: arrMiercoles, Jueves:arrJueves, Viernes:arrViernes};
var schedule = JSON.stringify(horarios);
//console.log(schedule);
var varurl= 'http://localhost/registerEntrance';
$.ajax({
type: "POST",
url: varurl,
data: {json:schedule},
dataType:'json',
success: function(res) {
var message = res.mesg;
if (message) {
$('.flash').html(message).fadeIn(300).delay(250).fadeOut(300);
};
}
});
When i press my button, doesnt happend anything. The next id the route and the controller code, the JSON file not arrive there yet.
Route::post('registerEntrance', array('as' => 'registerEntrance','uses' => 'CursoController#regisEnt'));
public function regisEnt(){
if(Request::ajax()) {
$data = Input::all();
return $data;
}
}
Thnks for any help.
What are you using to debug your requests? Have you checked your storage/logs/framework/laravel.log (if your log is HUGE you can always delete it and re-run your request)
Working with AJAX can get tricky when it comes to debugging your requests.
My recommendation would be
Open up your browser Inspector, and monitor Network Requests
Analyze the request you're sending.
Set debug to true under config/app.php to actually see a debug
Hope this helps!
I get resolv my problem, i post it if someone is getting a similar inconvenience.
In my view i wasnt create a form.
{!! Form::open(['route' => ['route'], 'method' => 'POST', 'id' =>'form-name']) !!}
{!! Form::close() !!}
This part create a implicit token that is necesary in laravel for use ajax method.
My code JS was modified for getting and send the csrf token.
var form = $('#form-name');
var myurl = form.attr('action');
crsfToken = document.getElementsByName("_token")[0].value;
$.ajax({
url: myurl,
type: 'POST',
data: {data:data},
datatype: 'JSON',
headers: {
"X-CSRF-TOKEN": crsfToken
},
success: function(text){
bootbox.dialog({
closeButton: false,
message: "Ok!",
title: "Perfect!!",
},
error: function(data){
console.log("Error");
}
});
With this change i get arrive to my controller.
Anyway Thnks.
I made an ajax code to send the form data to the controller but it's returning source code instead.
I am using FOSJsRoutingBundle to generate my route in my js code (i installed and used it like the doc said), this is working and return this when it's call on my js
/xampp/folder/web/app_dev.php/chat/
I render my form in twig like this
{{ form_start(form, {'action': '{{ path("chat_page") }}', 'method': 'POST'}) }}
{{ form_widget(form) }}
<input type="submit" value="Send">
{{ form_end(form) }}
My js code look like this
$('form').submit(function(event) {
event.preventDefault();
var url = Routing.generate('chat_page');
console.log(url);
console.log($('#chat_message').val());
$.ajax({
url: url,
type: $('form').attr('method'),
data: $('#chat_message').val(),
success: function(data){
console.log(data);
}
});
$('#chat_message').val('').focus();
});
My controller (probably not used when ajax is done) is this one
/**
* #param Request $request
* #Route("/chat/", name="chat_page", options={"expose"=true})
*
* #return \Symfony\Component\HttpFoundation\Response
*/
public function indexAction(Request $request)
{
$chatForm = $this->createForm(ChatType::class);
$client = $this->get('elephantio_client.socketio_key');
$elephantIOClient = $client->getElephantIO();
$elephantIOClient->initialize();
if ($request->isXmlHttpRequest()) {
$chatForm->handleRequest($request);
$chatData = $chatForm->getData();
dump($chatData);
$elephantIOClient->emit('chat message', ['msg' => $chatData]);
}
$elephantIOClient->close();
return $this->render('chat/index.html.twig', [
'form' => $chatForm->createView(),
]);
}
I think it's a problem with the url (who seems good) who don't call my controller but i don't know what.
I readed some topic about ajax with symfony and it's all the time like i made. If you have any ideas to help me to fix this.
Thanks
It's rendering your HTML code because in your controller you are rendering your HTML code with this :
return $this->render('chat/index.html.twig', [
'form' => $chatForm->createView(),
]);
You need to add a return response inside your if clause to return something else when it's an ajax request :
if ($request->isXmlHttpRequest()) {
$chatForm->handleRequest($request);
$chatData = $chatForm->getData();
dump($chatData);
$elephantIOClient->emit('chat message', ['msg' => $chatData]);
return new Response("ok");
}
I'm trying to build a search utility in Laravel 4 with ajax where a user can search through various things such as orders and estimates and have the result(s) load as links to those orders, estimates, etc in the "search_results" div on the hope page.
Right now I've gotten the ajax to correctly go into the database and return the relevant information but instead of displaying it in the "search_results" div on the "home" route I'm redirected to the "search" route where the information is displayed where EVERYTHING of these orders are shown.
If anyone can point out why I'm being redirected to a different page instead of having the info load in the correct div on the home page or how to control what get's returned by ajax it would be very much appreciated! Thank you!
Here is my View:
<div class="large-6 columns">
{{Form::open( array('route' => 'search', 'method' => 'post', 'id' => 'search_form'))}}
{{ Form::select('search_table',
array(
'select' => 'Search...',
'commissions' => 'Search commissions',
'estimates' => 'Search estimates',
'orders' => 'Search orders',
'warranties' => 'Search warranties',
), null, array('id' => 'search_table')) }}
<div class="search_box" id="search_column_div">
<select id='search_column' name='search_column'>
<option value='created_at'>by date created</option>
</select>
</div>
<div id="search_input_div">
<input id='search_input' name='search_input' class='search_input' placeholder='Enter Order Name'/>
</div>
{{ Form::submit('Search', array('id' => 'search_button','class' => 'button expand radius search_button no_display'))}}
{{ Form::close() }}
<div id="search_results">
</div>
</div>
JS:
/*AJAX Search*/
$(document).load(function(){
$.ajax({
url: '/search',
type: 'get',
cache: false,
data: $('#search_form').serialize(),
success: function(data){
console.log(data);
$('#search_results').html(data);
},
error: function(xhr, textStatus, thrownError){
console.log(xhr);
console.log(textStatus);
console.log(thrownError);
alert('Somethin went wrong');
}
});
});
Controller:
public function searchPost(){
$search_table = Input::get('search_table');
$search_column = Input::get('search_column');
$search_input = Input::get('search_input');
$search = DB::table($search_table)->where($search_column, 'LIKE', "%{$search_input}%")->get();
echo json_encode($search);
exit;
}
Route:
/*Search Page for Ajax*/
Route::post('/search', array(
'as' => 'search',
'uses' => 'HomeController#searchPost'
));
The problem is the return in your controller. When anything is returned from a route or controller in Laravel, it is sent back to the browser. Usually it's sent in the form of a page redirect or url. In this case you're sending it data which the browser is parsing and displaying.
To do an AJAX request in your case you need to echo out the search results instead of returning them. And don't have a return statement in the function at all. Whatever you print out is what will be returned to your AJAX request in the form of a string. You'll more than likely want to json_encode the search results so that you can then parse them on the front-end more easily which will allow you to display the results any way you like.
EDIT: The reason your're being sent to another page still is because you're triggering the form submission in javascript. You actually want to prevent that and handle it solely with the AJAX request. That form submission is triggering a normal browser handled HTTP request which is reloading the page.
first is to test your /search page for json output for that you need to modify your code to:
public function searchPost(){
$search_table = Input::get('search_table');
$search_column = Input::get('search_column');
$search_input = Input::get('search_input');
$search = DB::table($search_table)->where($search_column, 'LIKE', "%{$search_input}%")->get();
echo json_encode($search);
exit;
}
after this you should test your page e.g www.webpage.com/main/search
you should see a string with similar format to this:
{"player_id":1,"level":1,"quests":{"1":{"percent_completed":100,"quest_title":"the first quest"},"2":{"percent_completed":80,"quest_title":"the second quest"},"3":{"percent_completed":50,"quest_title":"the 3rd quest"}}}
DEBUGGING
but since the function needs post data we will change your code to(temporarily):
public function searchPost(){
//$search_table = Input::get('search_table');
//$search_column = Input::get('search_column');
//$search_input = Input::get('search_input');
//$search = DB::table($search_table)->where($search_column, 'LIKE', "%{$search_input}%")->get();
$sample_array = array("id"=>1,"name"=>"sample");
echo json_encode($sample_array);
exit;
}
run your ajax on load:
$.ajax({
url: '/search',
type: 'post',
cache: false,
data: $('#search_form').serialize(),
success: function(data){
console.log(data);
$('#search_results').html(data);
},
error: function(xhr, textStatus, thrownError){
alert('Somethin went wrong');
}
});
I'm new at Laravel and ajax. I'm trying to get the data from a form via ajax and calling a method in the controller via that same ajax. The method in the controller searches the database and then returns a json response that gets handled by ajax(that last part I'm still thinking about, I haven't really done it yet).
Let me show you what I have now:
Routes.php:
Route::get('/', 'HomeController#getIndex');
Route::post('/', 'HomeController#postIndex');
HomeController:
public function getIndex()
{
return View::make('index');
}
public function postIndex()
{
$match = Input::get('search');
$results = Customers::where('name', 'like', '%'.$match.'%')->get();
return Response::json(array('results' => $results));
}
And my index.blade.php View :
<script>
$(document).ready(function() {
$('form#find').submit(function() {
$.ajax({
url : 'CustomerSearch/Public',
type: 'post',
dataType: 'json',
data: $('form#find').serialize(),
});
return false;
});
});
and the form:
{{ Form::open(array('url' => '', 'method' => 'POST', 'id' => 'find')) }}
{{ Form::text('search', '', array('class' => 'search-query', 'placeholder' => 'Search')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
{{ Form::close() }}
So I should be getting the data from the form then sending it to the "postindex" method in the controller so it gets processed and then sent back, right? Except I get the error "Controller method [index] not found." when I don't actually call any index method since they are both named differently.
I'm new at this so sorry if it's not clear.
UPDATE:
Like I said in the commentaries, I found out combining the route into a route::controller got rid of my previous problem but unfortunately I'm still unable to get the ajax to send data to my controller. I get no errors, but the ajax doesn't load anything to the controller. Any idea what might be wrong with my ajax?:
$(document).ready(function() {
$('form#find').submit(function() {
$.ajax({
url : '{{URL::to('/')}}',
type: "POST",
dataType: 'json',
data: { search: $('.search-query').val() },
success: function(info){
console.log(info);
}
});
return false;
});
});
Just use in your controller:
return json_encode(array('key' => 'val'));
For the input of data, I moved to a JQuery plugin that works nicely for me. Follow this link.
This is how a function looks like:
function someName(){
// A plugin is used for this function
$('#form_id').ajaxForm({
url: '/',
type: 'post',
dataType: 'json',
success: function(response){
alert(response.key);
}
});
}
and the corresponding form:
<form id="form_id">
<!-- Put your fields here -->
<input type="submit" onclick="someName()">
</form>
I would suggest you use this method, which may depend on the plugin but is the simplest. Of course, you could use the .submit() statement instead of binding it to the onclick event