1

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="contact@email.com">
    [...]
    <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)

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
  • Could you please provide screenshots from your browser's _Network_ console of the request headers? It's easier than trying to make sense of the copied text you have in the question – Phil Oct 13 '19 at 23:51
  • I just notice your comment ^^ will do it ASAP, thanks –  Oct 14 '19 at 10:31

2 Answers2

0

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="contact@email.com">
    [...]
    <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

  • It's possible that not all your DOM nodes were initialized before your script ran. This is why web developers usually include their js in other file(s) that are called when the DOM is loaded. For more info on that check out window.onload, $(document).ready, and window.domcontentloaded – Barn on a Hill Oct 14 '19 at 23:32
-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

Barn on a Hill
  • 359
  • 3
  • 10
  • OP is using jQuery which certainly does include that header – Phil Oct 13 '19 at 23:45
  • 1
    Not necessarily if jQuery thinks the request is cross-domain. Regardless, I don't see it in the request header OP provided. – Barn on a Hill Oct 13 '19 at 23:47
  • Fair call. Everything here looks like it should be treated as a same-domain request though. – Phil Oct 13 '19 at 23:48
  • Thank you for your reply, I will check ^^ about the **X-Requested-With** I tried to force it but none of my attempts work, and for a reason I ignore, the header keeps sending the post request without the **X-Requested-With** header :/ By the way, I remember now one other difference. On laravel 5.8, I have used the [Laravel Force Https package](https://github.com/yaroslawww/laravel-force-https) which is no more compatible with laravel 6.2 Maybe it is here to focus on... –  Oct 14 '19 at 08:15