简体   繁体   中英

Call AJAX from a PHP script

I am aware that I can call PHP scripts after processing an AJAX request, but am I able to do it the other way around?

I am writing a dynamically sized navigation component for a new website and I want to refresh the nav every time a new item is added to the Menu.

In my menu class I am currently thinking of using this approach to achieve the effect:

public static function new_item($label, $link) {

    $pos = self::num_items();        

    $DB = Database::getInstance();

    $query = $DB->connection->prepare("INSERT INTO menu VALUES('', :label, :link, :pos )");
    $query->execute(array(':label'=>$label,
                          ':link' =>$link,
                          ':pos'  =>$pos+=1  
                   ));

    ?>

    <script>

        function refreshHeader() {
            $.ajax({
                type: "GET",
                url:  "my url",
                success: function() {
                    // refresh the header here somehow
                }
            });
        }

    </script>

    <?php
}

However, every time this runs I see nothing in my console (even when I put a valid url into my function), will I be able to achieve what I want this way or would I be better processing appending the tab to the document via AJAX and then calling the insert method in my Menu class on the success callback?

The only reason I ask is I feel this way may look neater in comparison to the other way of handling it, although I may be completely wrong.

Any feedback would be greatly appreciated - cheers Alex.

echoing the following line can call out existing javascript functions and you are even able to insert variables (only strings and ints though).

echo "<style onload='jsfunction(\"$vars\")'></style>";

I find this one of the most simple ways to do this quickly.

Oh, I now understand what you want to do, what you need is websockets. When a piece of php code (sever side) is executed, you want something to happen in the browser (client side). Take a look at how live chats are made with javascript and websockets, long polling and other similar methods, that's what you need here.

This helped me a lot What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

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