Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

feniixx's avatar

Post with AJAX not working

Maybe this is a very common topic, but i can't find any solution!, the app i'm developing is under Laravel 5.0, i need to send some data from jquery ajax to a laravel controller, i've followed this tutorial to post data using ajax, i've followed the steps and made the global configuration, so that i have a meta with the csrf token, when i send the post request to a url using ajax, it sends the data (i know it because the headers data has the values sent) but the controller function is not triggered.

Here's my form:

<meta name="_token" content="{!! csrf_token() !!}"/>

...

{!! Form::open(array('url'=>'/reservacion/paso-uno/enviar','method'=>'POST', 'id'=>'reservacion-paso-uno')) !!}
<label for = "cantidadpersonas" >Cantidad de personas</label >
    <input id = "personas" type = "text" placeholder = "#" >
    <br ><br ><br >

    <label for = "comidas" >Seleccione los platillos que desea reservar</label >
    <br ><br ><br >

    <div id = "comidas" class = "owl-carousel owl-theme" >

        @foreach($platos as $plato)
            <a class = "item opcion comida" >
                <p class = "hidden" >{{ $plato->id }}</p >
                    <img id = "{{ $plato->id }}" class = "img"
                    src = "{{ asset('club/img/gallery/gallery1.jpg') }}" alt = "{{ $plato->nombre }}" >
            </a >
        @endforeach
    </div >
    <br ><br ><br >

    <div id = "bebidas" class = "owl-carousel owl-theme" >
        @foreach($bebidas as $bebida)
            <a class = "item opcion bebida" >
                <p class = "hidden" >{{ $bebida->id }}</p >
                    <img id = "{{ $plato->id }}" class = "img"
                        src = "{{ asset('club/img/gallery/gallery2.jpg') }}"
                        alt = "{{ $bebida->nombre }}" >
            </a >
        @endforeach
    </div >
    <br ><br >
    {!! Form::button('Siguiente', ['id'=>'siguiente']) !!}
{!! Form::close() !!}

Here's the post route:

    Route::post('/reservacion/paso-uno/enviar', [
        'as' => 'publicPostReservacionPasoUno',
        'uses' => 'ReservacionCtrl@pasounoPost'
    ]);

Here's the post function in the controller:

    public function pasounoPost()
    {
        dd(\Request::all(),\Request::method(),Request::ajax());

    }

And here's the jquery ajax post event

$.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
        });

$("#siguiente").click(function (event) {
    event.preventDefault();

    ...

    var request = $.ajax({
        url: '/reservacion/paso-uno/enviar',
        method: 'post',
        data: {bebidas: bebidas_json, comidas: comidas_json, '_token': $('input[name=_token]').val()},
        success: function(data){
                    console.log(data);
                }
        });

});

The situations vary depending on some configurations:

  • When i add a button with a click event, it sends the data (i verified it in the formData of the headers), but it doesn't reach the controller's function so that nothing happens...
  • When i add a submit with a submit event, the event is not the fired one, instead the form sends only the inputs of the form; i mean the data i get in jquery isn't sent.
0 likes
34 replies
ftiersch's avatar

Are you using jQuery v 1.9 or later? Because the "method" option of ajax was called "type" before that. If you use <1.9 you would send a GET request instead of a POST one.

And: Have you checked the result of the AJAX call? Is there an Exception? Have you turned on debug mode in Laravel?

feniixx's avatar

@ftiersch I'm using jQuery 2.1.3, the result is a pretty large script, i'll paste a piece of it:

<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/; doc.documentElement.firstChild.appendChild(refStyle); function toggle(a) { var s = a.nextSibling || {}; if ('sf-dump-compact' == s.className) { a.lastChild.innerHTML = '&#9660;'; s.className = 'sf-dump-expanded'; } else if ('sf-dump-expanded' == s.className) { a.lastChild.innerHTML = '&#9654;'; s.className = 'sf-dump-compact'; } else { return false; } return true; }; return function (root) { root = doc.getElementById(root); function a(e, f) { root.addEventListener(e, function (e) { if ('A' == e.target.tagName) { f(e.target, e); } else if ('A' == e.target.parentNode.tagName) { f(e.target.parentNode, e); } }); }; root.addEventListener('mouseover', function (e) { if ('' != refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover', function (a) { if (a = idRx.exec(a.className)) { refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}'; } }); a('click', function (a, e) { if (/\bsf-dump-toggle\b/.test(a.className)) { e.preventDefault(); if (!toggle(a)) { var r = doc.getElementById(a.getAttribute('href').substr(1)), s = r.previousSibling, f = r.parentNode, t = a.parentNode; t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f = f.firstChild.nodeValue.match(indentRx); t = t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) { r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]); } if ('sf-dump-compact' == r.className) { toggle(s); } } } }); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), elt = root.getElementsByTagName('A'), len = elt.length, i = 0, t = []; while (i < len) t.push(elt[i++]); elt = root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i < len) t.push(elt[i++]); root = t; len = t.length; i = t = 0; while (i < len) { elt = root[i]; if ("SAMP" == elt.tagName) { elt.className = "sf-dump-expanded"; a = elt.previousSibling || {}; if ('A' != a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref'; elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; } a.innerHTML += '<span>&#9660;</span>'; a.className += ' sf-dump-toggle'; if ('sf-dump' != elt.parentNode.className) { toggle(a); } } else if ("sf-dump-ref" == elt.className && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { t = a.nextSibling; elt.appendChild(a); t.parentNode.insertBefore(a, t); if (/^[@#]/.test(elt.innerHTML)) { elt.innerHTML += ' <span>&#9654;</span>'; } else { elt.innerHTML = '<span>&#9654;</span>'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '&#8230;'; elt.className = 'sf-dump-ref'; } } } } ++i; } }; })(document); </script> <style> pre.sf-dump { display: block; white-space: pre; padding: 5px; } pre.sf-dump span { display: inline; } pre.sf-dump .sf-dump-compact { display: none; } pre.sf-dump abbr { text-decoration: none; border: none; cursor: help; } pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0; outline: none; }pre.sf-dump{background-color:#fff; color:#222; line-height:1.2em; font-weight:normal; font:12px Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:100000}pre.sf-dump .sf-dump-num{color:#a71d5d}pre.sf-dump .sf-dump-const{color:#795da3}pre.sf-dump .sf-dump-str{color:#df5000}pre.sf-dump .sf-dump-cchr{color:#222}pre.sf-dump .sf-dump-note{color:#a71d5d}pre.sf-dump .sf-dump-ref{color:#a0a0a0}pre.sf-dump .sf-dump-public{color:#795da3}pre.sf-dump .sf-dump-protected{color:#795da3}pre.sf-dump .sf-dump-private{color:#795da3}pre.sf-dump .sf-dump-meta{color:#b729d9}pre.sf-dump .sf-dump-key{color:#df5000}pre.sf-dump .sf-dump-index{color:#a71d5d}</style><pre class=sf-dump id=sf-dump-122313018 data-indent-pad="  "><span class=sf-dump-note>array:3</span> [<samp>
  "<span class=sf-dump-key>bebidas</span>" => "<span class=sf-dump-str title="2 characters">[]</span>"
  "<span class=sf-dump-key>comidas</span>" => "<span class=sf-dump-str title="2 characters">[]</span>"
  "<span class=sf-dump-key>_token</span>" => "<span class=sf-dump-str title="40 characters">zF12Oh0Nr9QtdXPJh2n3gZItFWVMu1pIouGy7yf5</span>"
</samp>]
veve286's avatar

Why you insert _token method in your post when u already setup in your header. Can u show me your network tab and how the server respond your request ?

anam's avatar

Your JSON format seems not correct. Try the following:

data: { 'bebidas': bebidas_json, 'comidas': comidas_json, '_token': $('input[name=_token]').val()},

One more thing, does bebidas_json and bebidas_json exist?

feniixx's avatar

@veve286 i was just verifying that it sent the token in both ways. Here's a screenshot of the network tab.

@anam i get the same result using you code, and yes, they exitst, that's why i added ... in the code, that portion of code wasn't relevant

bestmomo's avatar

What I use as generic code :

$(document).on('submit', '#form', function(e) {  
    e.preventDefault();
     
// Inits there
     
    $.ajax({
        method: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),
        dataType: "json"
    })
    .done(function(data) {
        // done stuff
    })
    .fail(function(data) {
        $.each(data.responseJSON, function (key, value) {
            // Errors gestion
        });
    });
});
feniixx's avatar

@veve286 i'll upload it again later, @bestmomo I did it just as how you got it and it fails, I don't know why it fails! I know it posts the data, but what I don't know is why it doesn't display the dd () in the browser, with setup your got a question:

  • If I want that when the form is submitted it redirects to another route with data should I use a get or a post request?
feniixx's avatar

Hmmm, Ok @bestmomo, i removed the dd () instead I add it a return function with a redirect, but it doesnot work either

feniixx's avatar

Hmmm, Ok @bestmomo, i removed the dd () instead I add it a return function with a redirect, but it doesnot work either

feniixx's avatar

@bestmomo to do what?, I need to return a view with some data taken from the form where I make the request with ajax

bestmomo's avatar

@JSolorzano Javascript is waiting for a JSON anwer to manage. You can send any data but it'll be received there :

    .done(function(data) {
        // done stuff
    })

If you want to return a view you must render it, like in this example :

if($request->ajax()) {
    return response()->json([
        'view' => view('back.blog.table', compact('statut', 'posts'))->render(), 
        'links' => $links->setPath('order')->render()
    ]);     
}
feniixx's avatar

@bestmomo using your code I get an error Call to undefined method Illuminate\Support\Facades\Request::ajax () if I get rid of the if statement, and it sends the view in a json, but it doesn't shows up in the browser... and also I still get into fail, not into done...

bestmomo's avatar

@JSolorzano how do you manage the response in JavaScript ? You must manipulate the DOM. Something like this :

.done(function(data) {
  $('tbody').html(data.view);
  $('.link').html(data.links);
})
jimmck's avatar

Hi @JSolorzano I do nothing but POSTS, 24 x 7. The only time I Get is for specific commands. Here are the 2 UTIL functions I use.

/**
 * Created by Jim on 6/11/14.
 */
(function( $ ){ //Sweetness Baby!!!!  Thanks STACKOVERFLOW!!!! :)
    $.myPost = function( url, data, context, success, error, timeout, sync ) {
        var settings = {
            type : "POST", //predefine request type to POST
            'url'  : url,
            'data' : data,
            'context': context,
            'success' : success,
            'error': error,
            'timeout' : timeout,
            'async' : sync
        };
        $.ajax(settings)
    };
})(jQuery);

(function( $ ){ //Sweetness Baby!!!!  Thanks STACKOVERFLOW!!!! :)
    $.myGet = function( url, data, success, error, timeout ) {
        var settings = {
            type : GET, //predefine request type to POST
            'url'  : url,
            'data' : data,
            'success' : success,
            'error': error,
            'timeout' : timeout
        };
        $.ajax(settings)
    };
})(jQuery);

I have a JS Class but it may be useless to you right now. The post call looks like this.

  // how do we check the url is correct? timeout causes problems.
    // the busy flag needs to be static for the class.

    // make sure if callData is an object we make it an empty object.
    // we do this so we can add _token to it.

    if (callData == "") {
        callData = {};
    }
    this.busy = true;
    callData['_token'] = this.csrf_token;
    fyi('Post... [' + url + ']');
    $.myPost(url, callData, this, this.handlePost, this.postError, this.timeout, this.async);
};

handlePost is the js function called on success of the post call.

For Example:

function findPayload($p) {
    var rec = $p[$p.rootName].Category[0];
    app.setLongName(rec.Desc);
    app.setShortName(rec.ShortName);
    setCmdButton(UPDATE);
    controlButtons();
}

function find(id) {
    // We POST data to the backend, in place of URL data.  For Flexibility.
    var postData = {
        id: id  // Each entry is a separate _POST['id'] item on backend.
    };
    //debugger;

    payLoad.setOnPayload(findPayload).call('find', postData);
}

The $p in find findPayload contains the JSON from the Controller. Its just a String at the end of the day.

The controller calls the Command to find the record and writes it back.

    public function execFind($in)
    {
        $cmd = new GetCvgCategory();
        $ret = $cmd->exec($in->id);

        return $ret;
    }

    public function find()
    {
        if ($this->ping()) {
            return "";
        }
        $in = new FindInputs();

        //$_POST['id'] = 'd';
        return $this->cmdExec($in, $_POST, 'execFind');
    }

And the routes...

    Route::post('find', 'CoverageCtrl@find');
    Route::post('create', 'CoverageCtrl@create');
    Route::post('update', 'CoverageCtrl@update');
    Route::post('idx', 'CoverageCtrl@index');
feniixx's avatar

@jimmck I don't see how do you redirect to another page with data from an ajax post... your code seems nice, but if you could make a better example of my situation i'lllll thank you lots!!

jimmck's avatar
jimmck
Best Answer
Level 13

@JSolorzano I was leaving off specific implementation so as not to confuse. Redirect where? My Controller returns back to the page that did the POST call. Its a single page App, once it loads it stays there. The page keeps track of Button state. Create or Update. Thats what the little JS snip does in the findPayload function.

Here is the trait that formats the return from the command.

    public function cmdExec($in, $postVars, $cmd)
    {
        /* @var DataMap $payload */
        $payload = null;
        $inputErrors = array ();

        /* @var ICommandInputs $in */
        if (CommandUtils::setInputs($in, $postVars, $inputErrors) == $in->expects() && count($inputErrors) == 0) {
            $ret = call_user_func_array(array ($this, $cmd), array ($in));
            $payload = $this->buildPayload($ret);
        } else {
            $msg = "";
            /* @var CommandInputError $err */
            foreach ($inputErrors as $err) {
                $msg .= '<li>' . "Field: " . $err->getFieldName() . " [" . $err->getMessage() . ']</li>';
            }
            $payload = Payload::create(Payload::MSG, 0, "Find", "Input Error", new Message($msg));
        }

        $r = $payload->toJSON();
        return $r;
    }

feniixx's avatar

@jimmck what I need is to redirect to a route and send some data from the first form.

Hmmm I don't need a SPA, what I need is just to send the data to another route....

jimmck's avatar

@JSolorzano So in the Controller called by the post, take the data return a new view with the data. The new view can point to a new controller.

feniixx's avatar

@jimmck i'm using AJAX because i have some arrays of data i need to send, here's my real setup, i have a carousel where i can select some items, i can access to the selected items through jquery storing the items that has selected class into a json, i need to send that data to a laravel controller and then resend that data to another view, so i thought about ajax, but it's not working as i expected...

feniixx's avatar

@jimmck Nice!, now i have the data in the controller, but how do i access to the json in the controller? and also how do i access to it?

jimmck's avatar

@JSolorzano You gave the TextArea an Id? Pull the data and call json_decode.

http://php.net/manual/en/function.json-decode.php

I use it to validate a JSON object I build through other means. But for you builds a nice assoc. array.

        $ret = <Your form JSON Object>
                $decode[] = json_decode($ret, true);
                $lastError = json_last_error_msg() . " :" . json_last_error();
                if (json_last_error() != 0)  // Use PHP to check our JSON output.
                {
                    throw new JSONParseException("JSON Parse Error: $lastError");
                }

I left the error stuff for info. purposes for you.

feniixx's avatar

You've been really nice @jimmck, if you could keep helping me i'll be thankful, how could i redirect to another route and send it data, i don't mean url parameters, i mean data like an array or something like that, the purpose if this is that i need to redirect the user to another route sending data.

jimmck's avatar

I am here. Do you mean you want to give user a new page? In the Controller that gets the json array. Do your thing with the data. Then build a new view with the processed data and return it. Just like when you created your initial view they made their picks from.

Next

Please or to participate in this conversation.