I'm making an API call with this code:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
})
That returns nothing, except for an error in the console saying:
"Uncaught TypeError: Cannot read property 'item' of undefined"
The JSON data looks like this when I use the url in the browser:
{
"folder": {
"item": 123123,
"item 2": false,
"item 3": "content",
"item 4": [
{
"subitem": "content"
},
{
"subitem": "content2"
}
]
}
}
I was expecting "123123" in the alertbox, but nope. So what am I doing wrong?
If its a JSON string you are getting it will need to be parsed. Try this:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
var parsed = JSON.parse(data);
alert(parsed.folder.item);
}
});
Or to force jquery to parse it for you:
$.ajax({
type: "GET",
url: "https://example/example.json",
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
});
Related
I'm using ajax and javascript for a game and I created a server using json-server where I keep a db.json file with words that the user can input and become available in the game.
db.json
This is what the json file looks like
{
"words": [
{
"cuvant": "cuvant",
"id": 1
},
{
"cuvant": "masina",
"id": 2
},
{
"cuvant": "oaie",
"id": 3
},
{
"cuvant": "carte",
"id": 4
},
{
"cuvant": "fmi",
"id": 5
},
{
"cuvant": "birou",
"id": 6
},
{
"cuvant": "birou",
"id": 7
},
{
"cuvant": "canapea",
"id": 8
},
{
"cuvant": "pasare",
"id": 9
I managed to get the POST request (adding the words to the db.json) using this:
function addWord() {
var word = document.getElementById("input-name").value;
var info = {
cuvant: word
}
$.ajax({
url:'http://localhost:3000/words',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(info),
succes: function(info) {
console.log(info)
},
error: function(error) {
console.log(error);
}
})
}
This is what I tried for the GET request
But I'm not sure if it's correct.
And I also need a way to get only the value hold by the cuvant key and add it into an array.
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
contentType: "application/json",
succes: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I think your code is correct. It was just missing the "s" on "success":
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I am firing an ajaxcall on page load and getting an array back. Now for each element called groupId present in the array, I have to fire another ajaxcall to get the group name and group notes.
Now I need to create a final array that would have the array returned from the first ajaxcall and merged with the corresponding group name and info returned from the second call.
This is the array returned from the first ajaxcall:
[{
"customMessage": "THis is the first message",
"groupIdx": 13
}, {
"customMessage": "This is the second message",
"groupIdx": 14
}]
Which I am getting by doing:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
});
Now to this I am appending a .each function and calling another ajaxcall.
This is the final code:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
}).each(dataObj, function(j, data) {
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/group/"/>' + data.groupIdx + '/info',
dataType: "json"
}).
My question is: How do I get the data returned from the .each function and append it to the original object?
$.each() function must be inside of .done() function.
Update: According to the last comment:
You should use Array#filter.
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
Something like this:
$(function() {
var vueInst = {
preVisitInstructions: []
};
var result = [];
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/17455e3ef90fb3cf096d1f051d4331e5/raw/ad51c85e7722a83e7085ad63e26a524b769efe50/firstData.json",
dataType: "json"
}).done(function(response1) {
$.each(response1, function(j, data) {
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/e610dd23f830b108bc1e24c78f66b3b6/raw/54851535eedd1e94a1a944ddf3d63412e83349f8/secondData.json",
dataType: "json"
}).done(function(response2) {
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
result.push(data);
});
vueInst.preVisitInstructions = result;
});
});
$("#btnCheck").on("click", function() {
console.log(JSON.stringify(vueInst.preVisitInstructions));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnCheck">Check data</button>
The result should be:
[{
"customMessage": "THis is the first message",
"groupIdx": 13,
"data": [
]
},
{
"customMessage": "This is the second message",
"groupIdx": 14,
"data": [{
"groupId": 14,
"groupName": "Test 1",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 2",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 3",
"groupNotes": "THis is a note"
}
]
}
]
I was wondering if it is possible to pass an array to a php function using the jQuery AJAX function. I have the following as my javascript
arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}
$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'field01': arr_data["field01"],
'field02': arr_data["field02"],
'field03': arr_data["field03"],
'field04': arr_data["field04"]
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});
When I try to do the following though
arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}
$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'data': arr_data
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});
I receive it in the PHP as "Array". How can I correctly send the object so that it is usable by the PHP function?
Please try to pass the array in the format of json. Then use the get the json in your php and access the json array.
<script>
arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}
var myJsonString= JSON.stringify(arr_data);
$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'data': myJsonString
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});
</script>
this is your java script. and below is the php
$dataJson=json_decode($_GET['data']);
here you can get the json array and loop through it and do what ever you want.
Please have try at this. This is working in my case.
from the second ajax you can access the data based on the property names like: $_GET['data']['field01']
$_GET['data'] is the js object converted in php in a associative array
try this :
$.ajax({
url: "scripts/php/phpfunc.php",
method: "POST",
dataType: "json",
data: {
'action': "exec_find",
'data': arr_data.serialize()
},
serialize()
http://api.jquery.com/serialize/
convert your array in string
Hi everyone i am working on phone gap project and using the ajax web services. I am sending request using the following code:
var credentials = {
"name": "nouman",
"email": "noumandilawar#gmail.com",
"mobile_number": 03324412764,
"employee_number": 4556,
"gender": 1,
"password": "1234567891234567",
"language": 1
};
function GetMember() {
$.ajax({
type: 'POST',
url: 'http://192.168.1.103:8080/mazaya_cms/signup.htm',
//data: "{'name': 'nouman','email': 'noumandilawar#gmail.com','mobile_number': 03324412764,'employee_number': 4556, 'gender': 1,'password': '1234567891234567','language': 1}",
data: JSON.stringify(credentials),
//data: '{"id": "nouman","name":"nouman"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
crossDomain: true,
success: OnGetMemberSuccess,
error: OnGetMemberError
});
}
GetMember();
function OnGetMemberSuccess(data, status) {
alert(data+ " "+status);
}
function OnGetMemberError(request, status, error) {
alert(request+" "+error+ " "+status);
}
I am getting error code:415 that is unsupported media type Please help me!
I have successfully solved this issue
var credentials = {
"name": "nn",
"email": "nn%40gmail.com",
"mobile_number": 03324412764,
"employee_number": 4556,
"gender": 1,
"password": "1234567891234567",
"language": 1
};
$.ajax({
url: "http://192.168.1.103:8080/mazaya_cms/signup.htm",
type: "post",
data: credentials,
dataType : "json",
success: function(request, status, error){
alert("success "+request.status);
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure"+errorThrown);
}
});
I have the following json object:
cNGJSON = {
"one": graph1.graphNode, "two": graph2.graphNode, "three": graph3.graphNode, "four": graph4.graphNode, "five": graph5.graphNode,"six": graph6.graphNode,
"seven": graph7.graphNode,"eight": graph8.graphNode, "nine": graph9.graphNode,"ten": graph10.graphNode, "eleven": graph11.graphNode, "twelve": graph12.graphNode,
"thirteen": graph13.graphNode,"fourteen": graph14.graphNode,"fifteen": graph15.graphNode,"sixteen": graph16.graphNode, "seventeen": graph17.graphNode, "eighteen": graph18.graphNode,
"nineteen": graph19.graphNode
};
where graph1.graphNode is an integer array.
[1,2,3,4]
I send this to the server with jQuery:
$.ajax({
url: 'validate',
type: 'post',
dataType: 'json',
success: function (data) {
console.log("Success!!");
},
data: cNGJSON
});
However I get a
Expected BEGIN_OBJECT but was STRING at line 1 column 1
Error every time I try.
I tried with setting the cNGJSON to:
cNGJSON = {
"one": "Number one", "two": "Number two"
};
Still I get the same error.
As you want to send JSON object in your XHR request you need to stringify the JSON object first
$.ajax({
url: 'validate',
type: 'post',
dataType: 'json',
success: function (data) {
console.log("Success!!");
},
data: JSON.stringify(cNGJSON)
});