You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.4中使用jQuery Ajax无刷新插入数据求助

Hey there! Let's fix your Ajax form submission step by step. I know you've been grinding on this for days, so let's get this sorted out smoothly.

First, let's break down the issues in your current code
  • The live() method was removed from jQuery years ago — we need to use on() instead for event binding
  • You're listening to the change event, but we should be targeting the form's submit event (so it triggers when the button is clicked)
  • You didn't stop the form's default submission behavior, which is why the page still refreshes
  • The form data serialization was placed incorrectly, and we need to make sure Laravel's required CSRF token is included in the Ajax request
  • Your controller returns a redirect, which Ajax will interpret as raw HTML instead of a usable success message
Step-by-step fixes

1. Update your frontend form & Ajax script

Replace your existing script with this — it listens for the form submit, blocks the default refresh, serializes all form data (including the CSRF token), and handles the response properly:

<form id="frm" method="POST" action="{{ url('post_job') }}">
    {{ csrf_field() }}
    <input name="title" type="text" required />
    <br>
    <input name="nature" type="text" required />
    <br>
    <textarea rows="4" cols="50" name="description" required></textarea>
    <input type="submit" value="Update post">
</form>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
    // Listen for the form's submit event
    $('#frm').on('submit', function(e) {
        // Stop the form from reloading the page
        e.preventDefault();
        
        // Serialize all form data (including the CSRF token)
        var formData = $(this).serialize();
        
        // Send the Ajax request
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'), // Use the form's action attribute for flexibility
            data: formData,
            success: function(response) {
                // Show success feedback
                alert(response.message);
                // Optional: Clear the form after successful submission
                $('#frm')[0].reset();
            },
            error: function(xhr) {
                // Handle submission errors
                alert('Oops, something went wrong. Please try again.');
                // Check the console for detailed error info
                console.log(xhr.responseText);
            }
        });
    });
});
</script>

2. Adjust your controller logic

Instead of returning a redirect (which doesn't work for Ajax), we'll send a JSON response that the frontend can easily parse:

use Illuminate\Support\Facades\Session;

public function store(Request $request) {
    // Optional (but highly recommended): Validate incoming data
    $request->validate([
        'title' => 'required|string',
        'nature' => 'required|string',
        'description' => 'required|string',
    ]);

    // Note: Laravel model names should be capitalized (PSR-1 standard)
    $recruitment = new \App\Models\Recruitment();
    $recruitment->title = $request->title;
    $recruitment->nature = $request->nature;
    $recruitment->description = $request->description;
    $recruitment->save();

    // Return a JSON response with success details
    return response()->json([
        'message' => 'Post done successfully',
        'data' => $recruitment // Optional: Send back the created record if needed
    ]);
}

Quick extra tips

  • Make sure you're using a modern jQuery version (the one in the script above is current)
  • If you want to replace the alert with a nicer on-page message, add a container like <div id="feedback"></div> to your blade file, then use $('#feedback').text(response.message).addClass('success'); in the success callback
  • Double-check your model class name follows Laravel conventions (capitalized, singular) — this avoids unexpected errors

That should get your no-refresh data insertion working perfectly. Test it out, and if you hit any specific errors, feel free to share details!

内容的提问来源于stack exchange,提问作者Mujahidur Rahman Mithun IUB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:31:40