简体   繁体   中英

Not working : Send POST Data with Ajax to a Symfony2 Controller

I would like to send Post Data to a Symfony Controller, but it doesn't work. When I send my data with AJAX, it is sending the POST data, but it is showing red link in the console with no error message or status; but 200ok in net FF. It is sending the request successfully through a normal form.

Here is my Javascript code:

function addprivate() {
    var form_data = $('#private_tuition').serialize();
    var getTeamsUrl = Routing.generate('addprivatetuition', {
        id: form_data
    });
    $.ajax({
        type: "post",
        url: getTeamsUrl,
        data: form_data,
        success: function(response) {
            if (response) {

            } else {

            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $.notify('Error : Record not found !!', {
                "status": "danger",
                "pos": "top-center"
            });
        }
    });
}

Below is the form tag and js funxtion:

<form method="post" role="form" id='private_tuition' action="{{base_url}}/privatetutionpdf/" >
    <button type="submit" class='btn btn-primary' onclick='addprivate()' name="btn-save">
        <strong>Generate PDF for client</strong>
    </button>

Here is the PHP Symfony Controller method which received data:

namespace Suntec\Marcus\AssignmentBundle\Controller;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
....
    /*****************************************************************/
    /**
    * @Route("/addprivatetuition", name="addprivatetuition", options={"expose"=true})
    * @Template()
    */
    public function addprivatetuitionAction(){

        return array();
        //return array();
    }
...

}

looks like you have to prevent the default action of the form, because when you click your submit button the html form will be submitted.

to only submit via javascript do sth. like:

$('#private_tuition').submit(function(e){ 
   e.preventDefault();    
}

or

$('#private_tuition').submit(function(){ 
    return false;    
}

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