Link to home
Start Free TrialLog in
Avatar of Eddie Shipman
Eddie ShipmanFlag for United States of America

asked on

Using Ajax to upload JSON to WebApi function

I'm rather new to this WebApi stuff and this is my WebApi function:
    [HttpPost]
    [Route("api/UploadToArchive")]
    public IHttpActionResult UploadToArchive([FromBody]string JSON)
    {
        Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(JSON);
        int PID = (int)jObject["PID"];
        string LT = (string)jObject["LT"];
        string HTML = System.Web.HttpUtility.HtmlDecode((string)jObject["HTML"]); 
        string Title = System.Web.HttpUtility.HtmlDecode((string)jObject["Title"]);

        string lt2 = getLT(PID.ToString());
        if (lt2 == LT)
        {
            // Upload the file to the archive using the UpdateArchive() function:
            _Repository.UpdateArchive(HTML, Title, "", PID);
            return Ok(PID);
        }
        else
        {
            return BadRequest("Invalid LT");
        }
    }

Open in new window

I've got the following Ajax code to send json data to my WebAPI. I have encoded HTML string in one of the fields being posted. All my fields are converted to JSON before sending.
    $.ajax({
        async: true,
        cache: false,
        type: 'POST',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        url: upload_url,
        data: JSON.stringify(post_data),
        dataType: 'json',
        beforeSend: function () {
            console.log('Fired prior to the request');
        },
        success: function (data) {
            console.log('Fired when the request is successfull');
            $('.document').append('<p>' + 'UploadTest:' + JSON.stringify(data) + '</p>');
        },
        error: function(jqxhr, errorText, errorThrown) {
            console.log('Error Thrown');
            $('.document').append('<p>' + 'UploadTest:' + upload_url + "</br>" + $(this).data + '</p>');
        },
        complete: function () {
            console.log('Fired when the request is complete');
        }
    
    });

Open in new window

I put a break point on the first line of my WebAPI function and JSON is null. What is the problem and how do I fix it?

Note: I'm only using ajax in my test, I will be converting to PHP cURL when I get the WebAPi functionality working.
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Eddie Shipman

ASKER

@leakim971, I need to be able to send files of different types, it may be binary, it may be text, The code above doesn't show that, however. How would I write the class to be able to accept different file types?
your question talk about sending JSON to WebApi
We're now sending binary, you CANNOT send binary file using JSON.
Forget what I said. I changed my mind. I will be sending just form fields and have created the class. Am looking into how it is being sent, now.
So I modified to this but my upload class is empty, null strings and PID = 0.

    [HttpPost]
    [Route("api/UploadToArchive")]
    public IHttpActionResult UploadToArchive(ArchiveUpload upload)
    {
        string HTML = upload.HTML;
        string Title = upload.Title;
        string LT = upload.LT;
        int ParticipantID = upload.PID;

        string lt2 = getLT(PID.ToString());
        if (lt2 == LT)
        {
            // Upload the file to the archive using the UpdateArchive() function:
            _Repository.UpdateArchive(HTML, Title, "", PID);
            return Ok(PID);
        }
        else
        {
            return BadRequest("Invalid LT");
        }
    }

Open in new window


ArchiveUpload class:
    public class ArchiveUpload
    {
        public string LT { get; set; }
        public int PID { get; set; }
        public string Title { get; set; }
        public string HTML { get; set; }
    }

Open in new window


HTML form:
    <body>
        <div class="document">
            <a class="upload" id="ul" href="#">Upload to Archive test</a><br />
            <textarea id="html">
                <span>usually have some long HTML posted here</span>
            </textarea>
        </div>
    </body>

Open in new window

javascript to post:
    var vLT = 'c40210542a253a8357e1c0b0e3eb82235fd1a68626';
    $(function () {
        $('.document').on('click', '.upload', function (e) {
            e.preventDefault();
            var post_data = {PID: 1158341,
                             Title: "CFL Confirmation",
                             LT: vLT,
                             HTML: $("#html").val()
                            };
            var upload_url = 'http://localhost:49494/api/UploadToArchive/';
            $.ajax({
                async: true,
                cache: false,
                type: 'POST',
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                url: upload_url,
                data: JSON.stringify(post_data),
                dataType: 'json',
                beforeSend: function () {
                    console.log('Fired prior to the request');
                },
                success: function (data) {
                    console.log('Fired when the request is successfull');
                    $('.document').append('<p>' + 'UploadTest:' + JSON.stringify(data) + '</p>');
                },
                error: function(jqxhr, errorText, errorThrown) {
                    console.log('Error Thrown');
                    $('.document').append('<p>' + 'UploadTest:' + upload_url + "</br>" + jqxhr.responsetext + '</p>');
                },
                complete: function () {
                    console.log('Fired when the request is complete');
                }
    
            });
        });
    });//]]>

Open in new window

Controls you post to the server need to have a name property whose value matches the model's corresponding property name. id is only useful for getting to a control via Javascript. In other words, your <textarea> needs to be:

<textarea id="html" name="html">

Open in new window

don't strinfigy your data :
 data: JSON.stringify(post_data),
just use :
 data: post_data,
@kaufmed, name is not needed when doing it like this. Adding the class and removing the JSON.stringify was the solution. I now have it working.
Thanks to both of you. Now to convert the ajax to PHP cURL...
I did not realize you were hard-coding the data into the AJAX call. I just assumed it was coming from the form. Whatever works, I guess   = )
@kaufmed, It is going to be passed to the PHP script that will send the data.