Ben Cahan
Ben Cahan

Reputation: 63

Converting .POST into equivalent .AJAX

I need to change one of my .post javascript calls to an equivalent .ajax call, but I can't seem to make it work. (I need to make it asynchronous, and the post does not allow that extra option).

The original working .post call is the following:

          $.post('includes/save_my_note.php', { pagenum: lastpage, userid: <?php echo $logged_user_id; ?>, subid: <?php echo $snipid; ?>, thenote: mynote, doctype: dtype, fileid: <?php echo $file_id; ?> });

It is a combination of javascript variables and inserted php variables, but it works perfectly in my code, calls the function and passes in all the variables via the $_POST variables.

In trying to turn this into the exactly equivalent .ajax call, I turned it into the following:

        $.ajax({
            type: 'POST',
            url: "includes/save_my_note.php",
            data: "{ pagenum: " +lastpage+ ", userid: <?php echo $logged_user_id; ?>, subid: <?php echo $snipid; ?>, thenote: " +mynote+ ", doctype: " +dtype+ ", fileid: <?php echo $file_id; ?> }"
        });

From looking at the .post and .ajax documentation, I think these should be identical in their execution, but it isn't working.

Anyone know the correct syntax to turn my post call into an ajax call? I must be missing something unless there is more going on behind the scenes than I know.

Upvotes: 0

Views: 451

Answers (2)

devnull69
devnull69

Reputation: 16544

The difference between

"{ pagenum: " +lastpage+ ", userid: <?php echo $logged_user_id; ?>, subid: <?php echo $snipid; ?>, thenote: " +mynote+ ", doctype: " +dtype+ ", fileid: <?php echo $file_id; ?> }"

and

{ pagenum: lastpage, userid: <?php echo $logged_user_id; ?>, subid: <?php echo $snipid; ?>, thenote: mynote, doctype: dtype, fileid: <?php echo $file_id; ?> }

is essential here. The former is a string, the latter an object literal. Only the latter will work here. If you want to use a string, you should do it like this

data: "pagenum=" + lastpage + "&userid= .....

Upvotes: 1

benesch
benesch

Reputation: 5269

$.post is asynchronous by default. Do you mean you want to make it synchronous?

In that case, don't bother with $.ajax. Just call

$.ajaxSetup({async:false});

before you call .post(). Careful, though: synchronous requests often cause the browser to "lock up", which is quite ugly and scares users. Could a simple loading indicator on an asynchronous request do the trick?

Upvotes: 0

Related Questions