Calling ajax request after processing another ajax request [duplicate] - javascript

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).

Related

is it normal, if I use php in javascript ajax for session inside condition? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have a code using javascript ajax like this :
$.ajax({
type: "POST",
url: "<?= site_url('test/test'); ?>",
dataType: "JSON",
data: {
id: id,
name: name,
},
success: function(data){
var data = {
"id": id,
"name": name,
}
<?php if ($this->session->userdata('class') == 'employee') { ?>
console.log('a');
<?php } else { ?>
console.log('b');
<?php } ?>
}
})
can I use session inside ajax code?
You should separate out the code:
PHP-side:
<?php
# what ever other code there is
echo $this->session->userdata('class');
JS-side:
$.ajax({
type: 'POST',
url: '/path/to/phpfile.php',
dataType: 'JSON',
data: {id: id, name: name},
success: function(response)
{
var data = {
'id': id,
'name': name,
}
if (response == 'employee') {
console.log('a')
} else {
console.log('b')
}
}
})
Now we only check the response value instead of mixing languages in a way that has no benefit. We set the response valueto the session value and perform a normal JS conditoinal to console.log()
You can only use a PHP variable (such as Session) as something you embed into the code as a hard-coded value e.g. if you write var x = '<?php echo $_SESSION["x"]; ?>'; then you create a JS variable x which has has the value of the Session value when the script starts. Assuming the Sesion value in that example was "hello" then in the final JavaScript which your browser receives and executes, you will see the following line: var x = "hello"; as a hard-coded snippet.
This is because PHP executes on the server, and generates the HTML and JS which is then sent to the browser after the PHP stops executing.
What you can't do is just write PHP inline in the JavaScript the way you've done in your example, and expect it to do anything. That PHP will execute before your JavaScript, and the result / output of the PHP (if anything) will be embedded in the JavaScript (or used to control exactly what JavaScript is generated and sent to the browser).
If you need to interact with the server during the execution of JavaScript code, but without posting back the whole page, then you need to make an AJAX request, so it generates a new HTTP request to the server, which can execute a PHP script and then return the response back to JavaScript to process.
In the specific example in your question, since you are already making an AJAX request, which can return data from PHP to JavaScript, I suggest you simply include the required Session value in the response data, and then write some JavaScript to read that value and decide what to do.
Further reading: What is the difference between client-side and server-side programming?

Get JSONP Response back to Original Function Call [duplicate]

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.

$.post javascript function in loop [duplicate]

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.

How can I get FileResult from ASP.Net by clicking a HTML button? [duplicate]

This question already has answers here:
Download Excel file via AJAX MVC
(15 answers)
Closed 6 years ago.
I want to get a FileResult by clicking the button. When I press the button the file is read well, but nothing happens. This is my code,
$(document).ready(function () {
$('#resource_btn').click(function () {
$.ajax({
url: "/Download/DownResource",
type: "POST",
cache: false,
success: function (data) {
// ?
},
error: function () {
alert("error");
}
});
});
});
[HttpPost]
public ActionResult DownResource() {
string fileName = Path.Combine(Server.MapPath("~/images/"), "down_arrow.png");
return File(fileName, "Iamge/png"); // Is that all?
}
The best way would be to send the request directly from form, not by JS.
You can make to form to post it directly, not by JA and ajax.
Or from JS you can change the accepted method to GET and send it via window.location.
However there are workarounds to force download from JS, but it is not well supported in older browsers. You can get more at: Create a file in memory for user to download, not through server

How to block thread on getJSON [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have two web services calls I need to make from my JQuery 1.9.1 app. I need the results from the first one before I make the second call.
It appears that my getJSON requests do not block the thread. I'm told that javascript is not multi-threaded, so how do I block between these server calls?
jQuery's ajax functions all return a jqXHR object that implement the Promise interface.
Instead of blocking an asynchronous request (and everything else), nest your requests like so
$.ajax({...})
.done(function( data ) {
// second request
$.ajax({...});
});
Well, you don't need to block threads, that's old school.
You have two options:
Make the ajax call syncronous.
Cascade the ajax calls, so the second is made only once the first one is completed.
I recommend the second approach, because that is the right way to do it.
/* Call 1 */
$.ajax({
url: 'first url to call',
data: 'first data sent to the server',
success: function (results1){
// Do something with the results
/* make the second call */
$.ajax({
url: 'sencond url to call'
data: 'second data sent to the server'
success: function(results2){
// Do something when all completed
}
});
}
});
Call your 1st ajax request in async false mode to server
$.ajax({
url: Url,
dataType: 'json',
async: false,
data: myData,
success: function(data) {
//stuff
}
});

Categories