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
}
})
Related
I'm trying to store data that I am retrieving from my JSON Ajax function. When I console output the data from inside the ajax function it works fine but when I try to do the same with the data variable it is failing.
Am I not storing the resulting data correctly?
function f_find() {
// create my data object from the results
var result = $.ajax({
url : '../scripts/php/users/f_users.php',
type : 'GET',
dataType : "json",
data : {'action':'find'},
success : function(data) {
// this bit works
console.log(data[0]["field01"]);
console.log(data[1]["field01"]);
},
error : function(log) {
console.log(log.message);
}
});
// this shows me that my result is an object
console.log(result);
// this bit fails
console.log(result[0]["field01"]);
console.log(result[1]["field01"]);
}
The php is as follows
<?php
if(isset($_GET['action'])) {
switch($_GET['action']) {
case 'find':
f_find();
break;
default:
echo json_encode();
return;
break;
}
}
function f_find() {
$la_info = array();
$la_info[0]["field01"] = "index 0 field 1";
$la_info[0]["field02"] = "index 0 field 2";
$la_info[1]["field01"] = "index 1 field 1";
$la_info[1]["field02"] = "index 1 field 1";
echo json_encode($la_info);
}
?>
The ajax call happens asynchronously. The "failing" is actually just running before the ajax responds. Look in your console and notice that your two failing console.logs write to to the console BEFORE the two "working" console.log statements.
Also... the "data" variable will only be accessible within the scope of that "success" callback unless you store its value in the global scope. window.data = data;
You have trouble with your scope.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
Try this :
function f_find() {
var ajaxResult = null;
// create my data object from the results
$.ajax({
url : '../scripts/php/users/f_users.php',
type : 'GET',
async: false,
dataType : "json",
data : {'action':'find'},
success : function(data) {
// this bit works
ajaxResult = data;
console.log(data[0]["field01"]);
console.log(data[1]["field01"]);
},
error : function(log) {
console.log(log.message);
}
});
console.log(ajaxResult[0]["field01"]);
console.log(ajaxResult[1]["field01"]);
}
When you receive data form ajax success they are now available in the ajaxResult var. In this example i said to ajax to be synchronous to prevent console.log call before you receive your ajax callback.
You can also do this with this notation :
function f_find() {
// create my data object from the results
$.ajax({
url : '../scripts/php/users/f_users.php',
type : 'GET',
dataType : "json",
data : {'action':'find'},
error : function(log) {
console.log(log.message);
}
}).done(function(data){
console.log(data[0]["field01"]);
console.log(data[1]["field01"]);
});
}
But you still can't access data outside of the done scope.
As #Dekel says, this is a timing issue (apart from the weirdness over the two data variables). Kevin Grosgojat's answer will still have the timing issue.
The $.ajax function is asynchronous. What that means is that the ajax function fires off the data request to the server and while that is being processed at the server, processing proceeds on to hit your two external console outputs however at this point in time the server has not responded and so there is no data to display. Some time later the server responds to the ajax call and your internal console logs spit out the answer that you anticipated.
'IF' your original code were to work for you now it would be because you have a very fast server or very small server process to get the data, but it would surely suffer and be an intermittent bug in production.
You 'could' add the parameter to the ajax function to make it run synchronously (meaning wait for server response) but that is rarely what you would truly want as the final solution.
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)
I have a backbone object that I'm calling save on. How do I know what comes back in the ajax call. Looking at the code for the project I got put on, I see some people just have a generic
success: function (data) {
console.log(data);
Then other times, I see:
success: function (library, response) {
console.log(library);
console.log(response)
I'm confused on how you would know you would have I presume a library or response object, vs a general data. When I look at the second example, I am looking at the output of
console.log(response);
and I see response has three attributes:
Notifications
Response
ResponseStatus
Response itself looks like Object {Id="12345", href="the/href", Name="asdf"}
So it looks like a Javascript object to me, but then when I try to do
console.log(response.Name);
I always get undefined even though I can see the value.
So I'm trying to understand how the callback in an ajax calls. Like when you can use an actual library object, response object, vs a data object, and how I can go about parsing the results properly. Thanks in advance!
You should either
$.ajax({
dataType : 'json',
..
})
or
$.ajax({
..
success : function(data) {
var result = JSON.parse(data);
});
Then I think you will be good
I want to use jQuery Validator to check against the server when a user is signing up for if their desired username is already taken. The PHP script untaken.php does this job, returning ok if the username is available, or taken if it is taken.
My entire source is below, however the line in question is this:
return data != "taken";
Currently the message "Username already taken" permanently appears. However if I change it to:
console.log( data != "taken" );
and type in the text box I see in the console true and false messages exactly when I expect them. That's how I know the design itself isn't to blame, it's just the fact that I can't return anything from the success clause in jQuery.ajax.
$.validator.addMethod("userCannotBeTaken", function(value, element){
var check;
check = $.ajax({
type: "GET",
url: "untaken.php",
data: ({ "user" : value }),
dataType: "text",
success: function(data){
return data != "taken"; //return false if taken or true if not, based on response
}
});
}, "Username already taken");
How can I return something from within jQuery.ajax?
Turns out I was overthinking the whole thing and it can be easily done with jQuery Validator's built-in remote method. Here's my code if it helps someone:
Rule in validator script:
remote: "untaken.php"
PHP:
<?php
//mysql info
[snip]
//connect to database
$sql = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
//Populate variable
$newun = $sql->real_escape_string( $_GET['newuser'] );
//Do the actual checks
$un_already_taken = $sql->query("
SELECT username FROM logins WHERE username = '$newun'
"); //check if UN already in DB
if($un_already_taken->num_rows > 0) //un taken already
print "false"; //tell jQuery to not submit form
else
print "true"; //tell jQuery all is good
As easy as printing "true" or "false". Note it uses GET (ie. URL paramaters) not POST, and the GET variable is the name of the field it is validating (in my case newuser)
To return data to the ajax function, you need to print or echo the result in your untaken.php page.
soemething like:
echo $result;exit;
Then Try to alert the data inside success function
and debug the result with
alert(data);return false;
The function you define for the success action is a callback.
When you make an ajax call, it is done asynchronously, (meaning the script continues executing while the browser connects to the server. You can't use return when dealing with callbacks because they are executed later, rather than immediately as a typical function.
This might make more sense: http://recurial.com/programming/understanding-callback-functions-in-javascript/
The success function should perform whatever actions that you want to happen after you get the data back to the server ie: alert the user that the username is taken.
I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).