This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
In basic terms I am trying to make a cross domain AJAX call using JSONP. The JS and PHP files need to be on a different domain. I can't seem to get the returned data back to the original function.
To explain how the page works. A user will enter something into an input box. e.g. Surname.
Input and search.
After the user clicks search a the searchClick() function is called. This function takes the text the user has inserted into the input box and calls another function called getInfo().
function searchClick() {
var jsonOfData = getInfo($('#searchInput').val());
console.log(jsonOfData );
}
The getInfo() function has to be in a JS file on a different domain.
function getInfo(surname) {
$.ajax({
url: "https://www.otherdomain.com/api/lookup.php",
dataType: 'jsonp',
crossDomain: true,
data: {
surname: surname
},
success: (data) => {
console.log(data); // This works
return data; // This doesn't
}
});
}
This ajax call goes off to my PHP page and does a search on the database. It then created a JSON array and sends it back. From my research instead of ending the file with the usual echo json_encode($array); I ended the file with:
echo $_GET['callback'] . "(" . json_encode($responseArr) . ")";
This is the point at which I have my problem. As you can see, in the AJAX success function, the data is successfully displayed and logged to the console but I can't return it back to the original jsonOfData variable.
I hope this makes sense and i'll be so thankful to anyone who can help me out.
What you're trying to do won't work, because the $.ajax calls works asynchronously.
Instead of work with the return of the function call at this point:
var jsonOfData = getInfo($('#searchInput').val());
Try to build your logic inside the success function of your $.ajax call.
Related
This question already has answers here:
How to manage a redirect request after a jQuery Ajax call
(34 answers)
replace div content using ajax and jquery
(4 answers)
Replace HTML page with contents retrieved via AJAX
(7 answers)
Closed 5 years ago.
User pushes the button on site and by this ajax request starts than Server returns True or False. If the result is True than another ajax request is to be processed, but I am getting nothing (I guess inside of ajax).
Here is my js code:
document.getElementById('next_in').onclick = function (){
$.ajax({
data: {
login: document.getElementById('log').value,
password: document.getElementById('pass').value
},
type: 'POST',
url: '/user_login',
success: function (localRes) {
if(localRes.result==true){
$.ajax({
data: {
login: document.getElementById('log').value
},
type: 'POST',
url: '/private',
success: function () {
alert('Connected')
},
error: function () {
alert('There is a mistake!')
}
});
}
else{
alert('Incorrect login or password!');
}
}
});
}
and python code:
#app.route('/private', methods=['POST'])
def private():
return render_template("rates.html")
Then after pushing the button on site I recieved "Connected", but then (I supposed this event calls my python function) there is no redirect to rates.html...
I do not understand what is wrong here..
Please. I hope at leaste to understand problem of which side it is and how to fix it?
Thank you!
EDIT ONE
I did shorten my python function just to show the issue. In actual case before return render_template("rates.html") there is huge proccessing (request to database, some calculation and so on), so python function is:
#app.route('/private', methods=['POST'])
def private():
# ******************** HUGE processing
return render_template("rates.html")
Sorry, if I confused you, but simple redirect to .html is not what I want. I want calling python function in nested ajax requests.
When you use an AJAX request, the browser doesn't automatically redirect you, or display any content that is returned from your request.
If rates.html is a full HTML page, change your inner callback from
success: function () {
alert('Connected')
},
to this:
success: function(data) {
document.body.innerHTML = data;
},
That takes the response from the server (your python code), and then does something with it (in this case renders it on the browser).
This question already has answers here:
Jquery call another function after ajax in loop is done
(1 answer)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am writing a code in which user checks multiple check boxes and those users assign to the selected division. I am using $.post function in a loop of check boxes. Everything is working fine and checked users are being assigned to the selected division. Now, the issue is that I want to print a response after $.post function but everything I write after this post function, javascript executes it before that function and that's why, I am unable to print the response. Please check the below code for your convenience and suggest a possible solution.
Thanks a lot
function assign_user(div_id){
//alert(div_id);
var favorite = [];
$.each($("input[name='user']:checked"), function(){
value = $(this).val();
$.post("../db/assign_user.php",{div_id:div_id,value:value},
function(x){
});
// I want to print final response here but it executes before post function
});
}
Ajax requests are asynchronous. They are sent to the server, then the javascript continues on without waiting for a response. If you type your Ajax request like:
$.ajax({
url: "../db/assign_user.php",
type: 'POST',
data: {div_id:div_id,value:value},
success: function(data){
alert(data);
}
});
then in the success function, you can handle or alert the response.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Im having issues getting my data passed back to an external variable. I know the ajax request works but its not passing it in the manner that i need.
here is a exact method in my class
function(amount,symbol=''){
var current_rate = '';
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'https%3A%2F%2Fwww.google.com%2Ffinance%2Fconverter%3Fa%3D"+ amount +"%26from%3DNGN%26to%3D"+ symbol +"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var get_rate = $.ajax({
url: url,
method: "GET"
}).complete(function(data){
current_rate = data.responseJSON.query.results.div.span.content;
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
return current_rate;
}
Ive edited the code for simplicity. but heres the full script . I just need to know how to pass the data from the request back into the 'Current_rate' variable
Your function returns current_rate = '' because that's the value of current_rate when the function ends. It ends before the asynchronous call completes!
This part:
$.ajax({
url: url,
method: "GET"
}).complete(function(data){
current_rate = data.responseJSON.query.results.div.span.content;
})
Will set current_rate when the AJAX call returns, which will be long after your function returns. You have to think of $.ajax() as scheduling the request (and the code that runs when the request is complete). It doesn't block or wait for that to happen - your function just continues on.
The best solution here is to return the promise that $.ajax() returns, so your calling function can wait on it:
function(amount,symbol=''){
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'https%3A%2F%2Fwww.google.com%2Ffinance%2Fconverter%3Fa%3D"+ amount +"%26from%3DNGN%26to%3D"+ symbol +"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
return $.ajax({
url: url,
method: "GET"
});
}
In order to use this, call the function like this:
get_current_rate(1000,'CAD').complete(function(data) {
// do something with the returned data
});
See the documentation for the jQuery Deferred object. See also this post, which contains an excellent (long!) explanation of the problem and various solutions: How do I return the response from an asynchronous call?
so I'm doing a basic assignment for uni, they asked us to use ajax and php to create a text input that validates the name and email plus a live search bar, all this without using db. So I have the html already set up, the .php with 3 different arrays with names, emails and news stored in and a main.js that already displays whatever you type in the text input in the console with the keyup event trigger. I just can't figure out a way to make an ajax request to compare what you type in to the info stored in the arrays.
In the arrays.php I have this :
*$classes = array('1' => 101, '2'=> 102, '3'=>103 );*
*$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');*
*$news = array('Title'=>array('El papa muere', 'Argentina gana el mundial', 'Fondos buitres cancelados' )'Noticia'=>array('noticia1', 'noticia2', 'noticia3')
);*
and in the main.js I have something like this:
$('#name').keyup(function(){
var name=$(this).val();
console.log(name);
that retrieves what I type in each text field. As far as I can remember, the prof wrote something like this to give us a hint:
$.ajax({
url: ' ',
type: ' ',
success:function(data){
}
}):
But I just can't figure it out so any help would be much appretiated!
The general idea is to pass the current value of the search box to your PHP script via ajax. Then in your PHP script, you would filter your options based on the current value passed to it and return a filtered response. The javascript would then take the filtered response and output it on the page.
People usually use JSON as a format for passing information between Javascript and PHP.
To give you a little better understanding what $.ajax does. It will make a request to your server and then process the results. The parameters specified do the following:
url: The URL to request
type: The format of the response (eg. text, xml, json, etc.)
success: A callback to be called when the response comes back from the response.
Also note that the A in AJAX stands for asynchronous. This is why you need to give the $.ajax function a callback. Due to the nature of HTTP, you make a request and the response can return right away or in 30 seconds or never. When the response returns the callback will execute. It is not linear. Therefore the callback can execute after code below the the $.ajax call depending on how long it takes for the response to come back.
Maybe take a look at the example below to give you a better idea of how to do this:
<?php
$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');
$result = array();
foreach($names as $name)
{
if (strpos($name, $_GET['name']) !== false)
{
$result[] = $name;
}
}
echo json_encode($result);
?>
And the javascript
$('#name').keyup(function() {
var name=$(this).val();
$.ajax({
url: '?name=' + name,
type: 'json',
success: function(data) {
console.log(data);
// add data to results
}
}):
});
Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.