I am very confused and I cannot find the right way. I have a problem which I'll try to make it simple with the following example. First, code of test.php:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script src="test1.js"></script>
</head>
<body>
<input value="press" type="button" onclick="test()">
<script>
alert ("Home");
</script>
</body>
</html>
and now the test1.js code:
function test()
{
alert("Test1");
$.post("test.php");
}
From my point of view I'd expect three alert windows:Test1,Home and Test1 again for I thought test.php would refresh after $.post("test.php") is called. What am I missing? What is my fault?
I want to do exactly that in pages with more complex code (namely, to make a php page to refresh after a click button inside its own body which will execute some JS code first). I 'd appreciate your explanation and your solution as to clarify it.
You just send request to remote server and do not work with respond.
From jquery documentation:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So what you are doing is sending an ajax request. This means the page does not get reloaded, and the result from the server is sent back to the callback function provided for the post request and it should be processed there.
To refresh the page you should submit a form like this:
$('#formid').submit(callbackFunction);
Of course I guess for this solution you should add a form in your html first...
If all you want to do is refresh your page, you do not need a post
or ajax
. Use this function instead:
function test()
{
alert("Test1");
window.location.reload(true);
}
$.post("test.php");
can only send your variables or data or any kind of request to test.php. It does not get all the code from test.php and run it in your page. if you want some response from test.php use:
$.ajax("test.php");
this method send request or data to test.php and then also have the ability to handle some responce ie:
$.ajax(
url: "test.php",
data: null,
type:"post",
success: function(result){
alert(result);
}
You should use location.reload(true); overload which not loads from the cache.
the true param make it not to be read from cache
$.post
use window.location.reload(true)
$(document).ready
include $(document).ready
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script src="test1.js"></script>
</head>
<body>
<input value="press" type="button" onclick="test()">
<script>
alert ("Home");
</script>
</body>
</html>
function test()
{
alert("Test1");
window.location.reload(true);
}
Sequence of alert will be home
--> test1
--> home