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.

qqruza
  • 1,275
  • 4
  • 19
  • 38
  • What is `var id = jQuery(this).attr('pid');` supposed to do in the context of `$(document).ready` callback? – John Dvorak Dec 27 '12 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 – Netorica Dec 27 '12 at 10:19
  • guys I need to get 1256 from url and insert it into "$.ajax({ url:" so it will work like url: 'http://www.domain.com/?post_type=news&post_id=1256, – qqruza Dec 27 '12 at 10:23
  • Then see asgoth's question. – John Dvorak Dec 27 '12 at 10:23

1 Answers1

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');
   ...
Community
  • 1
  • 1
asgoth
  • 34,208
  • 12
  • 85
  • 94
  • 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. – qqruza Dec 27 '12 at 10:25
  • 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. – asgoth Dec 27 '12 at 10:27
  • I have got an error now: Uncaught ReferenceError: getQueryVariable is not defined – qqruza Dec 27 '12 at 10:28
  • I've edited my answer. Replace the '...' by the contents of the getQueryVariable function from the link. – asgoth Dec 27 '12 at 10:34
  • It shows another error in jquery 1.8.2 "Uncaught TypeError: Cannot read property 'length' of undefined" – qqruza Dec 27 '12 at 10:37