Pages

Call php function from ajax?

You can call PHP function like this using ajax, but not as directly call from AJAX url.

Here, Ajax Part  for explanation, set path url of db.php for call ajax and get result

 $.ajax({
      url: "http://localhost/db.php",
    data: frm_mail_data,
    cache: false,
    processData: false,
    contentType: false,
    type: 'POST',
        success: function (result) {
            alert(result);
            document.getElementById('div_result').innerHTML=result;
           }
  });

Step 1. Create index.php


 <form method="post" id="frm_mail" action="">
   <input type="input"  id="name" name="name" placeholder="name">   
   <input type="hidden"  id="fun_name" name="fun_name" value="test">    
  <input type="button"  id="target" name="btnfrm" value="submit">
  </form>
<div id="div_result"></div>
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  <script>
  $(document).ready(function(){
     $( "#target" ).click(function() {

    var frm_mail = document.getElementById("frm_mail");
    var frm_mail_data = new FormData(frm_mail);
        $.ajax({
      url: "http://localhost/db.php",     //live
    data: frm_mail_data,
    cache: false,
    processData: false,
    contentType: false,
    type: 'POST',
        success: function (result) {
    alert(result);
            document.getElementById('div_result').innerHTML=result;
           }
        });
   });

  });
  </script>
step 2. Create a db.php
<?php 

//print_r($_POST);
if($_POST['fun_name']=='test'){
  $name=$_POST['name'];
  //call function
  echo test($name);
  exit(0);
}

 function test($name){
 return "Hello! ".$name;
}

?>

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Popular Posts