如何在jquery AJAX中使用参数调用php函数

时间:2015-03-12 12:52:41

标签: javascript php jquery ajax

我通过javascript从html表单获取值,我试图调用通过AJAX接受参数的php函数。但我无法完成它。我怎么能这样做?

php代码:

<?php
function updateJbdesc($jobdesc,$loginid) 
{
    include 'dbc.php';
    // Create connection
    $conn = new mysqli($hostname, $username, $dbpassword, $dbname);
    // Check connection
    if (!$conn) 
    {
        die("Connection failed: " . mysqli_connect_error());
    }
    $sql = "update table profile set employee_title ='$jobdesc' where login = '$loginid'";
    if (mysqli_query($conn, $sql)) 
    {
        echo "New Project Added!";
    } 
    else 
    {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
    mysqli_close($conn);
}

?>

Ajax代码:

$.ajax({ url: 'allfunctions.php',
         data: {action: 'updateJbdesc'},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

如何通过ajax将参数传递给php函数?

1 个答案:

答案 0 :(得分:0)

您需要添加一些代码来获取$ _POST值并使用它们来调用该函数。

$val0 = $_POST[ 'val0' ];
$val1 = $_POST[ 'val1' ];
$functionId = $_POST[  'functionid' ];

$result = -1;
if( $functionId == 0 ) $result = somefunction( $val0, $val1 );
else $result = someotherfunction( $val0, $val1 );

# echo this to return result to ajax
echo $result; 

您可以通过ajax传递一个值来告诉PHP您想要哪个函数:

$.ajax({ url: "myurl.php",
    data: { val0: "val0", val1: "val1", functionid: "identifier" }
}).done( function( result ) { alert( result ); });