1

I'm trying to call a specific php function using jQuery after my form is submitted, is there anyway to achieve that?

Here's my code:

HTML

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

jQuery

$("#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
    }   
});

PHP

<?php
    function insertarDato() {
        $cant = $_POST["txtcant"];
        $query_insertarcontacto = mysql_query("INSERT INTO pedidotemp(cant) VALUES('$cant')", $cnbddelicomi) or die(mysql_error());
    }
?>

Any help will be really appreciated.

Thank you in advanced.

Leandro Soriano
  • 669
  • 1
  • 6
  • 14
  • If you're redirecting the user, just use window.location? – Terry May 08 '16 at 22:55
  • Your header if for html not php – Pedro Lobito May 08 '16 at 22:57
  • Not directly. JavaScript can invoke a PHP file with Ajax (or the `
    ` can submit to it), and that file can invoke the function.
    – Jonathan Lonowski May 08 '16 at 22:58
  • yes I know, the thing is, I'm going to make php functions to insert and select data from a database. That's why I need to know how to call a specific function. – Leandro Soriano May 08 '16 at 22:58
  • I also tried: $.ajax({ url: 'functionsphp.php' }); while putting the code in a external file. – Leandro Soriano May 08 '16 at 23:00
  • @LeandroSS The ajax request can only request the file as a whole, not a specific function. So, `functionsphp.php` will have to invoke `IrA()` itself. – Jonathan Lonowski May 08 '16 at 23:01
  • exactly I couldn't remember but try it or this – Ivan Barayev May 08 '16 at 23:06
  • Do a POST AJAX call to functionsphp.php passing the value(s) as post data and in functionsphp read the value(s) using $VALUE = $_POST['X']; – Misunderstood May 08 '16 at 23:06
  • You can't resend a header for a served page even through AJAX. So even if said PHP function is called, the page cannot, and will not, be refreshed. Headers can only be sent before any actual output. – Terry May 08 '16 at 23:07
  • I updated the PHP code to a mysql query, how can i call it to insert the data succesfully to the database? from jquery ofcourse... – Leandro Soriano May 08 '16 at 23:19
  • @Terry not true. The AJAX call is its own http request with its own http request headers and the AJAX headers have nothing to do with the containing page's http request and response. – Misunderstood May 09 '16 at 00:06
  • You can try to use [php function call using javascript](http://stackoverflow.com/questions/15757750/php-function-call-using-javascript) – GSP May 09 '16 at 01:58
  • @Misunderstood I think you misunderstood me here. OPs original code involves invoking a refresh header when the Ajax call is made on the page triggering the Ajax call. You cannot remotely trigger a page refresh from AJAX unless you do it via JS. By issuing a new header via AJAX you are only declaring the header of the file called by AJAX, not the page that did the calling. But I can see that OP has changed his approach now. – Terry May 09 '16 at 06:11

1 Answers1

0

To anyone who might need some help with a similar issue, I'm sharing how I solved this one...

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();

}

And that's it! I'm calling a PHP function from jQuery.

Enjoy!

Leandro Soriano
  • 669
  • 1
  • 6
  • 14