How to call a PHP function with Ajax?

前端 未结 3 793
渐次进展
渐次进展 2021-01-25 02:34

I have a PHP function which returns an array :

function lire( $id) {
            $ret = array() ; 
            $sSQL = \"SELECT  *  FROM produit WHERE prod_code          


        
相关标签:
3条回答
  • 2021-01-25 03:01

    this is the response to the comment you added earlier. I couldnt format it in the comment. Sorry.

     $(document).ready(function() {
    
          $("#idofinput").blur(function(){
    
    
        var value = $.ajax({
        type: "POST",
        url: "some.php",
        data: "name="+$("#idofinput").val(),
        async: false
        }).responseText;
    
        myval= parseInt(value);
    
        if(myval>0)
        {
            //your code goes here
        }
        else
        {
        //your code goes here
        }
    
    
    
        }); 
    
        });
    

    You may attach the function with the input element on document load.

    replace the idofinput with input element id

    0 讨论(0)
  • 2021-01-25 03:16

    You have to put this code block in a php file and will have to call it in the ajax function like:

        var value = $.ajax({
        type: "POST",
        url: "some.php",
        data: "name="+customvariable,
        async: false
        }).responseText;
    

    also the some.php file will have

          if(isset($_POST['name']))
           {
            $id = mysql_real_escape_string($_POST['name']);
            $ret = array() ; 
            $sSQL = "SELECT  *  FROM produit WHERE prod_code = '$id' LIMIT 1" ;
            $this->db->query($sSQL) ;
            $ret['cnt'] = $this->db->num_rows() ;
                        echo $ret;
          }
    

    You will get the return value in the value variable.

    0 讨论(0)
  • 2021-01-25 03:17

    In AJAX you make simple HTTP request to some web resource. To get the data from your function you can provide simple php script which will have url parameter (id) and call your function. Than you

    can use suitable Javascript libaray (e.g. jQuery) to call the page with that parameter.

    function lire( $id) {
            $ret = array() ; 
            $sSQL = "SELECT  *  FROM produit WHERE prod_code = '$id' LIMIT 1" ;
            $this->db->query($sSQL) ;
            $ret['cnt'] = $this->db->num_rows() ;
                        return $ret;
    }
    
    $result = lire($_GET['id']); // CONSIDER SOME ESCAPING OF USER INPUT FOR SECURITY!
    echo $result; // OR USE SOME OTHER SORT OF SERIALIZATION (e.g. JSON)
    

    Maybe you will have to set the headers (MIME type of the result).

    0 讨论(0)
提交回复
热议问题