简体   繁体   中英

Calling php function from jQuery

I have a saveTestObject() method in a PHP file, and I need to call it from HTML with jQuery . I looked around but there seems to be no complete example out there. I would really appreciate one.

Here's my PHP file, which is called SM.php :

<?php

switch($_POST["functionname"]){ 

     case 'saveTestObject': 
        saveTestObject();
        break;   
}   

function saveTestObject() {
    echo "saveTestObject CALLED";

    $object = ParseObject::create("TestObject");
    $objectId = $object->getObjectId();
    $php = $object->get("elephant");

    // Set values:
    $object->set("elephant", "phpserver");
    //$object->set("today", new DateTime());
    $object->setArray("mylist", [1, 2, 3]);
    $object->setAssociativeArray(
      "languageTypes", array("php" => "awesome", "ruby" => "wtf")
    );

    $object->save();
}

?>

My HTML form in smpage.html looks like this:

<form>    
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>    
    <input type="submit"/>
</form>

How do I connect the two, so that when I press the submit button the saveTestObject() function is called?

Both SM.php and smpage.html reside in the save directory in my web server's Documents .

You'll have to do an AJAX call to the page.

 $('form input[type=submit]').on('click', function(e) {
    e.preventDefault();
    $.post('SM.php', {fname : $('form input[name=fname]').val(), lname : $('form input[name=lname]').val(), functionname: 'saveTestObject'});
 });

Just a quick note. preventDefault is needed on this case because it will stop the submission event (which redirects the browser).

Edit : Added the url.

You've got jQuery tagged, so lets use $.post because you're switching on $_POST["functionname"] .

$("form").submit( function(event) {
    event.preventDefault();
    $.ajax({
      type: "POST",
      url: 'sw.php',
      data: {"functionname": "saveTestObject"},
      success: function(response) { $("#response").html(response); }
    });
});

This will send a request to sw.php, with post data of functioname = saveTestObject , thus calling the function because of the switch case.

Edit

This would make your HTML file become something like;

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>    
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>    
    <input type="submit"/>
</form>

<script>
    $("form").submit( function(event) {
        event.preventDefault();
        $.ajax({
          type: "POST",
          url: 'sw.php',
          data: {
                "functionname": "saveTestObject", 
                "fname" : $("form input[name=fname]").val(),
                "lname" : $("form input[name=lname]").val()
          },
          success: function(response) { $("#response").html(response); }
        });
    });
</script>

You can then use;

  • $_POST['functionname']
  • $_POST['fname']
  • $_POST['lname']

The success is optional, but I like to see the result of the AJAX request. If you do, add a div with the id response to your file ( <div id="reponse"></div> ) somewhere you'd like to display the result.

To call that function with ajax you could do something like this:

$.ajax({
   url: "SM.php", //The requested url
   type:"POST", //The request type, post, get...
   data: {functionname:"saveTestObject"} //The data you want to send to server
});
$(function(){

  //If you submit the form:
  $("form").submit(function(){

    //post data to your php file
    $.post("SM.php", {functionname: 'saveTestObject'}, function(re){
      alert("Saved. returned" + re);
    });
    return false;
  });

});
Hi Copy this code and past to 'smpage.html' file run it. 
            <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
            <script type='text/javascript'>
            $("#formid").submit(function(event){
            $fname_val=$("input[name=fname]").val();
            $lname_val=$("input[name=lname]").val();
               $.ajax({
                    url: "SM.php",
                    type: "post",
                    data: {'functionname':'saveTestObject','firstname':$fname_val,'lastname':$lname_val},
                    success : function(data){
                          alert("Data saved successfully !");
                    },
                    error: function(){
                        alert('failed');
                    }
                });

            });
            </script>
            <form id="formid">    
                First name: <input type="text" name="fname"><br>
                Last name: <input type="text" name="lname"><br>    
                <input type="submit"/>
            </form>
            ----------smpage.html---------------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM