Execute php file with javascript function


I want to execute php file in javascript function. Code is as shown below:

<a id="cancel" href="./?&amp;_action=list" onclick="javascript:clearRecord();return rcm.command('list','',this,event)">Cancel</a>

<script language="javascript" type="text/javascript">
var u1='michael';
function clearRecord() {
        $(function() {
            location.href = 'clear.php?h='+u1;

But when I click to cancel button, clear.php not executed. How I should come out from this?




full & working answer to your question:

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script language="javascript">
        function cancelClicked() {
            // function below will run clear.php?h=michael
                type: "GET",
                url: "clear.php" ,
                data: { h: "michael" },
                success : function() { 

                    // here is the code that will run on client side after running clear.php on server

                    // function below reloads current page

    <a id="cancel" href="#" onclick="cancelClicked()">Cancel</a>



if you want to just execute some php and leave current page to the one generated by this php script. then you got it almost right. I do not see that you are using jquery - so skip this "$(function(){})" part, and i don't see what u1 is added for but this will work:

function clearRecord() { location.href = 'clear.php'; }

and this will do the same:

<a href="clear.php">Cancel</a>

BUT if you want only to run "clear.php" and then reload current page. One way of doing it can be putting at the end of your "clear.php" file something like:


(it will work only if clear.php does't write anything in response).

But you can do it other ways:
- using AJAX - call clear.php with jQuery.get() and call location.reload() on success;
- using IFRAME - set iframe's location to clear.php and then call window.location.reload();
- using IMG - set img.src to clear.php ...
...and possibly many other ways :)

People are also looking for solutions to the problem: html - Php Populate Table and Update


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.