0

I am trying to get the URL variable (pid) into the ajax request (url) and haven't got any success.

My url is: www.domain.com/news.html?pid=1256

My java script:

$(document).ready(function() {
var output = $('#news');
var id = jQuery(this).attr('pid');

$.ajax({
    url: 'http://www.domain.com/?post_type=news&post_id=' + id,
    async: false,
    callback: 'callback',
    crossDomain: true,
    contentType: 'application/json; charset=utf-8',
    type: 'POST',
    dataType: 'jsonp',
    timeout: 5000,
    success: function(data, status) {
        $.each(data.posts, function(i, item) {
            var news = '<div>' + item.title + '</div><div>' + item.content + '</div><hr/>';

            output.append(news);


        });
    },
    error: function() {
        output.text('There was an error loading the data.');
    }
});})

Thanks a lot for you help.

4
  • What is var id = jQuery(this).attr('pid'); supposed to do in the context of $(document).ready callback? Commented Dec 27, 2012 at 10:19
  • in what element you trying to get the pid attribute? you define it with this and it means your selecting your whole html document as you get document object Commented Dec 27, 2012 at 10:19
  • guys I need to get 1256 from url and insert it into "$.ajax({ url:" so it will work like url: 'domain.com/?post_type=news&post_id=1256, Commented Dec 27, 2012 at 10:23
  • Then see asgoth's question. Commented Dec 27, 2012 at 10:23

1 Answer 1

2

If I understand correctly, you want to get the query param 'pid' from your current page?

You can get the query params via window.location.search.

To get a specific param, you should create a getQueryVariable() function.

So in your case:

var getQueryVariable = function(variable) {
   ...
};
$(document).ready(function() {
   var output = $('#news');    
   var id = getQueryVariable('pid');
   ...
Sign up to request clarification or add additional context in comments.

5 Comments

Hi asgoth, sorry I am not a guru in java at all. Would you please drop me a line here how to do it. Really appreciate your help.
Eh? It's javascript... Did you check the link? Just copy paste the function into your code and replace your 'var id' line by the one above.
I have got an error now: Uncaught ReferenceError: getQueryVariable is not defined
I've edited my answer. Replace the '...' by the contents of the getQueryVariable function from the link.
It shows another error in jquery 1.8.2 "Uncaught TypeError: Cannot read property 'length' of undefined"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.