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
595 views
in Technique[技术] by (71.8m points)

javascript - Ajax not calling success function

I'm using ajax to validate a from without reloadind the page.

Script Ajax

    function updateResult(tab){
            $.ajax({
                url:"requeteSpecimen.php",
                data:{datas:tab},
                dataType: 'text',
                async:false,
                success: function(data){
                    document.getElementById('resultat').innerHTML = '<p>'+data+'</p>';
                },
                error: function(data){
                    document.getElementById('resultat').innerHTML = '<p>ERROR</p>';
                }
            });
    }

    $("#filtre").submit(function(){
        <?php $tab=$this->request->data; ?>
        updateResult(<?php json_encode($tab);?>);
    });

</script>

requeteSpecimen.php

<?php echo "Success"; ?>

My problem is that ajax do not call the sucess function, I always have the "ERROR" text appearing ...

For the moment I don't have yet the code of my requeteSpecimen.php file and I just would like the success function to be called. Don't know if it can help but I'm using cakePHP 3.0.

Many thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You do not call actions like that in Cakephp.

First set up an Action in one of your Controllers call the url from your $.ajax function like this.

function updateResult(tab){
        $.ajax({
            url:"/controller/request_specimen",
            data:{datas:tab},
            dataType: 'text',
            async:false,
            success: function(data){
                document.getElementById('resultat').innerHTML = '<p>'+data+'</p>';
            },
            error: function(data){
                document.getElementById('resultat').innerHTML = '<p>ERROR</p>';
            }
        });
}

You could later on add a route for request_specimen and make it prettier.

In your Controller there should be a method called: public function request_specimen() {} Wich will handle the ajax request like so: if($this->request->is(['ajax']) { /* Handle request */}

The data sent to the function will be in $this->request->data;


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

...