Reputation: 85
I'm trying to get the response of a GET request inside a textfield on my webpage using jquery. Currently, I have the following code with which I can get the response on the console.
$(document).on('click', '#get-button', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
data: '',
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
$(document).on('click', '#post-button', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
Below is a part of the HTML code where I want to fit the response(in JSON) format.
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-danger">
<div class="panel-heading">JSON Response</div>
<div class="panel-body text-danger">
<textarea class="form-control" rows="8" placeholder="server response"></textarea>
</div>
</div>
</div>
</div>
Upvotes: 1
Views: 5236
Reputation: 11620
.
$(document).ready(function(){
$('#get-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
success: function(response) {
console.log(response);
$('.form-control').val(response); // personally I would give your textbox an ID
}
});
return false;
});
$('#post-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response) {
console.log(response);
$('.form-control').val(response);
}
});
return false;
});
})
If your URL are correct, this will work.
Just remember that after you get the response, and you will get a JSON object, you will have to convert it to String using JSON.stringify().
I will try to explain. In Javascript we have Objects and simple types (boolean, String, float, etc). When we want to print a simple type, we just see it's value. But when we want to display a Object, JS engine has a problem, because each object can be very big, complex. Thats why when printing an object or JSON (witch is an Object) we get [Object]. Luckilly JSON is so popular that JS has an default methods for serializing String to JSON (JSON.parse(someString)) and other way around (JSON.stringify(JSONObject)).
Upvotes: 2