Sun Z Sun Z - 6 days ago 7
jQuery Question

Access an external variable (Ajax call)

How can I can use the URL that was requested using Ajax request with jQuery in a another Ajax call request?

For example: this is the Ajax requested url:


http://www.google.com?action=search


This is my first Ajax call using button 1:

function display_url1() {
jQuery.ajax({
type: 'GET',
url: 'http://www.google.com?action=search',
success: function(msg) {
$('#show_results').html(msg);
}
});
}


With the second Ajax request (Using button2) I want to call this url:


http://www.google.com?action=search&category=sport


Something like that:

function display_url2() {
jQuery.ajax({
type: 'GET',
url: 'THE FIRST URL + &category=sport',
success: function(msg) {
$('#show_results').html(msg);
}
});
}


So with the new Ajax request I want to add &category=sport to the first url.
So my question is how to access an external variable created with another call

Answer

So have a variable and use it in both calls. Something like:

var url = "http://www.example.com?q=1";

function display_url1(){
  makeCall(url);
}

function display_url2(){
  makeCall(url + "&foo=bar");
}


function makeCall(url) {
  jQuery.ajax({
    type: 'GET',
    url: url,
    success: function(msg) {
      $('#show_results').html(msg);
    }
  });
}

Edit based n comment...

var url;
function display_url1(){
  url = "http://www.example.com?q=1";
  makeCall(url);
}

function display_url2(){
  makeCall(url + "&foo=bar");
}


function makeCall(url) {
  jQuery.ajax({
    type: 'GET',
    url: url,
    success: function(msg) {
      $('#show_results').html(msg);
    }
  });
}
Comments