SivaRajini
SivaRajini

Reputation: 7375

$.ajax not working in mvc4

Please refer below code

var pdf="xxxxxxx";

 $.ajax({
            type: "post",
            url: "/Corporate/SampleChangeSummary/PDF",
            data: JSON.stringify(pdf),
            contentType: 'application/json',
            dataType: 'json',
            error: function (status, xhr) {

            }
        });


[HttpPost]
        public ActionResult PDF(object pdf)
        {
.......
}

but it returning pdf is null. What is the problem? Any syntax mistake in my code?

Upvotes: 0

Views: 72

Answers (4)

Ramppy Dumppy
Ramppy Dumppy

Reputation: 2817

  var pdf="xxxxxxx";

   $.ajax({
        type: "post",
        url: "/Corporate/SampleChangeSummary/PDF",
        data: { "pdf" : pdf },
        dataType: 'json',
        error: function (status, xhr) {

        }
    });


  [HttpPost]
    public ActionResult PDF(object pdf)
    {
       .......
    }

you don't need to stringify your pdf because it is already string try to pass it directly to your controller.

Upvotes: 0

arnoldrob
arnoldrob

Reputation: 823

Try somthing like this

$.ajax({
         type: "POST",
         url: '/Corporate/SampleChangeSummary/PDF',
         data: { pdf: JSON.stringify(pdf) },
         success: function (data) {
                    //do somthing with the result
                  },
         error: function (error) {
                    alert('Please try again!');
                }
        });

Upvotes: 0

Faron
Faron

Reputation: 1243

I believe that contentType is what causing the issue. In that script of yours, you were telling your $.ajax() that it is sending JSON string, but you had it sending a .pdf. Instead, just remove contentType line and try it.

Secondly, dataType: 'json' is telling your $.ajax() that it is expecting the response in JSON format. If that's what you are doing, then you dont have to worry about that line.

EDITED:

Found more information - if you wanted to keep contentType then, revise to this: contentType: application/pdf', and add header('Content-type: application/pdf'); on your php file that your $.ajax() is sending to.

Upvotes: 1

Ricardo Pieper
Ricardo Pieper

Reputation: 2702

Try this:

$.ajax({
    type: "post",
    url: "/Corporate/SampleChangeSummary/PDF",
    data: JSON.stringify({pdf: pdf}),
    contentType: 'application/json',
    dataType: 'json',
    error: function (status, xhr) { }
});

ASP.NET MVC requires you to send a 'key-value' JSON object so it can bind accordingly. Also, change object pdf to string pdf.

Upvotes: 0

Related Questions