简体   繁体   中英

Trouble sending json data from controller to ajax

I have an ajax/json/c# issue. I think I'm doing everything that I've read in other posts but still not working right. Very likely pilot error but i am missing it.

Any ideas appreciated.

Data is grabbed from an email form and is sent to the controller to send an email. The email gets sent! That works.

I try to return data to ajax but that doesn't seem to be working.

    [HttpPost]
    public JsonResult Sendemail(EmailStuff emailstuff)
    {
        string msg = sendmail(emailstuff); //this works fine - msg is returned as "ok"
        if (msg=="ok")
        {
            SendAutoReply();// this gets done
            return Json(new { success = true, message = msg }, JsonRequestBehavior.AllowGet);
        }
        return Json(new { success = false, message = msg }, JsonRequestBehavior.AllowGet); 
    }
//jquery
    $('#emailbtn').on('click', function (event) {
    //...get form data...
        var myData = {
            UserName: name, UserEmail: email, UserPhone: phone, UserAddress: address,
            UserSubject: subject, UserMessage: msg, UserList: emList
        };
    $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            processData: false,
            dataType: "json",
            url: $('#baseurl').text() + "email/sendemail",

            data: JSON.stringify(myData),
            success: function (response) {
                if (response.success === true) {
                    window.location = "email-ok";
                } else {
                    window.location = "email-error?msg="+response.message;
                }
            },
            error: function (response) {
                window.location = "email-error?msg=uhoh";
    })
})

In the controller the string msg is set to "ok".

My expectation is that the ajax success: function will be triggered and then the if statement will evaluate response.success and redirect to the email-ok or email-error page.

But what happens is the error: function is called and the redirect is to the email-error page with the message "uhoh"

Only test I know to do is Chrome DevTools>Network>XHR>Preview and this shows: Failed to Load Response Data

So it looks like the response object is not being sent correctly.

Thanks in advance

EDIT The response header is showing a 500 error - not sure what that's about

    Response Header from Dev Tools
    cache-control: private
    cf-ray: 4daaae4d1eca9f46-IAD
    content-type: text/html; charset=utf-8
    date: Wed, 22 May 2019 00:30:20 GMT
    expect-ct: max-age=604800, report-uri="https://report- 
    uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
    server: cloudflare
    status: 500
    x-aspnet-version: 4.0.30319
    x-aspnetmvc-version: 5.2
    x-powered-by: ASP.NET

EDIT 2

There is an error showing up in 2nd line shown below, error says "Failed to load resource, the server responded with a status of 500"

    //line 3954 of jquery-3.2.1.min.js.formatted 
    try {
            h.send(b.hasContent && b.data || null)
        } catch (i) {
          if (c)
             throw i
       }

Seems I had 2 (stupid) issues that overlapped. In addition to the SendAutoReply shown in the controller code there was also a save operation that I didn't show here. I had removed both to test but at the same time Intellisence suggested that I changed the return statement to a tuple

FROM CORRECT

    return Json(new { success = false, message = msg }, JsonRequestBehavior.AllowGet); 

to WRONG

    return Json(( success = false, message = msg ), JsonRequestBehavior.AllowGet); 
~~~

So there were 2 problems. I corrected the Json statement but it took me a while to  
remove the Save statement - once I did that it worked.  Still not sure why there was a 500 error
Thanks for the suggestions

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