kruthirshanks
kruthirshanks

Reputation: 171

jQuery/Ajax success method implementation

I have the following jQuery function on DOM ready:

$.ajax({
  url : '/weather/',
  type: 'GET',
  //dataType : "json",
  success : function(data) {
    alert("success");
    var jsondata = Object.keys(data);
    alert(jsondata);
    location = "testing";

    alert(data.weather);
    weather = data.weather;
    $("location").text(location);
  }
  }).setTimeout(executeQuery, 500);

The ajax call returns a proper json which I am using to change the values of my html. However, when this line executes,

$("location").text(location);

the page gets redirected to a url which appends the value of 'location' from the above line. I have used these lines elsewhere, without using success function call.

Can someone help me with what I should do to prevent this redirect from happening?

Upvotes: 0

Views: 105

Answers (2)

Montagist
Montagist

Reputation: 401

For one, your class or id selector is invalid. Should be either:

$(".location").text(location);

or

$("#location").text(location);

Depending on whether your html markup uses a class or id of "location", respectively.

Also, in this particular case, your lack of the word var:

var location = "testing";

Is causing the browser to assume the top level window scope. window.location is the property that redirects when you set it's value.

Upvotes: 4

Amit Joki
Amit Joki

Reputation: 59292

No, the problem lies in variable name you are using.

Don't use location since, if you assign any string to location, it redirects to the given string.

Like location="http://nettpals.com"; will redirect to my site.

Use any other variable name like loc

Also, if you are targeting a class, prefix it with . and if you are targeting id, prefix it with #

Like $('.location') or $('#location').

When you use $('location'), you are trying to match location element <location></location>, which obviously is not what you want.

Upvotes: 2

Related Questions