Populate a html div with json data received from a server - javascript

I need to have a html div populated with the json data received from the server which is a json-rpc server and it retruns an application/jsson-rpc content type and i can see the result in the chrome and firefox dev tools... I need to view it as part of the page inside a given div
i have this script to populate the mybox div but it gives nothing
var returnedinfo;
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
I also tied having the populating function outside the ajax block when the request is done
request.done(function(msg) {
$("#mybox").text(msg);
});
This just return an empty array like this
[object Object]
and nothing else help will be appreciated.

you need to append the key of the json item.
$("#mybox").html(json.key);

Add dataType to your ajax request.
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});

try this my working example
look contentType and html function to replace html of mybox element
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: 'url',
success: function (dataRes) {
$('#mybox').html(dataRes);
},
error: function(a,b,c) {
}
});
Note that in this case dataRes in success function is an html string like <strong>test</strong>. If your server side function returns a json object you should add dataType: 'json' to ajax request and then you can use properties of dataRes object like here $('#mybox').html(dataRes.property1);

Related

Change 'src' attribute of images by AJAX response

I'm trying to change src attribute of image by ajax request,
$.ajax({
url: "/l/"+id1,
type: "get",
dataType: "json",
success: function (data) {
$data = $(data);
$("#like" + id1).attr("src",$data");
}
});
Response is something like /uploads/like.png
Without dataType: "json" , I receive error:
Syntax error, unrecognized expression: /uploads/like.png
(So Ajax works and response is received) , after adding dataType:"json" error gone but nothing more happens.
HTML part (produced by server):
(every image has different id1, e.q id1=33 , so response goes to each selected image.)
<img id="like33" src="/uploads/default.png" />
You could do something like this:
$.ajax({
url: "/l/"+id1,
type: "get",
dataType: "json",
success: function (data) {
$("#like" + id1).attr("src", data);
}
});
If you are receiving the string /uploads/like.png in the ajax response, you can just pass it into the attr() method.
Hope it helps.

Ajax Request: Json Data Not Being Passed to Controller

I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});

ERROR: bad URI when sending data as JSON with GET method to a Rails resource

Hello I'm performing a GET request on a RESTful Rails resource, like so:
function getGroups(category) {
$.ajax({
type: 'GET',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "category":category }),
success: function(data) {alert(data)},
contentType: "application/json",
dataType: 'json'
});
});
getGroups("own_groups");
The problem is that Webrick server errors out like this:
ERROR bad URI
`/groups.json?{%22access_token%22:%22569669d8df0456%22,%22category%22:%22own_groups%22}'.
It must be something related with how the JSON data is parsed, because I am having no problems with another GET request WITHOUT JSON data, and a POST request WITH JSON data...
Update: adding code for POST request (where JSON.stringify is required)
function addGroup(name, description) {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "group_name":name, "group_description":description}),
success: function(data) { alert("ok")},
contentType: "application/json",
dataType: 'json'
});
};
addGroup("nice group", "full of people");
Do not use JSON.stringify. Simply put:
data: {"access_token":"569669d8df0456", "category":category },
Moreover, you do not need to specify complete url http://localhost:3000/groups.json, it can be just simply groups.json

Ajax response not showing in JS

I have an AJAX script like this
function savetoDB(inp) {
var userID = (FB.getAuthResponse() || {}).userID;
jQuery.ajax({
url: URL,
type: 'GET',
data:{ 'input': JSON.stringify(inp) },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function(msg) {
console.log(msg);
alert(msg);
}
});
}
The problem I am facing is that the php returns (echo's) some string , but I am unable to see it in alert.
I used the inspect element and Inside inspect element I can see the Response, and also the status is 200, what could be the reason that it is not showing the response in alert?
You are returning a JSON object, so it won't show in alert, which only displays strings. Convert it to a string first:
success: function(msg) {
console.log(msg);
alert(JSON.stringify(msg));
}
Replace "URL" with the actual url of file you're extracting data from otherwise you'll get an empty response as is the case.

How to use the response of Ajax Post

I make an ajax POST request to post JSON data to server, and I get a simple text response. I can see that everything works fine because it is shown in the browser's debugger. However, I cannot use it.
callajax1(Callback);
function callajax1(callbackfn) {
$.ajax({
type: "POST",
url: myUrl,
data: JSON.stringify({ Data: data }),
contentType: "text/plain; charset=utf-8",
dataType: "json",
success: function (data2) {
callbackfn(data2);
},
failure: function (errMsg) {
}
});
return false;
}
function Callback(data) {
alert(data);
}
No alert is showing.
You say that you are getting a "simple text response" back, but your JavaScript (dataType: "json") says to ignore the content type of the response and parse it as JSON.
Perhaps (since you are sending JSON and claiming it is plain text) you are confusing dataType (override the content type the server returns) and contentType (describe the data you are sending).
If the response is "simple text" and not JSON then you can't parse it as JSON. Either return JSON or use dataType: 'text'.
if result of ajax is text, datatype should be text
if result of ajax is html, datatype should be html
if result of ajax is json, datatype should be json
if result of ajax is xml, datatype should be xml
dataType tell jQuery to parse result in given dataType, default is 'text', though jQuery is intelligent enough to detect which conversion is required.
you can see the answer here:
http://jsfiddle.net/justtal/x9re9/
function callajax1(callbackfn) {
$.ajax({
type: "GET",
url: 'https://gdata.youtube.com/feeds/api/videos',
/*data: JSON.stringify({ Data: data }),*/
/*contentType: "text/plain; charset=utf-8",*/
/*dataType: "json",*/
success: function (data2) {
callbackfn(data2);
},
failure: function (errMsg) {
callbackfn(errMsg);
}
});
return false;
}
var Callback = function (data) {
alert(data);
}
callajax1(Callback);

Categories