skip to Main Content

I face a strange behaviour with no clue at all on why and how to resolve it. I am new on PHP/Laravel/Ajax so be nice please ^^

My blade form :

<form method="post" action="{{ route('postContact') }}" id="id_post_contact">
    @csrf
    <input class="form-control" type="text" name="in_email" placeholder="[email protected]">
    [...]
    <button class="btn" type="submit">Submit Question</button>
</form>

<div>
    <script>
        $("#id_post_contact").submit(function(e) {
            e.preventDefault();

            var form = $(this);
            var url = form.attr('action');
            var data2Send = form.serialize();

            $.ajax({
                type:'POST',
                url:url,
                headers:{
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                },
                data:data2Send,
                dataType:'JSON',
                cache:false,
                //contentType:'application/json',
                success: function(data) {
                    alert(data.success);
                }
            });
        });
    </script>
</div>

My route :

Route::post('/contact', 'BasisController@postContactEmail')->name('postContact');

My controller postContactEmail method :

public function postContactEmail(Request $req){
    dd(
        $req->ajax(),
        $req->isXmlHttpRequest(),
        $req->all()
    );

    return response()->json(['success' => 'Got Simple Ajax Request.']);
}

And for a reason I do ignore, my $req->ajax() always return false.

I have tried many things before asking my first question here and nothing works, especially that this same code works well till now so I have really no clue at all.

The only different thing is my Laravel version has changed from 5.8 to 6.2.

I dont know why my form does not send data correctly, my header request :

Accept  
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding 
gzip, deflate, br
Accept-Language 
fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Connection  
keep-alive
Content-Length  
149
Content-Type    
application/x-www-form-urlencoded
Cookie  
__cfduid=da74c7ad6c9ff7514e482…E_OPTINVEST_CONSENT=1; _gat=1
Host    
fake-site.tld
Referer 
https://fake-site.tld/
TE  
Trailers
Upgrade-Insecure-Requests   
1
User-Agent  
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/69.0

And my header response :

cf-cache-status 
DYNAMIC
cf-ray  
5254def1febccdd7-CDG
content-encoding    
br
content-type    
text/html; charset=UTF-8
date    
Sun, 13 Oct 2019 22:50:09 GMT
expect-ct   
max-age=604800, report-uri="ht….com/cdn-cgi/beacon/expect-ct"
server  
cloudflare
vary    
Accept-Encoding
X-Firefox-Spdy  
h2

P.S.: my jquery version is 2.2.4 (even with the version 3.4.1, the behaviour is the same, $req->ajax() will always return false)

2

Answers


  1. It looks like you’re not providing the X-Requested-With header, and that Request::ajax just checks for the existence of this header (or at least used to.)

    Check out this question: Laravel angularjs Request::ajax() always false

    See this question for providing the header with jQuery.ajax: Cross-Domain AJAX doesn't send X-Requested-With header

    Login or Signup to reply.
  2. Thank both of you =)

    Exposing my problems here helps me also to resolve them ^^

    I got my issue resolve by only “pushing” the ajax script in the main layout, at the end, before the tag, like this :

    <form method="post" action="{{ route('postContact') }}" id="id_post_contact">
        @csrf
        <input class="form-control" type="text" name="in_email" placeholder="[email protected]">
        [...]
        <button class="btn" type="submit">Submit Question</button>
    </form>
    
    @push('stack_js_foot')
        <script>
            $("#id_post_contact").submit(function(e) {
                e.preventDefault();
    
                var form = $(this);
                var url = form.attr('action');
                var data2Send = form.serialize();
    
                $.ajax({
                    type:'POST',
                    url:url,
                    headers:{
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    data:data2Send,
                    dataType:'JSON',
                    cache:false,
                    //contentType:'application/json',
                    success: function(data) {
                        alert(data.success);
                    }
                });
            });
        </script>
    @endpush
    

    From my point of view, I still do not understand this behaviour… I always though that we can trigger/declare a javascript anywhere, as long as it’s encapsulated in a tag. And that was what I do till now (with success)

    If anyone has an idea why, I will be glad to listen/learn =)

    Thank you again for your helping

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search