简体   繁体   中英

Submit form input value on page load with ajax

I have form and a input in it and I want to send its value to my controller.I wanna send its value when a page load or refresh current page using ajax and jquery because my page reload when I write submit function in body tags onload event. Here is my code:

<form method="post" id="counterForm" name="counterForm">
    @csrf
    <input type="number" name="count" id="count" value="{{ $visit->counts }}">
</form>

Script code:

$(window).load(function(){
                    var n=document.getElementById("count").value;
                    $.ajax({
                        type:'POST',
                        url:'/count',
                        data:n,
                    });
                });

My controller file :

public function count(Request $request)
    {
        $value=($request->count)+1;
        DB::table('visitorcounter')->update(['counts'=>$value]);
    }

That was my code but its not working...Thanks.

you can use .submit() :

Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

you code would be like :

$(window).load(function() {

     $('#counterForm').submit(function(){return true;});
});

Check out this example: :

$(window).load(function(){
    // this is the id of the form
    var url = "results.php"; // the script where you handle the form input.
    $.ajax({
           type: "POST",
           url: url,
           data:$( "#myformR" ).serialize(),
           dataType: "html", //expect html to be returned                
           success: function (response) {
                $("#prores").html(response);
            }
         });
});

I found it ... We can create a visitor counter very very simply by using a table with one integer column and a DB::table('test')->increment('count'); in AppServiceProvider Boot function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM