JSON request inside another JSON? - javascript

I am trying to make a JSON request using jquery, the first JSON request return me the data I want.
After the first Success JSON request, I want to look at the results from the first JSON request and use it in my second JSON request.
The problem I am facing currently, is my second JSON request return empty object.
Can someone help me figure out why my second JSON return nothing?
Even though when i post the second JSON url on a website url, it show me the JSON data. but in my program it is not returning anything.
Here is the code
$(document).ready(function() {
var api_wiki = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=cat&srwhat=text&callback=?";
var api_wiki_extract = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=info%7Cextracts&inprop=url&exsentences=1&callback=?&titles=";
var sp;
var linkReady = [];
var linkR;
$.getJSON(api_wiki, function(data) {
sp = data.query.search;
linkR = workWithTheData(sp);
anotherJSON(linkR);
}); //End of getJSON 1
function workWithTheData(sp) {
for (var i = 0; i < sp.length; i++) {
linkReady[i] = api_wiki_extract + sp[i].title;
}
return linkReady;
}
function anotherJSON(linkR){
$.getJSON(linkR[0], function(data1) {
console.log(data1);
});
}
}); //End of document ready

A few things you need to understand here:
JSON is a data format. What you are doing is HTTP Ajax Request, provided by jQuery, which return data in JSON format.
Your code is totally working fine. you can see #Hanlet 's link.
After your second Request, it will return {batchcomplete: "", query: Object} in Browser's Console. And once you expand the query, you will see everything inside.
The 2nd scenario that you might facing, is, may be there are some other parts affect your ajax request.
You can try to to convert back to normal $.ajax request and set async: false
Is it possible to set async:false to $.getJSON call

Related

Google spreadsheet showing undefined values when submitting through an AJAX request

I'm trying to send the data I gathered from my web app to a google spreadsheet.
I'm using the script from Martin Hawksey:
https://gist.github.com/mhawksey/1276293
I've set it up and did everything as shown in the manual. And I am getting data back, but it's showing up as undefined values:
This is the code I use to send the JSON string to my spreadsheet:
function sendData(){
var url = 'https://script.google.com/macros/s/AKfycby3SUJvfEjdHWVoEON0L5hN4uXod8M4Jv1LAIWH3Ny16MIUz9o/exec';
var data = JSON.stringify(member);
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: function (response) {
console.log("succes! I sent this: " + data);
console.log("got this back: " + JSON.stringify(response));
},
});
}
This gives me a success message, it even tells me which row it was placed on.
This is the JSON string I'm sending:
{"Voornaam":"Name","Achternaam":"Name","Mail":"x#x.com","Verjaardag":"0/0/0000","Foto":"https://graph.facebook.com/xxxxx/picture?width=1020","School":"School X","Richting":"Course X"}
I even checked this JSON with a JSON parser online and it didn't return any errors.
For starters, I'm not entirely sure how to check which string I'm receiving at my spreadsheet. If it's still correct when it arrives. I tried logging it, but can't seem to get any response from the google logger.
If anyone could point out what I'm doing wrong, you would be greatly appreciated!
The Web script expects a JSON object. However, Ajax call is made with a string using the stringify function
var data = JSON.stringify(member);
Modifying the script to make the GET call with JSON object as is resolved the issue, like so
var data = member;

Echoing two arrays to Angular?

I'm having some trouble with returning two arrays from an ajax request from and to angular via PHP, either works fine but not returning both which seems strange. Tried putting the two arrays in one array but that results in either empty responses or just responses of "Array".
This is from my PHP code:
$outp["arrayinarray"] = "$array";
$outp["arrayinarray2"] = "$result";
print_r(json_encode($outp));
And my JS:
$scope.go = function(EmailAccountId) {
$scope.id = EmailAccountId;
$http({
method : 'POST',
url : 'search_hand.php',
data : $scope.id,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function (response) {
$scope.formData = {};
$scope.formData.selectedServices = {};
console.log("response data " + response.data);
$scope.searchForm = true;
$state.go(nextState($state.current.name));
}, function(error) {
console.log("ERROR!");
console.log(error);
}
);
};
The background to this is a simple search and edit application. Upon registration a file can be selected from the server which is done with a simple glob-function for selecting the file. Since it's a multi-step form the PHP for building this select seems to happen after angular has initialized and as a result that is always set to "default".
So I'm trying to rewrite the code and make Angular do the repeating of these files based on the response from glob but since a database select is also in this search function it just seems to die.
Why can't I return two arrays without breaking the code?
My console simply says "object Object" if two are returned but will display each object correctly if just one of those are echoed/printed back.
Object Object is usually shown when a object.toString() is executed. So in your case you are getting the json object with two arrays and you are trying to access it in a wrong way.So try printing to console like response.data.arrayinarray .
You need to parse json after getting the response. Suppose you encoded like :
$outp["data"] = $array;
$outp["status"] = 1;
print_r(json_encode($outp));
than you need to decode and access like this:
.then(function (response) {
console.log("response data " + response.data);
var obj = jQuery.parseJSON(response);
console.log(obj.status)
console.log(obj.data)

How can I store js output in php?

I want to store my javascript output in PHP. I mean, my js code is:
function loadCurrentUser () {
var url = APIPATH + 'load_current_user.php' ;
var result = $.ajax({
type : "GET" ,
url : url,
async : false
}). responseText ;
var resultJSON = processJSONResult(result);
}
What I want is to store the output I received (in json format) to my variable $json (in php). How can I do that?
based on the comments above it cannot be done as you think. But if you insist on getting response date to a php variable you will have to make another ajax call as ajax call occur at client side and php runs in your server not on the browser #briosheje had explained it nicely. may be what you need is session variable ($_SESSION['index']) to store your response data

How to get a value from Json result

This is the json result I get from my controller
{"data":"Sunday"}
The data can say any day of the week (Sunday, Monday, etc...)
On success I want to do this in ajax call
success: function(Response){
var myresponse = Response.data;
alert(myresponse);
}
However, it gives me undefined.
If you are sure that you are getting a JSON response from the server, you can make use of the Ext.JSON class to decode the JSON.
You can use the decode() method to convert a string to an object. Then you should be able to easily access it.
Example:
var jsonObject = Ext.JSON.decode(Response.responseText);
var myData = jsonObjet.data;
If you are using jQuery to load this string you could just use $.getJSON which will automatically parse the string and pass the object as the return value to the 'success' function.
try to use a
console.log(Response);
to check the content of Response
It might be considering your response to be a string. I would do something like this:
success: function(Response){
alert(typeof Response);
var myresponse = Response.data;
alert(myresponse);
}
If it tells you that Response is string, you need to make sure that your framework knows you are getting back JSON. For instance with jquery it might be $.getJSON().

jquery function with variable problem

I'm trying to return a list of select options to a JqGrid Add feature.
I have a javascript/jquery function that does a GET to get a string preformatted to work with JqGrid. I'm having trouble returning the results to the JqGrid though. How do I return the data from the jQuery Get function?
function getDealerPoolSelectOptions() {
var selectOptions = "1:A;";
$.get("DealerManagement/GetAllDealerPoolCodes", function(data) {
alert("Data: " + data.toString()); //Displays all the data I'm looking for
selectOptions = data;
});
alert("SelectOptions: " + selectOptions); //Just Displays the 1:A
return selectOptions;
}
$.get begins an asynchronous AJAX request and calls your callback function(data) ... once it is done. $.get itself returns before the request is complete. The alert("SelectOptions ...") part runs immediately (before the data is retrieved) so selectOptions isn't set yet.
jQuery ajax, by default, makes an asynchronous request (meaning it will make the request in the background, without blocking execution in the rest of the function).
EDIT: While you can make synchronous requests, I should note that this is very discouraged. Instead, you should design your code in a way that takes advantage of event driven programming.
You can make a synchronous request like this:
function getDealerPoolSelectOptions() {
var selectOptions = "1:A;";
$.ajax({
async: false,
url: "DealerManagement/GetAllDealerPoolCodes",
success: function(data) {
alert("Data: " + data.toString()); //Displays all the data I'm looking for
selectOptions = data;
}
});
alert("SelectOptions: " + selectOptions);
return selectOptions;
}
Probably you should describe your original problem. What you want to do with jqGrid?
Do you want to fill select of edit or search field with the data from the server? You should use dataUrl of the editoptions or the searchoptions. The feature (dataUrl) are introduced exactly for loading the data per ajax.
If the data which you can provide from the server can be only JSON and not in the format which are waiting by jqGrid you can use buildSelect additionally to reformat the data returned from the server. For more information see my old answer.
The alert gets called before the selectOptions = data; because ajax functions are called asynchronously. If you want something to happen, like adding the data to a grid, call it in the get callback after you set the selectOptions data.

Categories