3

I have a situation where I am building the json data to post dynamically. so I create it in a for loop and then attempt to use the $.ajax command, but on the server side the model is null. If I hard code the data section as would be normal, it works fine. I tried the same process with a simple model just to check and the same happens.

So this works:

$.ajax({
            url: '@Url.Action("SetupQuestions", "Login")',
            type: 'POST',
            dataType: 'json',
            cache: false,
            data: {SharedSecret: 'Bob'},     
            success: function (data, status, xhr) {
                $('#divMFAQuestion').html(data).fadeIn('slow');
            },
            error: function (xhr, status, error) {
                alert("MFA Challenge Error (b): " +  error);
            }
        });

But this doesn't:

        var datastring = '{SharedSecret: Bob}';
        $.ajax({
            url: '@Url.Action("SetupQuestions", "Login")',
            type: 'POST',
            dataType: 'json',
            cache: false,
            processData: false,
            data: JSON.stringify(datastring),                
            success: function (data, status, xhr) {
                $('#divMFAQuestion').html(data).fadeIn('slow');
            },
            error: function (xhr, status, error) {
                alert("MFA Challenge Error (b): " +  error);
            }
        });

Nor this:

 var datastring = 'SharedSecret: Bob';

Any thoughts?

1
  • You have quotes around your json in datastring. Commented Oct 28, 2015 at 16:44

1 Answer 1

4

You have quotes around your entire JSON data structure:

var datastring = '{SharedSecret: Bob}';

JSON.stringify expects a JSON structure, so the quotes should only be around the string part for JSON.stringify to work:

var datastring = {SharedSecret: 'Bob'};

However, the reason that your AJAX call is not working is that the data parameter accepts a JSON data structure. JSON.stringify will serialize it as a string, which data does not expect. So you need to just pass the fixed datastring without JSON.stringify.

data: datastring
Sign up to request clarification or add additional context in comments.

2 Comments

More correctly, shouldn't it be {SharedSecret: 'Bob'}?
Works after removing the processData = false and JSON.stringify(). ThankS!

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.