如何从jQuery调用PHP函数?

时间:2016-05-08 22:53:30

标签: javascript php jquery

我正在尝试在提交表单后使用jQuery调用特定的php函数,无论如何要实现这一点吗?

这是我的代码:

HTML

localstorage

的jQuery

<form id="frmAgregar" method="post">
    <input id="txtcant" class="centrado" type="number" value="1" required>
    <input class="btnSubmit btnResize" type="submit" value="Agregar +">
</form>

PHP

$("#frmAgregar").submit(function() {
    if ($("#txtcant").val() < 1 || $("#txtcant").val() == "") {
        return false;
    } else {
        var popup = document.getElementById("popupAgregado");
        popup.setAttribute("style", "display: block;");
        popup.setAttribute("class", "popupAgregado");       
        setTimeout(function () {popup.style.display='none'}, 1700);

        //HERE'S WHERE I NEED TO CALL THE PHP FUNCTION
    }   
});

任何帮助都将非常感激。

先谢谢你。

1 个答案:

答案 0 :(得分:0)

对于那些可能需要一些类似问题帮助的人,我正在分享我如何解决这个问题......

<强> HTML

<form id="frm-addcart" method="post">
  <input id="txt-quantity" class="text-center" type="number" value="1" required>
  <input id="btn-submit" class="submitted btn-resize" type="submit" value="Agregar +">
  <input type="hidden" id="checker-login" name="checker-login" value="isValid">
</form>

<强>的jQuery

$("#btn-submit").on("click", function (event) {

  // DEFAULT ACTION OF THE EVENT WILL NOT BE TRIGGERED
  event.preventDefault();

  // GET THE VALUES FROM THE FORM
  var clickBtnValue = "btn-addcart";
  var checkerLogin = $("#checker-login").val();
  var quantity = $("#txt-quantity").val();

  // USE AJAX TO CALL THE PHP FUNCTION
  $.ajax({
    type : 'POST',
    url : 'php/functions.php',
    data : {
        "action" : clickBtnValue,
        "checkerLogin" : checkerLogin,
        "quantityAdded" : quantity      
    },
    success : function (data) {

        // data IS THE VALUE THAT THE PHP FUNCTION RETURNS THROUGH echo
        if (data == "valid") {
            window.location.href = "home.html";                     
        } else {                        
            alert("Something went wrong.");             
        }

    },
    error : function() {

        alert("An error has ocurred.");

    }
  });      

});

<强> PHP

if (isset($_POST["action"]) == true) {
  switch ($_POST["action"]) {

    case "btn-addcart":
      insertData();
      break;

  }
}

function insertData() {

  // GET DATA FROM AJAX PARAMETERS
  $checkLogin = $_POST["checkerLogin"];
  &quantity = $_POST["quantityAdded"];

  // VALIDATE AND EXECUTE REST OF FUNCTION
  // AND IF EVERYTHING GOES OK
  echo "valid";
  exit();

}

就是这样!我正在从jQuery调用PHP函数。

享受!