André Carvalho André Carvalho - 14 days ago 6
Javascript Question

Why is my Ajax not working?

I'm trying to use the Marvel API to do a school project so I've made a function to make a request to the Marvel server but I only receive the following back.

object

What is the problem?



function GetComic() {
var publicKey = 'e99561b7db2b414b085c39de1c7ed4ab';
var privateKey = 'dc00398114b3a9a4fbd20d8a318d54530c11659f';
var timestamp = Date.now();;
$.ajax({
url: 'https://gateway.marvel.com/v1/public/comics',
type: 'GET',
dataType: 'json',
data: {
apikey: publicKey,
hash: md5(timestamp + privateKey + publicKey),
ts: timestamp
}
})
.done(function() {
console.log("success");
})
.fail(function(r) {
console.log(r);
})
.always(function() {
console.log("complete");
});

}

$('#btSearch').click(function() {
GetComic();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="inputSearch">
</div>
<button type="submit" class="btn btn-default" id="btSearch">Search</button>
</form>





Thanks.

Answer

Your ajax function seem to correct but I did't see where you define the response for it so try this. Then we'll see what you get.

.done(function(response) {
    console.log("success",response);
})

Update

You said that your ajax not work when you add button. It's because when you use the button it's will submit your form then the page is reload. So to make it's not submit the form. You can just easy edit your click event like this.

$('#btSearch').click(function(e) {
    e.preventDefault();  //add this line to prevent form to submit
    GetComic();
});