Send data to a Laravel driver with AJAX

1

I am developing a web platform for an IPS with Laravel 5.4 and PostgreSQL 9.6 . The problem I have is the following: in the patient registration form, I would like to see the application by means of Ajax in the database when losing the focus on the input that captures the identification number. if that identification number already exists to block the registration button if the case is affirmative.

The route that is supposed to respond to the request is as follows:

Route::post('/pnt/isexist', array('as' => 'pntisexist', 'uses' => 'PacienteController@isExist2'));

I've also tried it with the following route and it does not work either:

Route::post('/pntisexist', function(){
$paciente = DB::select("SELECT NROUSR FROM LESUSR WHERE TPOPRS = 'PNT' AND NRIPRS = :NRIPRS", ['NRIPRS'=>$nriprs]);

return Response::json(array()); });

My Javascript file is as follows:

$(document).ready(function(){

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('#nriprs').blur(function(){

    var nriprs = $('#nriprs').val();
    //var dir = "http://lesoft.com/cif/public/pnt/isexist/" + nriprs; -> FORMA 1
    //var dir = "/pnt/isexist/"; -> FORMA 2
    //var dir = "{{route('pntisexist')}}"; -> FORMA 3
    //var dir = "{{url('pnt/isexist')}}"; -> FORMA 4 
    //var token =  $('input[name=_token]').val();

    $.ajax({
        url: "pntisexist",
        //headers: {'X-CSRF-TOKEN': token}, 
        method: 'post',
        dataType: 'json',
        data: { nriprs : nriprs },           
        beforeSend : function(){

        },
        success: function(data){
            if (data.result != 'true') {
                alert('El paciente ya existe: ' + data.paciente);

            } 
        }
    });

});     
});

The problem is really that in the Javascript file I never recognize the route as I put it. I have tried it in several ways (I have left the forms as I have tried in the comments of the code) and none of them work so that the browser throws the 404 error indicating that the route does not exist.

    
asked by Jesus Escorcia 28.08.2017 в 03:47
source

2 answers

1

If you define the route in this way (it's the same as what you do but a little more organized):

Route::post('/pnt/isexist', 'PacienteController@isExist2')->name('pntisexist');

The so-called ajax should work with the name of the route (on blade):

$.ajax({
    url: {{ route('pntisexist') }}, 
    method: 'post',
    ...
    
answered by 28.08.2017 в 04:13
0

I recently had to do something similar and what I chose to do is use laroute which is a library in javascript that allows you to "use" the Laravel routes.

link

This way you do not have to use blade for route() but you can continue using the document as javascript , being able to compile it with the rest of code javascript .

    
answered by 28.08.2017 в 08:50