This question already has answers here:
How do I close a connection early?
(20 answers)
Closed 8 years ago.
okay so,
[browser] ==> makes AJAX call to webserver running php
i have the following php code,
<?php
//Process Ajax request
//return success code to browser
//continue with other php code
?>
How exactly can i achieve the second part i.e "return success code to browser"? and continue with processing php code.
put **async:false** in ajax call so your code will execute synchronously means until you don't get success or failure from ajax return rest of code will not execute .. do like following
// add here jquery file
<script>
$.ajax({
url : "abc.com/page",
type: "POST",
data: {},
async:false
success : function(data)
{
//you can use data here
}
});
</script>
//you can write here php code
i think it can be done like follow
//initial php code
call_function();
echo json_encode(array('success'=>true));
//other php code
call_function(); //etc
or you can split the ajax call in 2 parts.. in 1st part it will get the status so echo json_encode() will be executed and call ends and in success call back of ajax make 2nd call which will execute the remaining code!
Related
Is it possible to use Ajax, Jquery or Javascript to call a specific PHP Function and refresh / reload it every 10 seconds for example inside a specific Div or areas?
Connection.php
function TerminalStatus ($IPAddress, $portStatus ) // Responsible for current terminal status
{
$connectStatus = fsockopen($IPAddress, $portStatus, $errno, $errstr, 10); // Build cconnection to Terminal socket 25001
if (!$connectStatus) {
echo "$errstr ($errno)<br />\n";
} else {
$Status = fgets($connectStatus) ;
echo $Status ();
}
}
This connection is just to see the current status of a terminal.
I want to see the status of this function at the bottom of my index.php without refreshing the whole page.
I can accomplish this by putting this function in its own PHP Files (status.php) and using Javascript in the following way:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#Status').load('status.php');
}, 1000); // refresh every 1000 milliseconds
</script>
But i just want to utilise the function instead.
Is this possible?
The solution you have already is the correct way to do this: the JavaScript fetches a URL, and that URL renders the appropriate piece of content.
It's important to remember that, as far as the web browser is concerned, PHP doesn't exist. Any request from the browser - whether you've typed in a URL, followed a link, submitted a form, made an AJAX request, etc - is just a message to some remote server for a particular URL, perhaps along with some extra headers and body data. When the server receives that request, it can do whatever it likes to generate a response to the browser.
So when you write $('#Status').load('status.php');, the browser is sending a request to the server, which happens to be configured to execute the PHP script status.php. You can then do what you like in PHP to produce the response - but there is no direct link between a request and a PHP function.
However, as others have pointed out, you don't have to create a new PHP file for every piece of behaviour you want, because inside the PHP code you can check things like:
the query string parameters, in $_GET
submitted form data, in $_POST
the HTTP headers from the request
These can be set by your JavaScript code to whatever you like, so you could for instance write $('#Status').load('index.php?view=statusonly'); and then at the top of index.php have code like this:
if ( $_GET['view'] === 'statusonly'] ) {
echo get_status();
exit;
}
How you arrange this is entirely up to you, and that's what programming is all about 🙂
That's impossible to do this operation just with the PHP function.
you should use javascript as you use that or use socket in javascript to connect you status.php and update without refresh the whole page.
I'm not sure if i understood the problem but you can use AJAX to execute specific function. Something like this:
First build your ajax:
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus", // this will call the function
success: function(status){
$('#Status').text(status); // this will load the info you echo
},
});
Since you want to do it every second - wrap the whole thing with interval (i use your code from the question):
var auto_refresh = setInterval( function () {
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus",
success: function(status){
$('#Status').text(status);
},
});
}, 1000);
Then, on you PHP_FILE add condition the execute the specific function when POST been done:
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST['refreshStatus']) {
// run this code
}
Is that what you aimed to achieve?
jQuery::load() supports fragment identifiers. So you can just load the part that you want to replace:
$( "#Status" ).load( "status.php #PartId" );
This will load the HTML output of the script and extract the part. The PHP script will run completely - the rest of the HTML output will be thrown away on the JS side.
This question already has answers here:
JavaScript to reload the page as GET request
(3 answers)
Closed 2 years ago.
I have this weird issue here where I have the following ajax call inside a file called index.php:
$.ajax({
method:'post',
data:
{
action: 'del_comment',
comment_id: comment_id,
},
success: function (data) {
location.reload(true);
}
});
The PHP portion of the page which intercepts the ajax request is the following:
if($_POST['action'] == 'del_comment') {
// Do some processing
die;
}
The issue is that the ajax is executed but when the page is reloaded, the request is a POST instead of a GET. I was under the impression that the following line in the success of my ajax call:
location.reload(true);
Should force a GET request, but it doesn't work. How can I reload the same page with a GET request after the ajax call?
User window.location instead of "location.reload(true);" with the get parameters that you want, you have to create custom URL with parameters and you can use it like (window.location = 'YOUR URL?GET PARAMETER=VALUE';)
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 5 years ago.
I'm writing a jquery code and calling a JavaScript function through it on a jsp page.
This is the jquery function
$(function () {
$('#defaultCountdown').countdown({until: $.countdown('//SomeTime'),onExpiry: liftOff});
});
liftOff is a javascript method which is called after the specified time expires.
This is the JavaScript function
<script>
function liftOff() {
alert("Before Delete");
<% DAO_Object.deleteRecord(ID);%>
alert("After Delete");
}
</script>
Now here the problem is, the line <% DAO_Object.deleteRecord(ID);%> is getting executed before the function call and the record from database is getting deleted. The alert statements are executing correctly AFTER the function call.
Am i calling the deleteRecord method incorrectly?
You are mixing your server-side JSP logic with your client-side JavaScript logic.
Everything between <% %> runs on your servlet when it's processing the request, so the record is already deleted by the time you get the response in the browser. If you look at the HTML/JS you are receiving in the browser using Chrome DevTools or similar tool, you will see that there is nothing between those alert(...) calls.
Your solution here is to setup a route that handles the deleteRecord() on the server-side, and call it via AJAX in your liftOff() method. So liftOff() would look something like this:
// assuming `id` is a string here
function liftOff(id) {
alert("Before Delete");
// You'll have to setup this endpoint to run
// your `DAO_Object.deleteRecord(ID);` code
// in your JSP code.
$.get("/delete/my/record/" + id, {
error: function(e){
// some kind of error occurred in making the request
},
success: function(resp){
// `resp` is the response from the server
alert("After Delete");
}
});
}
This question already has answers here:
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
(14 answers)
Closed 6 years ago.
I want to send to server (php) a request AJAX from an api javascript:
JS File :
var commit = new Object();
commit.id= this.id;
commit.action = this.doCommit;
commit.vrp= this.vrp;
$.post(this.ajaxURL, commit);
with this code i can send a request but in mode asynchroun. I searched on internet and I found a solution :
$.ajax({
type: 'POST',
url: this.ajaxURL,
data: commit,
async:false
});
I don't know if it is the best solution, or I can precise async:false in a $.post request, if yes , how ?.
So you do or you do not want to send the request asynchronously? The question seems to be confusing for me. But by default, $.ajax({... is always async, and $.post is just a shorthand way to write a simple post ajax request, which is also async. If you use the async:false, you are telling the javascript to not continue to execute the next line of code until the request finishes.
Sorry if this is a silly question but I'm completely new to AJAX and I'm wondering why my code is not working like I want..
I have the following:
an Ajax Call looking like that:
$.ajax({
type: "POST",
url: "/newnote.php",
data: {
content: content
},
success: function() {
}
});
and on the beginning of the page newnote.php (which is exactly the one, where the ajax-call is on, I have the following PHP:
if(!empty($_POST)){
header("Location:index.php");
}
But the php on the beginning of the page is not executed, of course, because the site seems not to be reloaded, but, when looking in developer tools under "network", i see that there is a post request on newnote.php with the values I want. But the question is: How can I access them? So for example, if I post the following data: content: "test", that I can write in PHP sth. like <?=$_POST['content'];?>... So how can I access the $_POST-Data from AJAX? Do I need to refresh the page or how does this work?
Thanks for your help
after exchanging I now got the question:
to access to your code you must use the callback of your ajax call
success: function(result){
$("#div1").html(result); // here you put the content that echoes your php inside your div1 on the actual page without reload
}
On the php side where the content is posted you must echo something that will be caught by this ajax call