简体   繁体   中英

How to send AJAX data from VIEW to CONTROLLER? (PHP(MVC)+AJAX)

I have http://visiting/blog page.

Controller contains action_index and add_index methods. Action_index() return indexes pages. Add_index() call model's method add_data() , which insert data from form to the database.

I need organize my application with ajax-request, that http://visiting/blog page not to refresh after submitting the form.

VIEW

    $.ajax({
        type: 'POST',
        url: '???',   --------------------------> What should URL contain?
        data: $(this).serialize()

CONTROLLER

    function action_add() {

        $title = $this->cleanStr($_POST["title_field"]);
        $text = $this->cleanStr($_POST["text_field"]);



        if ($title!="" && $text!="") {
            $this->model->add_data($title, $text);              
        } else {
            throw new Exception("Data is empty");
        }

    }

MODEL

   public function add_data($title, $text) {
        try {
            $query="INSERT INTO post (title, text) VALUES('$title', '$text')";
            self::$db->query($query);
        } catch(Exception $e) {
            echo $e->getMessage();
        }
    }

VIEW
It is a full html file with ajax-request. I want to handle form, that the page isn't refreshed and data is sent to the database.

  <div class="blog">
    <h1> Blog </h1>
    <form onsubmit="return validate()" id="add_form">
        <fieldset>
            <legend>Add new post:</legend>
            <label>Title:</label><br>
            <input type="text" name="title_field" id="titlef">
            <br>
            <label>Text:</label>
            <br>
            <textarea name="text_field" id="textf"></textarea>
            <br>
            <input onclick="return validate(); return false" type="submit" value="Submit">
            <input onclick="return resetclass()" type="reset" value="Reset">
        </fieldset>
    </form>

    <div class="blogposts">
        <div id='response'></div>
        <?php
            foreach ($data as $values) {
                echo "<div class=\"blog_item\">";
                echo "<h4 class=\"blog_item_title\">" . $values["title"] . "</h4>" . 
                "<div class=\"blog_item_text\">" . $values["text"] . "</div>" .
                "<div class=\"blog_item_time\">" . $values["time"] . "</div>";
                echo "</div>";
            }
        ?>
    </div>
</div>
<script>
$(document).ready(function(){
    $('#add_form').submit(function(){

        // show that something is loading
        $('#response').html("<b style=\"font-size:20px; margin:40px;\"\">Loading ...</b>");


        $.ajax({
            type: 'POST',
            url: '???',   ------------> What should be into url?
            data: $(this).serialize()
        })
        .done(function(data){

            // show the response
            $('#response').html(data);

        })
        .fail(function() {

                // just in case posting your form failed
                alert( "Posting failed." );

        });
        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

the url should be the path to your controller method you would like to hit. you do not have to include the basepath in the url (but you can if you want to). so something like:

url: "howeverYourStructureIs/Action_index",

to hit method action_index(). You can think of ajax like "as if you were to hit the page, but not actually navigating to that page" kinda thing. So however you would normally hit that method, is the url you put in the ajax call.

hope this helps

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