0

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.

1

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for remembering (and reminding me) on e.preventDefault()
@MinusFour, your code doesn't call the function for some reason. It recognizes the SM.php file (if I change the name I get an error.) But the function isn't called, and if I change the name of it to something random, functionname: 'whateverrandom' I don't even get an error message. Is it something with my SM.php? Could you take a look at in in my question?
Check on your browser network tab (F12 if you are in chrome) and see the ajax call. Check if there's data printed out to SM.php call.
3

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.

17 Comments

OK but how do I call this ajax from my html form?
Have a trigger. Anything. What do you want your trigger to be?
I imagine that the form inputs are not just for fun - though the OP will need to confirm
Simply listen for the button click. $("form").submit( function() {
@ʰᵈˑthanks, but could you add a complete example of the html file? I'm new to PHP / jQuery.
|
0

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

Comments

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

});

1 Comment

I imagine that the form inputs are not just for fun - though the OP will need to confirm
0
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---------------------------

3 Comments

None of the alerts shows up, and the echo in the saveTestObject isn't called.
Hey please add ready function for script i missed this. $(document).ready(function(){ });
where should I add it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.