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 .
Related
I try to make an ajax request through JQuery triggering an onClick event, but when it sends the AJAX request I receive:
PATCH http://localhost:8000/courses 405 (Method Not Allowed) (Current page) Because it doesn't get the URL with the id
HTML
#foreach ($courses as $course)
<tr>
<td>{{ Form::select('year', $years, ['class' => 'form-control'], [ 'placeholder' => $course->academicYear]) }}</td>
<td>{{ Form::select('subject', $subjects, ['class' => 'form-control'], [ 'placeholder' => $course->subject]) }}</td>
<td>
Save
<input type="hidden" id="idCourse" value="{{ $course->id }}">
(...)
JQUERY + AJAX
$('#saveCourse').click(function(e){
e.preventDefault();
var id = $('#idCourse').val();
// Ignore this logic
var values = {year: "", subject:"", id: id};
var parameters = ['year', 'subject'];
var i = 0;
$('td > select option:selected').each(function() {
values[parameters[i]] = $(this).text();
i++;
});
// Ajax request
$.ajax({
type: 'patch',
// Appending the course id here not working,
// but if i put anything else like /blabla/ + id ajax doesn't ignore it...
url: '/courses/' + id,
headers: {'X-CSRF-Token': csrf_token},
dataType: 'json',
data: values,
success: function (response) {
console.log("SUCCESS: " + response);
},
error: function (reject) {
if( reject.status === 422 ) {
$("#error").text("Los datos dados no cumplen el formato requerido.");
}
}
});
});
WEB.PHP
/* -----COURSE_ROUTES------ */
Route::resource('courses', 'CourseController')->except([
'create', 'edit'
]);
ROUTES
EDIT
If I use POST instead of PATCH in type AJAX gets the id.
Found a GitHub issue with the same problem https://github.com/jquery/jquery/issues/3944
PUT and PATCH are request methods. An HTTP error of 405, which you get means that the server knows the request method, but the service does not support it. Read more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
not sure if matters but try PATCH instead of patch
type: 'PATCH',
I forgot to put this condition at the start of the update method in the controller... Now it works!
if(request()->ajax()) { ... }
As mentioned below the 405 (METHOD NOT ALLOWED) basically means you're ajax request method PATCH is not allowed for the specific resource on the server.
If you using a routing library you can go their docs and search how to change this behavior. A route can accept one or multiple request methods, I assume that the Route::resource create a route with method POST by default, which explains that the ajax request works in POST type.
I am using laravel homestead. I am making a game that requires credits on the account of which it is played on. I want to make sure that after every play the credits of the user gets updated through an ajax request, however with this ajax request, I get the same error which is PATCH http://gamesite.test/updateBalance/13 419 (unknown status) if I change the data it gets the error: The GET method is not supported for this route. Supported methods: PATCH.
I already tried to change the methods of the ajax request and it is working on other pages.
The ajax request that I made is the following:
$(oMain).on("save_score", function(evt,iMoney) {
if(getParamValue('ctl-arcade') === "true"){
parent.__ctlArcadeSaveScore({score:iMoney});
}
//...ADD YOUR CODE HERE EVENTUALLY
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: 'updateBalance/'+{{ auth()->user()->id }},
type: 'PATCH',
data: {iMoney:iMoney, _method: "PATCH"},
success: function(res) {
}
});
});
I expected that it would update the users credits, instead got the error: "PATCH http://gamesite.test/updateBalance/13 419 (unknown status)"
EDIT:
Route:
Route::patch('/updateBalance/{id}', 'GamesController#updateBalance');
GamesController:
public function updateBalance(User $id) {
$selecteduser = User::find($id)->first();
$this->validate(request(), [
'credit' => 'int'
]);
$selecteduser->credit = request('iMoney');
$selecteduser->save();
}
Found the answer, I needed to add
to the header in the blade.
use HTTP default GET method, this works fine.
$.get (url, {iMoney:iMoney, _method: "PATCH"} , function(){
//success
})
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'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
on Firefox, only on firefox it will popup and give you a warning "This web page is being redirected to a new location. Would you like to resend the for form you have typed to the new location."
I got no form , i use javascript to extract values from textbox
I checked on firebug it says
PUT /admin/submit-scan/ 301 moved permanently
PUT submit-scan 302 Found
My JS
function submitGoods(){
var registeredNo = $('input[name=registeredno]').val();
var weight = $('input[name=weight]').val();
$.ajax({
type: 'PUT',
url: '/admin/submit-scan/',
data: {
registeredNo: registeredNo,
weight: weight,
_token: csrfToken
},
dataType: 'json'
}).done(function(data){
data = $.parseJSON(data);
});
}
My Route
Route::put('submit-scan', 'Controllers\Admin\DashboardController#putUpdateSubmitScan');
My controller
public function putUpdateSubmitScan()
{
if (Request::ajax())
{
return Response::json(array('success' => 1, 'data' => "test"));
}
}
Any idea what went wrong?
Removing the trailing slash should do the trick (most probably prior to Laravel 4.1, see below).
url: '/admin/submit-scan'
Update
As mentioned in Laravel4 POST unexplained redirect to GET
Laravel bootstrap/start.php is calling $app->redirectIfTrailingSlash(); which seems to be the culprit. This has been changed in Laravel 4.1:
http://laravel.com/docs/upgrade#upgrade-4.1