简体   繁体   中英

simple PHP AJAX : How to call a php script

I'm trying to get my javascript function to use ajax to call a php script. The php script will update a MYSQL table but I've tested the PHP script and it works fine.

This is my function:

    function rate()
{

 $.ajax({
    data: '' ,       
    url: 'update.php',
    method: 'GET', 
    success: function(msg) {
        alert(msg);
    }
});

}

and the function is called later with:

rate();

The php script doesn't need any information given to it, it just needs to be called, can anyone point out where I'm going wrong.

Just use like in this example:

<script>
  function rate() {
    $.get("update.php");
  }
</script>

Here is an example of how I use the ajax call:

$.ajax({
                               type: "POST",
                               url: "page_url",
                               dataType: 'json',
                               data: {
                                   'date1' : date1,
                                   'call': 'function_name'
                               },
                               beforeSend: function(){
                                   $("#loading").show();
                               },
                               success : function(response){    
                                  },
                                complete: function(){ 
                                   $("#loading").hide();
                               }
                      })

and on php part I add:

function function_name($request){
  your code here
}

if (!empty($_POST['call'])) {
    die($_POST['call']($_POST));
}

If you dont need to pass the data to the PHP page, you can omit 'Data' from the ajax parameters.

<script>
    function rate(){
        $.ajax({      
            url: 'update.php',
            method: 'POST', 
            success: function(msg) {
               alert(msg);
            }
        });
    }

    rate();
</script>

Have you included jquery library Try this

<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
<script>
      function rate()
{

 $.ajax({
    data: '' ,       
    url: 'update.php',
    method: 'GET', 
    success: function(msg) {
        alert(msg);
    }
});

}


    rate();


</script>

i show my all working code, try it:

<html>
  <head>
    <script type="text/javascript" src="/js/jquery-1.8.2.js"></script>
    <script>
      function rate() {
        $.get("update.php");
      }
    </script>
  </head>

  <body>
    <button onclick="rate()">Click me</button>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM