Lengthy jQuery AJAX request freezes browser - php

I have an AJAX request, processing of AJAX request is complex and lengthy. The problem is that this lengthy request freezes browser. I mean when AJAX request is in process then no matter if I click any link/button from page or type some Url of same website in browser address bar it does nothing and keep waiting fro AJAX request response, once AJAX response arrives back other processes start working. I am using async: true with AJAX request.
Here is the code I am using. Its a simple page having nothing else but this jQuery AJAX request. My server side PHP.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Page</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'http://www.mywebsite.com/doprocessing',
async: true,
success: function () {
alert('done');
}
});
});
</script>
</body>
Why this is happening? How can I solve this?
PS: Before you mark this duplicate, I have checked almost all similar questions on StackOverflow. No solution is working in my case (though solution in most cases was using async: true which I am already doing.
Thanks in advance,

The reason, why any of the links of the same website are not working during ajax, is that your script is locking the session in the server.
You could either not to use session for this script, or finish session after you are sure that this is correct user etc, but before starting sending emails (or doing anything else lengthy).
Use session_write_close() before starting sending emails in PHP for this.
Alternatively you can implement your own asynchronous session handler.

Related

Debug AJAX Form

I have a .php file with HTML code and inside it I call another php with html file with AJAX. A form.
Apparently something with this form is wrong, or the query after it. Problem is:
When I submit it, the page reloads, and I cannot debug my form.
When I use preventDefault on my code, and prevent the form from
submitting I cannot debug because the query is not executed yet.
Cannot write an html message displaying the variable because after
reload php with the form is gone.
How can I debug my code in this situation?
File1.php
$(".edit-post").click(function(){
var postid = $(this).attr("id");
$.ajax({
type: "GET",
url: "/admin/EditProductForm.php/",
dataType: "html",
data: {
ajaxpostid: postid
},
success: function(data){
$('#post').html(data);
}
});
$("#post").show();
});
EditProductForm.php
<?php
$ID = $_GET["ajaxpostid"];
$post = GetProduct($ID);
if(!empty($_POST)){
...query
}
?>
<html>
<form>
.
.
.
</form>
</html>
The first thing to understand is that although your HTML and Javascript might have been delivered to the workstation by PHP, it is now running in a totally separate environment with no access to PHP at all.
The PHP you're running on your server is running in the server environment, and has no access to the HTML and JavaScript running in the browser.
The two parts of your application communicate either by sending data as part of a GET or POST request when the form is submitted, or by sending and receiving messages through AJAX. It would be unusual to use both methods in one page.
Thus, you can debug the two parts separately.
Turning to your code:
Your AJAX code is triggered when your button is clicked. In the absence of any other attributes, the button will also trigger a submit. This is what is causing the page to reload. Since you're using AJAX to update your page you don't want it to reload, so stop it with preventDefault();
$(".edit-post").click(function(event){ // add the event parameter here
event.preventDefault(); // Prevent the default action - the submit.
var postid = $(this).attr("id");
...
With this done you can use the browsers tools Network tab to watch the messages, see what's being sent, and look at what response is received.
The server end of things is a little more awkward, but adding echo statements at appropriate places can provide useful output while debugging. Note that you don't need your AJAX script to debug the server end - a simple HTML form with the right fields will do. If you're using GET you could even type the URL and query string on the command line by hand and watch the results.
In your code there is a basic flaw, however.
In your AJAX code you're setting the request type to GET (type: "GET",). In your PHP script you're looking for $_GET["ajaxpostid"];, which is OK, but then you start looking at the $_POST array, which will be empty because your AJAX call used GET.
Now at this point, there's not enough code to be clear about what you're trying to achieve. If your SQL query is just retrieving data to populate an edit form then GET is an appropriate method, and you shouldn't be looking at the $_POST` array.
However, the code you've posted suggests that the EditProductForm.php code is generating the HTML to perform the edit. If this is the case you don't need AJAX at all, and you can just submit the form from File1.php. On the other hand, if you want the page to transform to an editing form without a refresh then File1.php needs to create the editing form and incorporate the data sent by the server, and your EditProductForm.php should not do that job.
a button on form can have three types button|submit|reset , the default type is submit.
on your case, you are clicking on button which has the default type of submit, so its submitting form. that's why the page refreshes. but you want to apply Javascript instead.
so in these cases, either you apply event.preventDefault(); with the javascript code to stop form submission, or simply add type="button" to your button to explicitly say this button is going to run javascript
type=submit -> it means button is going to submit form date
type=reset -> it means button is going to clear form data
type=button -> it means button is going to apply javascript
<button type="button">Submit</button>
file 1(jquery):
$(".edit-post").click(function(){
var postid = $(this).attr("id");
$.ajax({
type: "GET",
url: "./EditProductForm.php",
dataType: "html",
data: {
ajaxpostid: postid
},
success: function(data){
$('#post').html(data);
}
});
$("#post").show();
});
file 2:
<?php
if($_GET["ajaxpostid"] == "test"){
?>
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type='text/css' href="../Requirement/css/bootstrap.min.css">
<link rel="stylesheet" type='text/css' href="./index.css">
<title>test</title>
</head>
<body>
<h1>hello world !</h1>
<script src="../Requirement/js/jquery-3.5.1.min.js"></script>
<script src="../Requirement/js/bootstrap.min.js"></script>
<script src="../Requirement/hls.js/dist/hls.min.js"></script>
</body>
</html>
<?php } ?>

POST variable from jquery redirecting but is not set

I asked a question recently about sending a POST variable off of jquery to another php page, redirecting to that page, doing some action with the sent information, and redirecting off of the original page.
jQuery post method and directory confusion
I am asking for help on almost the exact same code, since the person who commented on it only answered half of my question and marked it as a duplicate. While it did help, it did not solve the problem.
I have made edits according what was suggested in the previous attempt to get this problem solved. As you will see, hitting the save button in this example will bring you to changePage.inc.php, the first redirect, but the second redirect does not happen, which should bring you to secondPage.php.
File named index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message});
window.location.href = "includes/changePage.inc.php";
}
};
changeText();
send();
});
});
</script>
<body>
<textArea id="text"></textArea>
<form id="saveForm" action="includes/saveEssay.inc.php" method="POST">
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
File named changePage.inc.php (within a folder named includes)
<?php
session_start();
if(isset($_POST['message'])){
header("Location: ../secondPage.php");
}
exit();
File named secondPage.php
<?php
echo 'Hello World';
?>
The jQuery $.post() method is what is referred to as an asynchronous call. What this means is that while $.post() is trying to execute, any line of code after it will try to execute.
Note that you're redirecting immediately after your $.post(). This means that while $.post() is trying to run, you're redirecting to includes/changePage.inc.php, which is probably preventing the PHP redirect to ../secondPage.php from running. This is what we call a race condition, where two events are running simultaneously and either one could finish before the other with no way to keep the events synchronized.
What you're really trying to do, from what I can tell, is hand off processing of your data to PHP, then upon finishing, you want to redirect to a given page.
If I'm correct about this, then remove the window.location.href = "includes/changePage.inc.php"; line because otherwise you're always going to run into issues with this race condition. Handle the redirect in PHP--it should work on its own. If you're having trouble with redirecting directly in PHP, then you can redirect through jQuery:
Your jQuery POST
$.post("includes/changePage.inc.php", {message: message}, function(data) {
var obj = $.parseJSON(data);
window.location.href = obj.redirect_url;
});
What to return via PHP
echo json_encode(array('redirect_url'=>'includes/secondPage.php'));
If this doesn't meet your needs, then you'll need to really sit down and better explain your use case and your intent. If you can't explain it well enough to communicate exactly what you want, then you probably don't have a complete grasp of the problem you need to solve.

How do I use Ajax to auto refresh a div across domains?

Can someone help me out? I have an html file that calls a php script via ajax and displays a random number that the php script generates. It works just fine when both files are on the same domain, but if the 2 files are located at different domains, which is what I need, nothing happens. Can someone help me fix this.
The code for the HTML file is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
}, 5000); // the "5000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
</head>
<body>
<div id="divToRefresh">Loading users...</div>
</body>
</html>
If the line
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
is changed to:
$('#divToRefresh').load('random.php');
and placed in the same folder as the html file all is well.
The code for the php file is:
<?php
$random1 = sprintf("%02f", rand(0,9212));
echo $random1;
?>
What would the revised code that would allow cross domain ajax calls look like? I was reading documentation that talked about a json request wrapper, but I did not get where it was going. Any help would be hugely appreciated.
you are not able to use ajax cross domain its not possible, you have the following options though:
1.do the ajax to your own page and make a curl call to that page..
2.do $.getJSON('ur', variables, function(data){}).
there are few other solution, but those 2 are basically your best options
here is how getJson works:
On your server you should have a page that is ready to receive the $_GET sort of like an API or normal ajax call would do with $_POST.
should look something like :
<?php
if(!empty($_GET['jsoncallback']) && !empty($_GET['variable'])){
/* do whatever you like with the variable you get as get
*
*
*
**/
// echo the name of the callback function + the variables you want to receive back in JS
echo $_GET['jsoncallback'].'('.json_encode($jason_echo).')';
}
?>
Your JS or page you are going to do the call from should look something like:
$.getJSON("SomePage/PagethatTakesTheGet.php?jsoncallback=?", {variable:15}, function(response){
// do whatever you want with response.
});

ajax call is not responding

I am using ajax for retrieving data from my remote server when i am posting the ajax url directly in the address bar of browser, i am getting the data but when i am doing ajax call to that url in javascript file , it is showing error.I am pasting my code here.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$.ajax({
url:"http://www.appitechture.com/api/index.php?action=getContactDetails&id=96",
type:'get',
datatype:'json',
success:function OnSuccess(data , status){
alert(data);
} ,
error: function OnError(request , status , error){
alert('error');
}
});
</script>
</head>
<body>
<div id="images"></div>
</body>
</html>
so please if any one knows its solution please tell me.
Thank's
puneet
Are you trying to do a crossdomain AJAX request? Bad idea, read this article http://en.wikipedia.org/wiki/Same_origin_policy
If it is not the same domain, you need to use JSONP (JSON with padding). This is due to Same Orgin Policy, as Bogdan Burim states.
jQuery.getJSON can help you with this in a easy way. It will include a script tag like this on your page.
<script type="text/javascript"
src="http://example.com/jsonp?callback=parseResponse">
</script>
You will also need to change the response of the remote server to include the callback var like this:
parseResponse({"bar": "foo", "foo2": "bar2"});
You can also have a look at easyXDM:
easyXDM is a Javascript library that enables you as a developer to
easily work around the limitation set in place by the Same Origin
Policy, in turn making it easy to communicate and expose javascript
API’s across domain boundaries.
Wikipedia have a nice article about JSONP.

Facebook auto-refresh

What technology does Facebook use to auto-update information on a page without reloading it?
For example, while someone is viewing his profile if he receives a new message the inbox number auto-updates in the top bar. Same with wall posts, etc. Code-wise how is this managed?
They are using several new technologies like AJAX and History API.
I strongly recommend you to use jQuery or another framework for AJAX and History.js for the History API.
the core javascript function set_timeout() is the man! Every x seconds the server is queried to fetch new results, updates etc. FB uses AJAX to get the info from the server and JS to update the page.
Facebook open a connection using AJAX which then hangs and hangs. The server doesn't send anything or respond to your browser unless, of course, a notification. Eventually, your browser may give up and disconnect from Facebook in which case the javascript will create a new connection and the process continues.
This is superior to polling the server every few seconds as it reduces load and makes load more predictable too.
Here's more info: http://en.wikipedia.org/wiki/Comet_%28programming%29
use setInterval on a function which makes an Ajax call to a file in which you have a MySQL query which checks something.
setInterval( "refresh();", 60000 );
refresh = function(){
var URL = "file.php";
$.ajax({ type: "GET",
url: URL,
succes: function(data){
if(data){
//change stuff
}
}
});
}
that should be a good starting point
coba gunakan script ini..
autocallajax.php
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'load.php',
success:function(data){
$("#sample").html(data);
}
});
}
setInterval(callAjax,5000);
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
<div id='sample'>100 </div>";
?>
</body>
</html
load.php
<?php
mysql_connect("localhost","root","siantarman");
mysql_select_db("konsultasi") or die("<br><br><hr width=350 size=1 align=left>
<font color=red><b>Database belum tersambung!</font></b>
<br>Hubungi administrator anda!<br>" . mysql_error());
$sql_info=mysql_query("select jumlah from data_konsultasi where id = '9'");
$r_data=mysql_fetch_array($sql_info);
echo"$r_data[jumlah]";
?>
selamat mencoba..

Categories