AJAX Getting Data, Post Back and Get Again - javascript

I'm trying to do the following thing with AJAX:
Visitor click button/ AJAX show spinning/loading image to visitor.
AJAX Visit URL 1 http://www.mywebsite.com/url1.php and it'll return a random code, for example 1357.
Then, I want it to visit URL 2 http://www.mywebsite.com/url2.php?code=1357&action=ask (1357 is a variable from url1). URL 2 will verify the request return a final code. I want to show the code to the visitor after removing the spinning/loading image.
How do I do that?
Thanks in advance.

Try this.
$.get("http://www.mywebsite.com/url1.php").done(function(data){
$.get(
"http://www.mywebsite.com/url2.php",
{code: data, action: "ask"}
).done(function(next){
$("#result").html(next);
});
});

Try this:
$.ajax({
url: 'http://www.mywebsite.com/url1.php',
dataType: 'html',
type: 'GET',
success: function (data) {
// Show the random code, like 1357
$(".result").html(data);
$.ajax({
url: 'page2.php?rand_n=' + data, // Change rand_n to what you want
dataType: 'html',
type: 'GET',
success: function (data2) {
// Hide the spinning/loading image
$("#loading_img").hide();
// Show final code
$(".result").html(data2);
}
});
}
});

Here is my idea for you:
Method one:
1.ajax request http://www.mywebsite.com/url1.php
2.in url1.php generate a random code like :1357
3.use [curl][1] request http://www.mywebsite.com/url2.php?code=1357&action=ask
4.echo result from curl2 to frontend
above only need one time ajax,the second request use curl quietly..
Method two:
you also could use header to redirect the url:
go on with step 2:
step 3:could use header('Location: http://www.mywebsite.com/url2.php?code=1357&action=ask');
step 4:url2.php should echo the result.
this tow method only have one ajax request and won't affect you frontend ,i recommand you use method two,method one is better used in different domain..

Related

How to asynchronize multiple Ajax Post call to the same URL

I've an array of items in javascript, and for each item, I've to make an ajax post to a URL to get corresponding info and display the info in a container. The code broadly looks like this:
var data = some_data;
array.forEach(item, idx)=> {
callAjaxAndUpdate(data, item, $('div#container'+i);
});
and the Ajax method is simply
var standardUrl = 'https://example.com/post.php';
function callAjaxAndUpdate(data, item, container) {
$.ajax({
url: standardUrl
data: data,
type: 'POST',
}).done(function(res) {
container.append(res.data);
}).fail(function(res) {
container.append(res.responseText);
}).always(function() {
container.append('DONE!');
});
}
However, this thing whole thing seems to have become blocking. I did server-side logging of timestamps, and I could see that ajax request for each item is getting triggered only after that for the previous one has completed (always section executed).
Could someone help me out with why this setup is synchronous, and how to make it async? Please note that this script is executing in the browser, and not on nodeJS.
EDIT: Turns out, it's the PHP backend which is processing the requests in a blocking way. Perhaps the session is the culprit here. I would close the question now. Thanks for your help and suggestions.
Try default Ajax async
var standardUrl = 'https://example.com/post.php';
function callAjaxAndUpdate(data, item, container) {
$.ajax({
url: standardUrl,
async: true,
data: data,
type: 'POST',
}).done(function(res) {
container.append(res.data);
}).fail(function(res) {
container.append(res.responseText);
}).always(function() {
container.append('DONE!');
});
}
Or you can call the method on .done method

jQuery Ajax call on HTTPS

I have a form that takes three steps to fill it.
At each of these steps you fill some info, click "Next" and then see either errors you have to fix in order to get to the next step or if there are no errors it takes you to the next step (change "display" to "block" in CSS).
At first step it uses $.ajax() to call file lib/ajax.php which returns some results in JSON that matter a lot to filling the rest of the form.
The thing is this works locally on my http://my.dev address, but live on https://something.example.com it does not.
Where should I first try looking to go about it? What are the most common workarounds on this?
Both lib/ajax.php and the index.php file (that has the jQuery call) are on the same domain (https://something.example.com) so we are not talking about cross-domain calls.
Here's some of the code.
$.ajax({
type: 'GET',
url: 'lib/ajax.php',
async: false,
data: {id: id},
dataType: 'json', // what type of data do we expect back from the server
}).done(function(data){
// do stuff with data
});
and the lib/ajax.php
//stuff with db and retrieving row by id
header('Content-type: application/json');
echo json_encode($result);
That's pretty much it. It doesn't work when I place it on live HTTPS server.
In https i think you must change the dataType: 'json' to dataType: 'jsonp'
1.Check the whether the url given in the function $.ajax() is the right path or not.
2.Here you specified data type as "JSON",so response must be "JSON".
3.If the response is not in correct JSON format,it makes issue.
contentType: "application/json; charset=utf-8"
Add the above code in $.ajax() function
Please check the above specified points

Redirect in the middle of an ajax request

I have a site where users can publish links. Users fill a form with 2 fields:
Title
URL
When the user clicks "submit" I have a crawler that looks for an image of the link provided and makes a thumbnail.
The problem is that the crawler usually takes about 5-10 seconds to finish loading and cropping the thumb.
I thought I could do an ajax call like this. As you can see, when the user submits a link first we see if its valid (first ajax call) then if succesful we do another ajax call to try to find and save the image of this link.
My idea was to do that while I move the user to the links.php page, however, I find that if I do it like this the AJAX call breaks and the function in save_image.php doesn't run.
What can I do to avoid making my users wait for the save_image.php process? I need this process to run, but I don't need any data returned.
$.ajax({
url: 'publish/submit_link.php',
type: 'POST',
dataType: 'JSON',
data: {
link : link,
title : title,
},
success: function (data) {
if (data)
{
$.ajax({
url: 'publish/save_image.php', type: 'POST',
data: {
id : data.id,
type : data.type,
url : url,
csrf_test_name : csrf
}
});
}
//THIS NEXT LINE BREAKS SECOND AJAX CALL
window.location = 'links.php';
}
});
Thanks in advance!
SUMMING UP: I want the user to submit a link and redirect the user to the links page while the thumbnail for that link is being generated. I don't want to show the thumbnail to the user.
The AJAX request seems to fail, because when you navigate away, the user request is aborted. Because of that, the execution of save_image.php is interrupted.
You can use PHP's ignore_user_abort to force the PHP process to continue in the background. Put it at the top of save_image.php:
<?php
ignore_user_abort(true);
// ... save image, etc.
?>
For this to work, you have to send (and flush) some output to the client:
PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush().
Any output should work (e.g. "OK"). This might be a bit of a challenge considering you're using a framework, but it shouldn't be impossible. This might work: Flushing with CodeIgniter
You can read more about PHP connection handling here.
force user to fill first the url and then the title, when user go to title field start crawl data, till finish the title and press sumbit you will gain some time and make the proccess apparently faster.
Why use XHR at all if you don't need the data returned? Just let your form submit the link to links.php and let it save the image there!
to understand your problem, we need to understand the working of javascript
your code is as follows
$.ajax({
url: 'publish/submit_link.php',
type: 'POST',
dataType: 'JSON',
data: {
link : link,
title : title,
},
success: function (data) {
if (data)
{
$.ajax({
url: 'publish/save_image.php', type: 'POST',
data: {
id : data.id,
type : data.type,
url : url,
csrf_test_name : csrf
}
});
}
//THIS NEXT LINE BREAKS SECOND AJAX CALL
window.location = 'links.php';
}
});
from the above i can say that as soon as ajax request is made, java script executes the second line regardless of the response.
we can take the following example
$.ajax({
url: 'publish/submit_link.php',
type: 'POST',
dataType: 'JSON',
data: {
link : link,
title : title,
},
success: function (data)
{
console.log(data);
}
});
for(var i = 0; i < 15000000; i++)
{
console.log(i);
}
you may see the output as follows
1
2
3
.
.
.
1000
data//response of ajax
.
.
14999999
so to avoid that you can use either jQuery.when() our ajax success function.
Hopefully this will help you

Trying to set variable as part of URL in jquery ajax post

So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID

Change window location Jquery

I am using ajax to load my website content and want to update the window location when ajax is successful.
How can I update the window location to "/newpage"?? I need users to be able to go back and to refresh. Is this possible??
I'm assuming you're using jquery to make the AJAX call so you can do this pretty easily by putting the redirect in the success like so:
$.ajax({
url: 'ajax_location.html',
success: function(data) {
//this is the redirect
document.location.href='/newpage/';
}
});
You can set the value of document.location.href for this purpose. It points to the current URL. jQuery is not required to do this.
you can use the new push/pop state functions in the history manipulation API.
Assuming you want to change the url to another within the same domain, you can use this:
history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');
If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin
Use document.location.href to change the page location, place it in the function on a successful ajax run.
I'm writing common function for change window
this code can be used parallel in all type of project
function changewindow(url,userdata){
$.ajax({
type: "POST",
url: url,
data: userdata,
dataType: "html",
success: function(html){
$("#bodycontent").html(html);
},
error: function(html){
alert(html);
}
});
}

Categories