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"]);
Related
I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.
Having a few problems creating a products index.
It looks like you're pushing down html as well in the products.php page. Make sure the output of the php that you're retrieving from only returns JSON.
Also, check the syntax on your script:
$.get({
type: "GET",
url: "products2.php",
data: 'id=' + userid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("decription").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
document.getElementById("stock").innerHTML = data[3];
}
});
You were using $rows but attempting to access data. Adding a simple console.log(data); in the success function will dump the results to the console in chrome/firefox so you can see what is being returned. (Be sure to check the network tab as well, as it can give you some tips as to why the data isn't being properly fetched.)
I've done something similar and this worked fine for me:
<?php
$array['status'] = 0;
...
echo json_encode($array);
Populate the array with whatever you need.
And then:
$.ajax({
type: "type",
url: "url",
data: {
data: data
},
success: function (data) {
console.log(data.status);
}
});
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.
This is something I recently found out, I have the following piece of code in JS:
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(data) {
var places = JSON.parse(data);
// do something
},
error: function(data) {
// do something else
}
});
The data returned from my backend is indeed in JSON format, and var places = JSON.parse(data); this line works perfectly in Chrome and Firefox, it parses my JSON data into a JS list; however, in Safari, var places = JSON.parse(data); gives me error, because data is already a JS list. Instead of doing var places = JSON.parse(data), just changing to var places = data solved the error, I am wondering why it is converted automatically?
Thanks in advance
Your best solution would be to tell jQuery that the response is json so that you will always receive it as js object
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(obj) {
// do something
},
error: function(data) {
// do something else
},
dataType: 'json' // reponse is json so it will always be pre-parsed
});
I'm getting an xml answer from a server using jquery and I need to have one of its child nodes as a string to further work with it.
Here is my code:
function pollServer(dataObject) {
$.ajax({
type: "POST",
url: '/server.php',
data: dataObject,
success: function (data) {
$xmlDoc = $(data);
$listen = $xmlDoc.find('listen');
console.log($listen);
},
dataType: 'xml'
});
}
I already tried using (new XMLSerializer()).serializeToString(listen) but that gives me an empty string.
The following should work fine for XML:
var listen = $("listen", data)[0].outerHTML;