简体   繁体   中英

How to use Ajax call to a specific controller action?

I am trying to use Ajax to reload data from a database. However, the Ajax doesn't call the controller action that I specified in the url: . Here is my Ajax code:

function selectFieldChanged(id){
    $.ajax({
        type: "POST",
        url: Routing.generate('demo_ajax'),
        data: id,
        success: function(){
            alert("Success");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert('Error : ' + errorThrown);
        }
    });
}

$(document).ready(function(){
    var id = $(this).val();
    $('#form_patient').change(function(){selectFieldChanged(id)});
});

The routing.xml :

demo_ajax:
    pattern: /ajax/patient
    defaults: { _controller: DemoBundle:Default:index}
    options:
        expose: true

So, I tried to simply echo the value out in the indexAction to see whether it is called or not.

public function indexAction(Request $request)
{   
        if($request->isXmlHttpRequest()){
            echo "xmlHttpRequest is called";
        }
        if($request->getMethod()=='POST'){
            echo 'POST is called';
        }
}

However, I didn't get anything from the indexAction but I got the alert message, `Success , from my Ajax What did I do wrong?

The success callback receives data from your server so a variable must be declared to capture it:

success: function(data){ // <-----

    console.log(data);

    alert("Success");

},

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