How to use ajax $.post() in a callback? - ajax

I'm trying to use Ajax in a callback on 'eventDrop'
Here is the line of code I use:
$.post('{{ route('update_event_ajax') }}', data);
But when add it, the calendar no longer appears.
Here is my FullCalendar script:
$(document).ready(function(){
$('#calendar-NcAT6P42').fullCalendar( //calendars options...
,"eventDrop":
function(event) {
$('#event_id').val(event.id);
$('#event_title').val(event.title);
$('#event_footnote').val(event.footnote);
$('#event_id_team').val(event.id_team);
$('#event_id_customer').val(event.id_customer);
$('#event_title').val(event.title);
$('#event_start_date').val(moment(event.start).format('YYYY-MM-DD HH:mm:ss'));
$('#event_end_date').val(moment(event.end).format('YYYY-MM-DD HH:mm:ss'));
var data = {
_token: '{{ csrf_token() }}',
event_id: $('#event_id').val(),
event_title: $('#event_title').val(),
event_start_date: $('#event_start_date').val(),
event_end_date: $('#event_end_date').val(),
};
$.post('{{ route('update_event_ajax') }}', data);
},
"events": ...);
});
I've also tried with $.ajax(...) but got the same problem
I assume that my Ajax isn't at the right place ? But where should I place it ?
Thanks in advance
edit:
I'm using Laravel 5.0 and Laravel 5 Full Calendar Helper (https://github.com/maddhatter/laravel-fullcalendar)

Blade syntax can't be used in an external Javascript file.
I fixed my problem by adding this line in my view:
window['ajax_event_url'] = "{{ route('update_event_ajax') }}";
And then use it this way:
$.post(ajax_event_url, data);

Related

How to insert data in the database using ajax in laravel?

I'm working on a simple web application in the laravel framework. I have blade, controller and model files and I want to insert the data into the database with the help of ajax. But, I'm not able to insert the data. Below is the code:
Thanks.
<script>
$(document).ready(function(){
$("#button").on("click", function(){
var name=$("#name").val();
var email=$("#email").val();
$.ajax({
url:'insert.php',
method:'POST',
data:{
name:name,
email:email,
},
success:function(data){
alert(data);
}
});
});
});
</script>
There are so many issue with your code:
url:'insert.php', // here you are not working in core php so url is not passed in this way
it will be like:
url:'{{ url("/insert") }}', // This 'insert' will be a route and that will be mapped to a controller function.
And if you are using:
method:'POST',
then you have to set the csrf token like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
or
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
Resolve the above issues and try again.
at least, you have to call in your script.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
Because it is POST request, your csrf_token is required.

Passing django variable in ajax data

I would like ajax to post some variables which have been created in a view.
My problem is that it isn't written in the proper way and anything is sent to my post request when I am looking at the chrome inspecter.
This is my javascript function :
function submitDataTable() {
let table = $(document.getElementById('datatable')).DataTable()
let advisedPriceColumn = table.column('advised_price:name')
let advisedPriceData = advisedPriceColumn.data().toArray()
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' }
})
$.ajax({
url: 'submit/',
type: 'POST',
data: {
advisedPrice: advisedPriceData,
normal_price: '{{ normal_price|safe }}',
},
processData: false,
success: res => {
alert('Bien ouej mon vieux')
location.reload()
},
error: xhr => {
alert(xhr.responseText.split('\n')[1])
}
})
};
These are some of the variables of my view that I would like to pass in my JS function:
return render(request,'livedb_model/typeDetail.html',{
'property':property,
'roomtype':roomtype,
'invdf':invdf,
'price_advised_list':price_advised_list,
'price_list':price_list,
'occupancy_list':occupancy_list,
'c_occupancy_list':c_occupancy_list,
'normal_price_list':normal_price_list[:100],
'normal_price':normal_price,
'week_day_multi':week_day_multi,
'week_end_multi':week_end_multi,
'max_discount':max_discount,
'max_markup':max_markup,
'coccCategory':coccCategory,
'agressiveness':agressiveness
})
And this is a screenshot of the chrome inspector, where we can see that only an [object Object] is passing
Please can you help me on this?
You can't use django tags in .js file, what you can do is set data attributes in html like -
<input type="text" data="{{ normal_price|safe }}" id="id_normal_price" value="">
and then get it into your js like -
normal_price: $("#id_normal_price").attr("data")
you can set data values in any html tag.
Look at - https://www.w3schools.com/tags/att_global_data.asp

Django - Is it possible to transfer template tags to client asynchronously?

I am looking for a way to receive template tags,
specifically a paypal form generated in views.
I've been trying with jquery $.post and $.get to no avail.
Also considered ajax but it seems to receive only json
one of my template tags is a form, and it can't be converted to json:
TypeError: Object of type PayPalPaymentsForm is not JSON serializable
I need this for users that click the browser go back button when in paypal,
in case that happens I need to send the price to the view
and generate the form,
if I don't send the items and discount I will get multivaluedictkey
views.py
return render(request, 'pagamentos/payment.html', { 'morada':morada, 'telemovel':telemovel,'codigo_postal':codigo_postal, 'cidade':cidade, 'form': form })
payment.html
$.post( "/token/", {
items: x.toString(),
desconto: y.toString() ,
'csrfmiddlewaretoken': '{{ csrf_token }}' },
function( data ) {
console.log(data.morada)
console.log(data.telemovel)
console.log(data.cidade)
console.log(data.codigo_postal)
console.log(data.form)
});
it doesn't work like that.
Looking for a solution to load the template tags in the javascript ready function, without additional buttons.
I think what you want is to keep the django variables in a JS variable during rendering.
Something like this should work:
payment.html
var data = {
morada: '{{ morada }}',
telemovel: '{{ telemovel }}',
cidade: '{{ cidade }}',
// ... other variables
};
$.post(...);

Howto do autocomplete with Symfony3 AJAX and Chosen2

Hi and thanks for helping me, English is not my first language, sorry in advance. :)
When selecting the selectbox I get the notification "no results found", but when I look at the result in the developer toolbar I see that I receive a complete JSON.
How can I match a single value instead of getting the whole JSON?
JSON result:
["Descent: Journeys in the Dark (Second Edition)","Dominion","Ascension","Star wars LCG","Magic: The
Gathering Duel Decks Anthology"]
The script:
<script type="text/javascript">
$('select').select2({
placeholder: 'Select an item',
ajax: {
url: '{{ path('user_games_json') }}', //url to the json data
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
if you want to get the data from server by ajax request you can use Select2 Bundle i'm using it in my projects it's one of the best bundle you can use to make auto complete functionality .

Using ajax with laravel

I'd like to know if it's possible to use Ajax with Laravel without writing the code inside a .js file.
Script.js
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '',
data: ...
});
})
I don't know how to get the URL that I want (which is my currently page,
I just want to change the < select> value then reload the data that's already shown on the page).
Do I have to write the ajax inside my .php files? Is this a 'good practice'?
I'm asking this because I already have another script inside that same .php file.
Update
Following the answer posted by #ohgodwhy
Now nothing happens when the ajax executes.
It hits the success code but nothing happens, the URL does not change. Is it because I'm redirecting to the same page am at?
file.php
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: { anoSemestre: anoSemestre },
success: function(){
console.log('HELLO WORLD');
}
});
})
</script>
MyController:
public function getProfessorList()
{
$professor = Professor::all();
if( Request::ajax() )
{
echo 'yolo';
}
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres'));
}
What I usually do is add a #yield('scripts') section to my layout that I extend.
Then in the child templates that require specific JS, I'll add that in there.
#section('scripts')
<script>
//your javascript here.
</script>
#endsection
There is 1 caveat however. If you use an #include from within a child template, and that included file has it's own javascript, it must invoke the parent first, like this:
#section('scripts')
#parent
<script>
</script>
#endsection.

Resources