Laravel 4: manipulating ajax data through controller - javascript

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

Related

Problema sending json file from javascript to laravel controller

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.

Laravel Using AJAX to pass Javascript variable to PHP and retrieve those

How can I use Ajax to pass a Javascript variable to Php and retrieving those?
I am using a Jquery Ui Slider and on each slide I want to pass the javascript slider value to php so to say.
I have no ( not much ) experience in Ajax and really appreciate help.
This is how my slider looks:
$("#sliderNumCh").slider({
range: "min",
min: 0,
max: 20,
step: 1,
value: numbersOfChapters,
change : function(e, slider){
$('#sliderAppendNumCh').empty();
var i = 0;
var sliderValue = slider.value;
var getSliderVal = document.getElementById('sliderValue').value = sliderValue;
$.ajax({
type: 'POST',
url: '',
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
value: getSliderVal
},
success: function (option) {
console.log(getSliderVal);
}
});
...
}
})
My route example:
Edit my route looks like this now:
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController#editProduct']);
Edits what I have tried:
url: '{{ route("editProductWeb") }}',
and got this error:
POST http://localhost/myApp/public/product/edit/%7BproductID%7D 500 (Internal Server Error)
and tried this:
url: 'edit',
and got this error:
POST http://localhost/myApp/public/product/edit 500 (Internal Server Error)
Edit my edit controller method:
public function editProduct($productRomID = 0)
{
$product = ProductRom::find($productID);
$sheets = Chapters::where('product_id', '=', $productID)->get();
$productId = $product->id;
$sheetCount = count($sheets);
return view('product.edit', [
'productId' => $productId,
'product' => $product,
'sheets' => $sheets,
'sheetCount' => $sheetCount,
'type' => 'edit',
'route' => 'updateProductRom'
]);
}
Edit using haakym suggestion so far:
$.ajax({
type: 'post',
url: "{{ Route('editProduct', $product->id) }}",
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
value: getSliderVal,
productId : getPrId
},
success: function (option) {
console.log(getSliderVal);
}
});
does print me the id + the current slider value in my debug, so that works so far. Now I need to get that value and use it in my view(php) any suggestion how to proceed?
using this in my controller method:
$sliderValue = $request->input('value');
returns me
null
Edit I also tried this:
$sliderValue = Input::get('value');
which also returned me
null
Edit I added a Log:
Log::info(Input::all());
This shows the correct slider value and product id on slide.
But my Input::get('value') still returns me null
Edit I think I should add this information:
I changed my routes to this now:
Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController#editProduct']);
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController#editProductPost']);
The get shows the data from the database for a specific product and shows them in my view, I added the post one to post the slidervalue data to the editProductPost method and returns afterwards the value(sliderValue) in the edit view, is this correct?(Btw still does not work)
EDIT
If I put this in my controller method:
if ($request->isMethod('post')){
return response()->json(['response' => 'This is post method']);
}
return response()->json(['response' => 'This is get method']);
I keep getting the following error (if I slide):
POST http://localhost/myApp/public/product/edit/54 500 (Internal
Server Error)
I have this in my head:
<meta name="csrf-token" content="{{ csrf_token() }}">
and put this before my ajax post:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
EDIT:
Doing this returns the correct current slider value in the logs:
Log::info($request->get('value'));
I tried this:
return view('productRom.edit', [
'value' => $value,
]);
But I get an error in the console:
Failed to load resource: the server responded with a status of 500
(Internal Server Error) http://localhost/myApp/public/product/edit/73
As #julqas stated you need to include the URL in your $.ajax() method.
As you have a named route editProduct, you can output the link using blade:
$.ajax({
type: 'POST',
url: '{{ route("editProduct" }}',
...
Edit 1:
Your route is get and your ajax method is post, I guess this is the issue. You need to make them the same.
If you change the route to post you will need to add the CSRF token to the ajax request when it is sent. There is some guidance on the docs how to do this here:
https://laravel.com/docs/5.2/routing#csrf-x-csrf-token
The docs recommend adding this in your HTML head:
<meta name="csrf-token" content="{{ csrf_token() }}">
then use the following code before sending the request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
alternatively you can add it to the request in the ajax call.
Edit 2
A side point - I was just guessing what the error is, it would have been better if I'd asked you if you could debug it yourself in order to see what the error was. Learning to debug ajax requests is very useful and not too difficult.
The best way to do that is by using the developer console in your browser of choice when making the ajax request. If you're using Chrome for example open Developer tools and then click on the Network tab before making your request. After making the request you can inspect the request and its details. Hope that helps!
Edit 3
I would change your editProduct() method to not accept any parameter and instead get the id value for the product from the request
public function editProduct()
{
// value here is referring to the key "value" in the ajax request
$product = ProductRom::find(\Request::get('value');
...
}
Consider changing the value key in your json to something more useful, such as productId
data: {
productId: getSliderVal
}
you haven't entered value for 'url'. Create any route then put it in url:'{any_route_name}' and then check in console weather your value has been posted or not
You have to do some R&D at your level for this .

Symfony2 + AJAX return source code

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");
}

Ajax returning information but redirecting to a different page

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');
}
});

Avoid page reload when submitting form using ajax with laravel

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.

Categories

Resources