Having trouble getting JSON data from database with AJAX - javascript

So as the title suggests, I am having difficulty retrieving data from my database with these technologies. This is my current situation:
var username = $('#username').val();
var password = $('#password').val();
// For the sake of example this is a dummy IP
var url = 'http://55.55.55.55/dbfuncts.php?action=getuser&user=' + username;
// For debugging purposes I compare this object with the one I get with the ajax function
var obj1 = {
"name" : "Dave"
};
var obj = $.ajax({
url: url,
type: 'POST',
dataType: 'json'
});
The format of my JSON is supposed to be like this:
{"UserID":"User","Password":"User","Email":"User#questionmark.com","Fname":"Web","Lname":"User","isManager":"0"}
When I go to the URL I am able to see this JSON string in my browser.
Currently when debugging, I find that I keep getting the jqXHR object instead of the json object that I want.
How do I retrieve the information as a JSON from the database?

I don't think jQuery ajax call will return the result directly as you did (but I'm not sure).
I used to get result from ajax call by using callback function as below.
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(data) {
// data argument is the result you want
console.log(data);
}
});

Try this:
Place the url which gives the json data in the url column.
var jsonData = $.ajax({
url: '*',
dataType:"json",
async: false
}).responseText;
var parsed = JSON.parse(jsonData);
If this does not then try this:
var jsonData1 = $.ajax({
xhrFields: { withCredentials: true },
type:'GET',
url: '*',
dataType:"json",
crossDomain: true,
async: false
}).responseText;
var parsed1 = JSON.parse(jsonData1);
TRY 2:
Ok so try it with Spring MVC. Get the data from the database, and keep it in a url. As given in this link. Ckick Here And then use the above ajax call to access the data from the url.

Related

Print JSON string from URL

I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});

How to Select DuckDuckGo Element. AJAX

I'm trying to use AJAX to gather search results from DuckDuckGo's Search API.
Here's the JavaScript I've written so far:
$.ajax({
type: 'GET',
url: 'https://api.duckduckgo.com/',
data: { q: myhomestate, format: 'json', pretty: 1 },
jsonpCallback: 'jsonp',
listLocation: "RelatedTopics",
dataType: 'text'
}).then(function (data) {
console.log(data);
});
}
The code works fine, but it just returns a big JSON object, and I don't know how to select any of its elements. Please help!
data = JSON.parse(data);
turns it into a normal JavaScript object. Then you can select elements like you would any other object.
e.g.
var heading = data.Heading;
var developer = data.meta.developer[0].name
First you need to convert JSON response into JSON Object, as shown below :
var jsonObj = JSON.parse(data);
Then you can access, it's fields as shown below :
console.log(jsonObj["RelatedTopics"]);

List from Javascript to Post Method c#

Hi everyone i have a problem on javascript for pass the list from the result of form to post method in c#.
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#runProcess').click(function() {
var request = new WebPay();// is only a method where i take the result from the fiel of the form
var list = new Array();
list.push(JSON.stringify(request));
var jsonstr = {'':list};
$.ajax({
type: "POST"
url: "http://localhost:4556/Pay_Info"
datatype: "JSON",
data: jsonstr,
traditional: true,
success:function (data,textStatus, jqHr){
//build a grid with jquery
The post method is :
public HttpResponseMessage Pay_Info([FromBody] List Pay)
The fields are good i mean when i take the result from a form i have the right Json String but when i pass the array (list) in the post method the fields are empty i mean i have only the default fields of the form and not my json string result. The problem is when i pass the array to the post method.
Can you help me ??
list.push(JSON.stringify(request));
var jsonstr = {'':list};
You can not have object with empty key.make it like
list.push(request);
var jsonstr = JSON.stringify(list);
So with:
var list = new Array();
list.push(JSON.stringify(request));
var jsonstr = { '' : list };
$.ajax({
type: "POST",
url: "http://localhost:4556/Pay_Info",
dataType: "json",
data: jsonstr,
traditional: true,
something pass in the post method but the fields are with default values and not with my json string value. When i debug the count of the list is 1
With:
list.push(request);
var jsonstr = JSON.stringify(list);
$.ajax({
type: "POST",
url: "http://localhost:4556/Pay_Info",
dataType: "json",
data: jsonstr,
traditional: true,
In the list of post method the count was 0 and nothing pass
With:
var jsonstr = {Key:list}; or var jsonstr = {"Pay":list};
The count of the list in post method is 0 so nothing is passed

Can we send data to controller till my array gets empty?

I have big array which exceed request object length so i am thinking to send data to controller in small data frames so that it will not get crashed on extending http request object limit and data will in after certain interval of time.....
var param = "&table=" + table; //remove first three charactor 'btn' from id
param = param + "&tblheader=" + tblheader;
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
dataType: 'text',
contentType: 'application/text; charset=utf-8'
});
controller :
[HttpPost]
public ActionResult SendReport(string table, string tblheader)
{
}
I Thinks your url isnt validate :
check this code please :
var param = { Table: table
Tblheader: tblheader }; //json data
var request = $.ajax({
url: '../Reports/SendReport'
data: param,
type: 'POST',
cache: false,
dataType: 'json',
contentType: 'application/text; charset=utf-8'
});
Create Json object and send using ajax
var ajaxPostDatastr = '{"table":"' + table + '","tblheader":"'+tblheader+'" }';
var jsonData = JSON.parse(ajaxPostDatastr);
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
contentType: 'application/text; charset=utf-8',
data: jsonData});
In controller use same as what you did right now.
Hope this will solve your issue
You can send large data via JSON. But you need to increase the maxlength of the json data in web.config.
Refer the post : Getting "The JSON request was too large to be deserialized"
All above way right to send data but when we are using
var param = "&table=" + table; //remove first three charactor 'btn' from id
param = param + "&tblheader=" + tblheader;
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
dataType: 'text',
contentType: 'application/text; charset=utf-8'
});
then we are passing data as a parameter to the $.ajax then it has a certain limit around param.length = 1600 then after $.ajax fail to execute
if you want to send huge data then you have to use View Model object and assign this values on data so it will work easily..
because as i m using Asp.net MVC ,in that view model is strongly bonded to view.so we can assign .if nay having better soln please share

How to retrieve JSON variables from a AJAX response

When I tried to fetch the values from a JSON response, I stucked up. Here is my code
Code:
$.ajax({
url: 'checkvotes.php',
dataType: "json",
success: function(data) {
// want to fetch UP and DOWN variables from JSON here
}
});
AJAX Response from PHP
{"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]}
$.ajax({
url: 'checkvotes.php',
dataType: "json",
success: function(data) {
var up = data.sample[0].up;
var down = data.sample[0].down;
}
});
Try data.sample[0].up and data.sample[0].down. If in doubt, use this JavaScript to emulate the call:
var data = {"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]};
Run that in a debugger and examine data.
var up = data['sample'][0]['up'],
down = data['sample'][0]['down']
just print a console.log(data) to inspect your json

Categories

Resources