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

Gabotronix's avatar

Not getting any response from ajax call

Hi, I'm kind of new to ajax so I'm having asome issues, I'm doing a POST ajax call to a controller method wich sends an email, the ajax call itself is a success but I'm not getting any JSON response, error or anything to know what's happening with the data. How could I solve this?

This is my code:

JQuery AJAX call

$(document).ready(function(){
    
    
    var message_body = $("input[name='message']").val();
        
    $(".sendmail_action").click(function(e){
        alert('clicked');
        /* prevent link from directing to page */
        e.preventDefault();
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({

            url: '/contactar',
            type: 'POST',
            data: {message_body},
            dataType: 'JSON',
            
            success: function (data) { 
                alert('success');
                //console.log('yesss');
            }
            
            /*error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
            }*/

        }); 
    });
    
    
    
    
});

Logic inside my controller:

public function contactar(Request $request)
    {
        
        $destination_mail = Config::get('globals.client_mail');
        
        
        $validator = Validator::make($request->all(), [
        
            'message_body' => 'required|min:10'
            
        ]);
        
        if ($validator->fails())
        {
            
            return response()->json(['errors'=>$validator->errors()->all()]);
        }
        
        else
        {
            Mail::to($destination_mail)->send(new ContactMail());
            
            return response()->json(['success'=>'Message sent']);
        }
    }
0 likes
4 replies
burlresearch's avatar

Try logging your data and checking the logs - if there is an error it should pop right after you dump the request data - this may help you see what's happening.

public function contactar(Request $request)
{
    \Log::debug(__METHOD__, $request->all());
    // ...
}
Gabotronix's avatar

Loggin only showed this in the log file: [2018-06-25 14:10:10] local.DEBUG: App\Http\Controllers\ContactController::contactar

What I did now is add console logging json response (success message and errors) like this:

$(document).ready(function(){
    
    
    var message_body = $("input[name='message']").val();
        
    $(".sendmail_action").click(function(e){
        alert('clicked');
        /* prevent link from directing to page */
        e.preventDefault();
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({

            url: '/contactar',
            type: 'POST',
            data: {message_body},
            dataType: 'JSON',
            
            success: function (data) { 
                console.log(data.success);
                console.log(data.errors);
            }
            
            /*error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
            }*/

        }); 
    });
    
    
    
    
});

I am getting this message error: ["The message body field is required."]

This is pretty weird as I'm fairly certain I'm sending the data correctly, any help??

Dalma's avatar

I'm not an ajax expert but, the syntax for your data differs from mine, the following worked for me in my view data was name: value combo.

I also needed to pass the csrt_token

           var token = "{{csrf_token()}}";
            var todo_id = $('#id_show').val();
            var myurl = "{{url('updatetodo')}}" +"/"+ todo_id;
            $.ajax({
                type: 'PUT',
                url: myurl,
                dataType: 'JSON',
                data: {
                    '_token': token,
                    '_method': 'PUT',
                    'id' : todo_id,
                    'due': $('#due_show').val(),
                    'assignedto': $('#assignedto_show').val(),
                    'description': $('#description_show').val(),
                    'notes': $('#notes_show').val(),
                    'status': $('#status_show').val()
                },

In my controller

   public function updateajax(Request $request, $id)
    {
        $this->validate($request, [
            'description' => 'required',
            'notes'       => 'required',
            'status'      => 'required',
            'due'         => 'required'
        ]);
        $requestData = $request->all();
Cronix's avatar
var message_body = $("input[name='message']").val();
//...
data: {message_body},

You're not sending key/value pairs for your data. Just like form attributes need names, so do the parameters you're sending. So the key "message_body" is missing from the request.

should be:

data: { message_body: message_body }
1 like

Please or to participate in this conversation.