How to correct this Ajax Request in Laravel [closed] - ajax

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to send ajax request to fetch data from controller when I change date. I am not able to write ajax code properly. My code is as under:
{!!Form::open(['action' => 'BookingsController#store', 'method' => 'POST'])!!}
#csrf
<input type="date" name="eventDate" id="eventDate" value="">
<select name="vehicleName" id="vehicleName">
<option disabled selected>Choose Vehicle...</option>
<?php foreach ($availableVehicles as $key => $vehicle): ?>
<option id="{{$vehicle->id}}">{{$vehicle->name}} </option>
<?php endforeach; ?>
</select>
{!!Form::close()!!}
$(document).ready(function(){
$(#eventDate).change(function(){
var eventDate = $(this).val();
$.ajax({
url:"{{ route('booking.create') }}",
method:"GET",
data:{eventDate},
success:function(result){
$('#vehicleName').val('');
}
});
});
});

1) You need to add into your data attribute the token variable token. Because Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.
data{'_token': '{{ csrf_token() }}'},
2) You forgot to add quotes into your #eventDate function. Change this:
$(#eventDate).change(function(){
to this
$('#eventDate').change(function(){
3) My opinion is to create the ajax inside the .change() function. Here is a full code below:
$(document).ready(function(){
$('#eventDate').change(function(){
var eventDate = $(this).val();
$.ajax({
url:"{{ route('booking.create') }}",
method:"POST",
data:{'_token': '{{ csrf_token() }}','eventDate' : eventDate },
success:function(result){
$('#vehicleName').val('');
},
});
});
});
I hope it helped you
EDITED
You can create a meta element inside your master layout like the example below.
<meta name="csrf-token" content="{{ csrf_token() }}" />
Furthermore, inside your jQuery scripts you can call it:
$('meta[name="csrf-token"]').attr('content');
This is better, because you can use csrf_token inside js files

To avoid form being submitted you should add:
$(document).ready(function(){
$("#form" ).submit(function( event ) {
// to track it is working: console.log( "Handler for .submit() called." );
event.preventDefault();
});
});

Related

Vue-Resource gives TokenMismatchException in Ajax POST call

Please note, I'm using the Laravel framework.
Also please note, there are similar questions on SO, I've checked them, but wasn't able to solve my problem based on those solutions...
Even though I set my CSRF token right to my knowledge, I'm not sure why it won't work.
When checking the console, it seems I have 3 cookies: two Request cookies of which one is called XSRF-TOKEN and one is called laravel_session. And one respone laravel_session cookie. All have a different value!!!
My Vue:
new Vue({
el:'body',
http: {
root: '/root',
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
},
});
My head:
<meta name="_token" content="{!! csrf_token() !!}"/>
My Vue component addNew method:
Vue.component('things',{
template:'#things-panel-template',
data(){
return {
list: [],
newThing: {
body: '',
// _token: $('meta[name=_token]').attr('content'),
// tried removing token from head meta and adding up here.
},
}
},
methods:{
addNew(){
var thing = this.newThing; // get input
this.newThing = {body:''}; // clear input
this.$http.post('/api/things/add',thing) // send
},
},
});
My route:
Route::post('/api/things/add',function(){
return App\Thing::create(Request::get());
});
And finally, the form in my Vue Template:
<form action="/things/add"
method="POST"
#submit.prevent="addNew"
>
<div class="form-group">
{{ csrf_field() }}
<label for="">Add</label>
<input type="text"
name="body"
id="task-body"
class="form-control"
v-model="newThing.body"
>
<button :disabled="!isValid"
class="btn btn-primary"
type="submit"
>Add</button>
</div>
</form>
Try this:
this.$parent.$http.post('/api/things/add', thing)
instead of
this.$http.post('/api/things/add', thing)
Or set default values using the global configuration:
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');
I found the answer myself:
If you're gonna work with a vue-component, you should just add the token to that component instead. Otherwise it won't go with your ajax request.
So put this part underneath the template in the component:
http: {
root: '/root',
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
},
Do this to check if your token was properly sent inside the headers:
Go to google chrome, open dev-tools, go to the network tab and Reload.
Make the ajax call and look at the file added in the network tab, open it and go to the 'Headers' tab.
Look at the bottom where it says: 'Request Headers' and check if the token was properly added in the request.

How laravel set path for ajax and forms

I have simple question:
How laravel set correct path for ajax or form action?
I have my laravel instalation in
localhost/laravel-test/public
Ok and lets say i have url opened: localhost/laravel-test/public/hello
<form method="post" action="some/very/long/path">
<input type="submit" value="just-test" />
</form>
Now i hit just-test button, and its always know where it should start routing - allways start from public/[route here].
I was try to do my own routing system, but i have problem because its going to addres:
localhost/my-framework/public/hello/some/very/long/path
It allways put after public my actual url, and then after form action..
So my question is how laravel know it should get
localhost/laravel-test/public/some/very/long/path
It works same for jquery ajax request for ex:
$.ajax({
url: "test.html",
context: document.body
})
Laravel console output:
localhost/laravel-test/public/test.html
My custom framework console output
localhost/my-framework/public/actualpath/test.html
For the form action you can use the url or route helper. Like so:
{{ url('very/long/path') }}
And for your front end part.
$('#form').live('submit', function(event) {
$form = $(this);
$.ajax({
url: $form.attr('action')
});
});
I think this is what you're looking for.
In routes.php
Route::post('some-very-long-uri', ['as' => your-name', 'uses' => 'YourController#method']);
Then you can do something like that
<form method="post" action="{{ route('your-name') }}">
<input type="submit" value="just-test" />
</form>
and for ajax
$.ajax({
url: "{{ route('your-name') }}"
});

Using ajax to pass text to a db

I am trying to take simple text from a form, pass it to my controller via ajax, and have that send to the data base.
View
<form method="POST">
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="rate" type="submit">
</form>
<script type = "text/javascript">
$(function(){
$("#rate").click(function(){
dataString = $("#email").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/trial/insert_into_db",
data: dataString,
});
});
});
</script>
The controller code and the model code work fine. I am almost sure that it is the ajax code that is not working.
Any information would be greatly appreciated!
Thank you.
One thing missing from your posted code is disabling the default form submission. There still could be other issues.
You don't specify an action so by default the action is the same url as the page.
<form method="POST">
You are doing AJAX but you have not disabled the default behavior with return false or event.preventDefault
$("form").submit(function(event) {
event.preventDefault();
// or
return false;
});
I prefer preventDefault() but the point is you need to prevent the default browser behavior.
Edit: This is how I would submit the form with AJAX.
If you had more than one form button to consider then
$("form").submit(function(e) {
e.preventDefault();
});
$("#rate").click(function(e) {
$.ajax({ ... });
});
But it's (marginally) easier to do it with one handler. I'd also stick the action on the form so the form still submits to the correct url if the javascript failed.
<form id="myform" action="<?php echo base_url();?>index.php/trial/insert_into_db" method="post">
Instead of handling the button click handle the form submission
$("#myform").on("submit", function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type = "post",
url = $(this).attr("action"),
data = formData
})
.done(function(result) {
// do something with the response
});
});

How to capture AJAX response?

I have a simple script, in ajax, and I want to capture the return and process it according to the value:
if (xmlhttp.readyState==4) {
if (xmlhttp.responseText == "not available") {
document.write("not available");
}
}
At the same time, I tried this, which worked:
if (xmlhttp.readyState==4) {
document.write(xmlhttp.responseText);
}
What wrong am I doing?
Thank you for your reply. This is my current domain availability checking script which works great:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#dtype').change(function() {
var opt = $('#domain').val();
$.ajax({
type: "POST",
url: "testwhois.php",
data: 'd=' + opt,
success:function(data){
$('#txtHint'). html(data);
}
});
});
});
</script>
</head>
<body>
<form> Domain name : <input type="text" name="domain" id="domain"> <input type="radio" name="dtype" id="dtype" value="new">New <input type="radio" name="dtype" value="transfer">Transfer <span id="txtHint"></span> </form>
</body>
</html>
However, I want to have two things in it:
a preloader image (I have it) while the script is working in the place of 'txtHint' where the answer will be displayed.
The answer is returned in the format of "not available" or available". I want to make the 'domain' field blank, when the answer is returned as "not available" with the html codes.
Thanks again.
Forgive me if you know this already, but in case you don't:
Ajax posts data to an external php file, which processes the data it receives, and sends back an answer. It looks like this:
FILE #1:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Sel').change(function() {
var opt = $(this).val();
var someelse = 'Hello';
var more_stuff = 'Goodbye';
$.ajax({
type: "POST",
url: "receiving_file.php",
data: 'selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
success:function(data){
alert('This was sent back: ' + data);
}
});
});
});
</script>
</head>
<body>
<select id = "Sel">
<option value ="Song1">default value</option>
<option value ="Song2">Break on through</option>
<option value ="Song3">Time</option>
<option value ="Song4">Money</option>
<option value="Song5">Saucerful of Secrets</option>
</select>
FILE #2: receiving_file.php
<?php
$recd = $_POST['selected_opt'];
echo 'You chose: ' . $recd;
The above example works. If you copy/paste it into two files, you will see AJAX in action. Of course, the server side scripting is in PHP, so your server needs to handle that. If necessary, download XAMPP and install it on your local computer. Place these two files in the htdocs folder and, in the browser address bar, type:
http://localhost/whatever_you_called_the_first_page.php
As you can see, it is much simpler to write AJAX code using jQuery. All that is needed is the jQuery library (usually in the header tags, as in code example above), and the AJAX code block.
Here are some other examples to study:
More complicated example
Populate dropdown 2 based on selection in dropdown 1

Load PHP array into html as select options

I am having trouble working the finishing touches out with this. I am still fairly new to ajax and json, but here's what i have so far. I am trying to take an array(s) from a php file and load them into a select dropdown (#input) via ajax/json. I think i'm pretty close, but i'm not sure where i'm messing up. Please help
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="../_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
if ($("#numbers").val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = <?php echo json_encode($array); ?>;
for (i=0;i<numbers.length;i++){
$('#input').append("<select>" + numbers[i] +
"</select>");
}
},
});
}
});
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
</div>
<div id="content">
<div class="main">
<div id="formwrapper">
<select id="numbers">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="input"></select>
</div>
</div>
</div>
</div>
</body>
</html>
And here is my PHP (login.php)
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>
In your script, you aren't doing anything with the data that is returned from the AJAX call. I suspect that is because you don't understand how AJAX works. I'll try to explain it without going into super deep detail.
When you make an AJAX call to a URL, you are making an HTTP request, just like when you type http://www.google.com into your web browser. In response, the server at the other end of that URL sends you an HTTP response with some data.
In the case of your AJAX, you are requesting the response of login.php, which, I will assume, is the PHP you added to your question above. In the success function, you get a result. That result is everything that was output by login.php.
So,
$(document).ready(function() {
$("#numbers").change(function(e) {
if ($(this).val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = result; //result is equal to your array from the php. You don't put PHP here.
$('#input option').remove(); //Remove any existing options.
for (i=0;i<numbers.length;i++){
$('#input').append("<option>" + numbers[i] + "</option>");
}
}
});
}
});
});
If login.php is NOT the PHP you added above, then I'm not going to be able to help you until you tell me what file that is from.
Also, notice that we wrapped the AJAX call into a change event on the #numbers select box. That way, when the select box's value changes, it will call this AJAX, and select the numbers.
Thanks for the assist tymeJV.

Resources