Progger
Progger

Reputation: 2254

Trying to set variable as part of URL in jquery ajax post

So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:

$.ajax({

type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
    $('#data_box').html(data);
    }
});

Here is my problem:

When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.

Thanks!

Upvotes: 0

Views: 1920

Answers (3)

bokonic
bokonic

Reputation: 1771

Are you rendering this in PHP? In that case you need to do:

url: '/groups/dissolve/<?php print $org_ID; ?>'

Otherwise, you need to do something like

var org_id = 'foo'; 
// or
var org_id = '<?php print $org_id ?>';
$.ajax({

type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
    $('#data_box').html(data);
    }
});

Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.

If you're trying to POST a variable (org_id) then you should put it in data:

data['org_id'] = org_id;

$.ajax({

type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
    $('#data_box').html(data);
    }
});

While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.

Upvotes: 2

Pablo
Pablo

Reputation: 6058

Short answer, concatinate

url: '/groups/dissolve/' + $org_ID

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

It's not clear in the question where your data comes from, but you can use something like:

url: '/groups/dissolve/'+orgId,

or:

url: '/groups/dissolve/?orgId='+orgId,

Upvotes: 0

Related Questions