0

I'm getting an ajax failed when working with symfony2 in ajax.

Any ideas?

HTML

              $.ajax({
                  url: "{{ path('destination_app_ajax') }}",
                     type: "post",
                     data: {
                         "json" : JsonData
                     },
                     success: function(JsonData){  
                          $('#result').html(JsonData);

                          /* Clear all Data */  
                          JsonData = "";
                          localStorage.clear();
                          alert("Data Sent!");

                     },
                      error:function(){
                          alert('ajax failed');    
                      }   
                }); 

Controller

public function ajaxAction(){

    $json = json_encode($_POST);

    return new Response(array('json' => $json));


}
1
  • Just a comment but you should have a look at the JsonResponse object class in Symfony2. more useful than manually encoding your response, and it sets appropriate headers etc. Additionally, you should look further into what error status you are getting from the server on the jQuery side - jQuery.ajax().error() has the following method signature: Type: Function(jqXHR jqXHR, String textStatus, String errorThrown). A status code can go a long way in debugging... Commented Feb 26, 2014 at 16:25

2 Answers 2

1

Your response should look like this:

public function ajaxAction(){

    $json = json_encode(array('json' => $_POST));

    return new Response($json, 200, array('Content-Type'=>'application/json'));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man I had to also add use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; to top
Sure, that goes without saying. If you use object, add use statement.
1

Try this,

echo  json_encode(array('json' => $_POST));

Script:

    $.ajax({
        url: "{{ path('destination_app_ajax') }}",
           type: "post",
           data: {
               "json" : JsonData
           },
           success: function(data){  
                $('#result').html(data.json);
                /* Clear all Data */                    
                localStorage.clear();
                alert("Data Sent!");

           },
            error:function(){
                alert('ajax failed');    
            }   
      }); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.