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)
Related
I'm trying to implement a function that will do something based off of the response text given by a certain ajax call. But I can't access the response text field. Here is my code:
var response = $.getJSON('/add_participant',{
email : uemail,
password : upassword
})
and I've tried to access it this way:
response.responseText
But when I log it out to the console, it says it's undefined.
I think it has something to do with the ajax call needing to resolve first, before I access the response text. That's because if I save it to a global variable, when I pull up the webpage and use the inspection tools, I am able to access the responseText in that way.
How can I get that response text during my function? Is there a way I can have the script wait for it to resolve or whatever?
Thanks in advance!
Since this gets executed asynchronously, you need to handle it in .done callback. Here is the sample code.
var response = null; // assign to [] if you think you will receive an array
$.getJSON('/add_participant',{
email : uemail,
password : upassword
}).done(function (data) {
response = data;
console.log('response: ', data);
})
Hey I figured out what was wrong with my code, and it was actually a problem with the python code I was calling. I'm setting up my website with the Flask library in Python, and I was using the ajax call to use a python function in the back end and get the output it returned. The problem was that when I returned the output in the python function, I was returning a string, just like this:
return ("It worked!")
The rest of the function was still operating and doing the things I wanted it to do, and I could still check out the response when I used the inspection tools. But the returned value was in the incorrect format. It seems that this resulted in something along the lines of the Javascript code on the front end not getting the message from Python that the Python function had finished. And for that reason, nothing in the .done(function (data) { } ) block would get executed.
To fix this, I had to instead return a jsonified dictionary. jsonify is a function from the flask library. Here's how it should look:
return(jsonify({'result': 'It worked!'}))
And then if you want to access that data back in the javascript, access the result property of the data object inside the
.done(function (data) { } ) block. For me, it looked like this:
var response = $.getJSON('/add_participant',{
email : uemail,
password : upassword
}).done(function (data) {
if (data.result ='It Worked!'){
console.log("It worked!!");
// Do whatever else you wanted
}
else{
console.log("It didn't work.");
// Do something else
}
})
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;
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
So I'm learning Ajax and I followed this tutorial: https://phpacademy.org/course/submitting-a-form-with-ajax to create a function that works for any form. This is the complete function:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
alert(url + ' ' + response);
}
})
return false;
});
As you see all I'm doing is alerting the response, which in this case is php echo. That's where my problem starts, I need a flexible and secure way to handle the javascript/php communication. Preferrably one function for all forms, maybe with if () statements instead of alert(url + ' ' + response); depending on the form url.
The function I need is not very complicated, based on the response I get I will just update the current form with errors.
Aslong as I know what to use in the communication I'm fine from there, echo '1'; as I have now doesn't feel like the ideal solution but it's all I could handle.
So, what type of response should I send from the php page, and where (in the javascript) and how is the best way to handle it? I've heard of json but having a hard time wrapping my head around it. Could someone show a json response sending a basic integer thats easy for my response to pick up as an int?
You can send back a simple JSON response via PHP and check it in your success callback. Make sure you're setting the type to json and in your AJAX call, and using json_encode on the PHP side:
$response = array('response' => 1);
echo json_encode($response);
Output should be:
{ 'response' : 1 }
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().