Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - Please help use AJAX on my self made PHP framework

I have made a simple php MVC framework for my project which works perfectly unless I try to implement some AJAX. So here is the case: I have a simple form for adding product, that passes the data to controller for processing. Simplified controller code:

    public function add()
{
        $data = [
                'name' =>check_input($_POST['name']),
                'price' =>check_input($_POST['price']),
                'name_err' => '',
                'price_err' => ''
            ];

            //Validate Name
            if (empty($data['name'])) {
                $data['name_err'] = 'Please enter the product name';
            }
            //Validate price
            if (empty($data['price'])) {
                $data['price_err'] = 'Please enter the product price';
            }

            //Make sure no errors
            if (empty($data['name_err']) && empty($data['price_err']) ) {
                //Validated
                $this->productModel->addProduct($data);
                header('location: product/list.php');
            } else {
                //Load the view with errors, $data with errors is accesible in the addForm file
                require_once 'products/addForm.php';
            }
}

So now the task is to make it so, that when there are errors, the form page loads with errors without refreshing the page. If its ok, than it redirects to product list page as it does already (with refreshing or without it doesnt matter)

This is my JS code, that I tried to make for this, but ran into a deep issues.

<script>
    var form = document.getElementById("addForm");
    form.addEventListener("submit", function (e) {
        e.preventDefault();
        
        var xhr = new XMLHttpRequest();
        var formData = new FormData(form);
        
        xhr.open("post", "<?= URLROOT; ?>/products/add", true);
        xhr.onload = function() {
            if (xhr.response == 'somehow to determine that there is no errors') {
                //it continues to redirecting as usual
            } else {
                //Here I thought I could load the entire document body which would be with errors already
                var responsebox = document.getElementById("body");
                responsebox.innerHTML = xhr.responseText;

                //Or to recieve a separate error variables and put them into the error box
                var responsebox = document.getElementById("errorbox");
                responsebox.innerHTML = xhr.responseText;
            }
        }
        xhr.send(formData);
    });
  1. First of all, how do I continue the redirect in controller which is going on already? is possible to switch from JS back to php execution?

  2. Second, how can I differentiate what is given in respone in xhr.response? The .responseType is empty, getResponseHeader('content-type') is always returning me text/html. I tried to make return json_encode($data) in my controller, and then in JS check if the response is Json or not, but could not find any function for that

  3. Maybe it would be easier to rewrite the entire JS code, or use JQuery instead? I have very little experience in these languages, so if you have any idea on how to redo it I would really appreciate your help. The controller outputs can be changed as well.

question from:https://stackoverflow.com/questions/66055785/please-help-use-ajax-on-my-self-made-php-framework

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...