CodeCannibal
CodeCannibal

Reputation: 344

jQuery ajax call does not open requested site

I got a

<button id="myid">

in my HTML code. In my JS-file I try to catch the click event and call a specific URL - just like clicking a normal HTML-link.

This is what I did:

$('#myid').on('click', function () {
    doSomething();
});

var doSomething = function () {
    $.ajax({
        url: "/targetURL",
        type: "GET",
        cache: false,
        async: true,
        error: function (error) {
            console.log(error);
        }
    });
}

So - the URL is called, but the response is not shown - I guess because this is a ajax call. But how can I handle that?

Upvotes: 0

Views: 45

Answers (3)

Chamila
Chamila

Reputation: 1

To catch the response data, You need to add success function like the error function.

var doSomething = function () {
$.ajax({
    url: "/targetURL",
    type: "GET",
    cache: false,
    async: true,
    success: function(response){
        console.log(response);
    },
    error: function (error) {
        console.log(error);
    }
});

}

Or if you only want to open an another url like normal html, you should use JS window objet

var doSomething = function () {
    window.open('/targetURL');
}

Upvotes: 0

Quentin
Quentin

Reputation: 944441

The entire point of Ajax is that it doesn't cause navigation but gives the response to JavaScript instead.

If you want to navigate to the new page, don't use Ajax.

Use a link.

If you want it to look like a button, apply CSS to it.

Upvotes: 0

Krzysztof Janiszewski
Krzysztof Janiszewski

Reputation: 3854

The same way as you handle the error function you should handle the success() function which triggers if the ajax call is succesfull.

Also you don't need to set async: true because it is set to true by default.

Add .preventDefualt() to click function to make sure that when you click the button the only thing is happening is the function that you want to trigger.

$('#myid').on('click', function(e) {
    e.preventDefault();
    doSomething();
});

var doSomething= function(){
    $.ajax({
        url: "/targetURL",
        type: "GET",
        cache: false,
        success: function(data) {
            console.log(data);
        }
        error: function(error) {
            console.log(error);
        }
    });
}

The data parameter in the success() function the data that ajax returns. So when you log into the console you can see the structre so that you know what to do with it later.

Upvotes: 1

Related Questions