简体   繁体   中英

Load target ajax php file on initial page load

I have an AJAX setup in php to return and dispaly some data from DB:

$("#sub_shops").click(function(){
                    var range_start = $("#start_shops").val();
                    var range_end = $("#end_shops").val();
                    $.ajax({
                        url:'process_shops.php',
                        data:{start:range_start,end:range_end},
                        type:'POST',
                        success:function(data){
                            $("#result_shops").html(data);
                        }
                    });
                });

There are two inputs on page #start_shops and #end_shops , after filling in data and clicking #sub_shops page sends values from inputs to process_shops.php . After processing, it displays the results in #result_shops :

<div id="result_shops"></div>

The question:

If there are default values are set for #start_shops and #end_shops inputs, how do I send it's values to process_shops.php and display processed results in #result_shops on initial page load ?

Thanks in advance!

First break your code out into a function:

function updateResultShops()
{
    var range_start = $("#start_shops").val();
    var range_end = $("#end_shops").val();
    $.ajax({
       ...
}

Then call it from the click handler:

$("#sub_shops").click(updateResultShops);

And on document load!

$(document).ready(updateResultShops);

Now any initial values will be sent immediately when the page loads, and every time you click. Easy!

If the values are pre-loaded in the inputs, I think the easiest way would be

$("#sub_shops").click(function(){
    // your code...
}).trigger('click');

You could turn the anonymous function into a function.

 function loadAjax() { /* Commented this part since it wont run on the snippet. var range_start = $("#start_shops").val(); var range_end = $("#end_shops").val(); $.ajax({ url:'process_shops.php', data:{start:range_start,end:range_end}, type:'POST', success:function(data){ $("#result_shops").html(data); } }); */ alert("blablabla"); } $("#sub_shops").click(loadAjax); //Add event to click $(document).ready(loadAjax); //Add event to run when page loads. 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="background-color: black; height: 50px; width: 50px;" id="sub_shops"></div> 

But if you wish to leave the function inside the click... you can do this:

$(document).ready($("#sub_shops").click);

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