Creighton Fowler Creighton Fowler - 4 months ago 10
jQuery Question

Is it possible to redirect to a webpage if a value is a certain number?

I have my website checking another website for a value, and returning back with the results. I'm trying to get my page to redirect me, if I have a certain value.

Is this possible?

Here is my code. `



<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/2fd6657d79448494/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>




Answer

Simply check the value inside the success function of an AJAX function, there use window.location = "http://www.example.com" to do a javascript redirect.

In this example if temp is > 80 then the redirect happens!! (which is at the time of writing this post!!). The code runner below will show 404 or server error because example.com is not a valid page.

jQuery(document).ready(function($) {
  $.ajax({
    url: "http://api.wunderground.com/api/2fd6657d79448494/geolookup/conditions/q/IA/Cedar_Rapids.json",
    dataType: "jsonp",
    success: function(parsed_json) {
      var location = parsed_json['location']['city'];
      var temp_f = parsed_json['current_observation']['temp_f'];
      alert("Current temperature in " + location + " is: " + temp_f);
      if (temp_f > 80) {
        window.location = "www.example.com";
      }
    }
  });
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

Comments