0

I am trying to send 2 variables in a JQuery Ajax call, but for some reason, both variables end up bundled in the first one:

function getNextQuestion(answer, queryType)
{    
    $.ajax
    ({
        async: false,
        url: 'handlers/question_hdlr.php',
        type: 'POST',
        data: "answer="+ answer +"&queryType=" + queryType,
        dataType: "json",
        success: function(result)
        {
           ...
        },error: function(XMLHttpRequest, textStatus, errorThrown)
        {
           alert ("error: "+textStatus);
        }
    });
    return false;
}

When I run it in the debugger, I get only one variable:

$_POST["answer"], containing "answerqueryTypequeryType"

$_POST["queryType"] does not exist.

What am I doing wrong?

2 Answers 2

3

You shouldn't have to manually serialize your data. Just pass an object and jQuery will serialize it for you.

$.ajax({
    ...
    data: { answer: answer, queryType: queryType }
});

Also, never issue AJAX requests with async:false. There's never a valid reason to use a synchronous XHR request.

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

4 Comments

Sorry, I just found out what the problem was. Both codes work, but my browser was still using a cached copy of a previous version of the js file which had a typo in it.
What's the issue with async:false? The workflow involves going from one question to the next, nothing else. I don't want the user to go off and do anything else on the site until the next question is loaded. Isn't that what async:false does?
@Sylverdrag: Synchronous XHR freezes the entire browser UI, which is embarrassingly bad UX. See this relevant answer.
Outch, my bad. Thanks for pointing that out to me. It's actually a serious weakness if anyone can crash the browser just by asking resources over and over again
0

Just found out that there is nothing wrong in the code in the question, the only problem was that the Javascript file cached by the browser contained a typo and even though the problem was fixed on the working copy, the browser was never actually running it.

The solution was to add the date & time to the script url as a parameter to prevent the browser from using the cached version:

<script type="text/javascript" src="<?= $pathRoot ?>js/commline.js?<?= date(U);?>" />

This works fine.

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.