javascript - How to send AJAX data from VIEW to CONTROLLER? (PHP(MVC)+AJAX) - Stack Overflow

admin2025-04-21  1

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/blogpage 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>

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/blogpage 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>
Share Improve this question edited Jan 5, 2015 at 13:43 Taryn 248k57 gold badges371 silver badges408 bronze badges asked Jan 2, 2015 at 13:53 Dmytro BorysovskyiDmytro Borysovskyi 311 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745215608a290830.html

最新回复(0)