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.

Eddy
  • 3,533
  • 13
  • 59
  • 89
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – dynamic Nov 10 '14 at 12:50

5 Answers5

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.

MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • +1 for remembering (and reminding me) on `e.preventDefault()` – ʰᵈˑ Nov 10 '14 at 13:03
  • @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? – Eddy Nov 10 '14 at 16:47
  • 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. – MinusFour Nov 10 '14 at 16:54
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.

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
  • OK but how do I call this ajax from my html form? – Eddy Nov 10 '14 at 12:52
  • Have a trigger. Anything. What do you want your trigger to be? – ʰᵈˑ Nov 10 '14 at 12:53
  • I imagine that the form inputs are not just for fun - though the OP will need to confirm – Steve Nov 10 '14 at 12:54
  • Simply listen for the button click. `$("form").submit( function() {` – ʰᵈˑ Nov 10 '14 at 12:54
  • @ʰᵈˑthanks, but could you add a complete example of the html file? I'm new to PHP / jQuery. – Eddy Nov 10 '14 at 12:55
  • Modified post for you Eddy. @Steve that's been dealt with the edit, thanks! – ʰᵈˑ Nov 10 '14 at 12:59
  • @ʰᵈˑ, I have a echo "saveTestObject CALLED"; inside my saveTestObject function but I'm not seeing it called. Any idea? – Eddy Nov 10 '14 at 13:04
  • @Eddy - You have the div? Open up the console and see if there are any errors (there shouldn't be) – ʰᵈˑ Nov 10 '14 at 13:05
  • How do yon mean the div? I have the console open but there aren't any errors. Shouldn't the echo print to it? Also the saveTestObject function isn't doing the work it's supposed to do. – Eddy Nov 10 '14 at 13:06
  • Do you have `
    ` in your file?
    – ʰᵈˑ Nov 10 '14 at 13:07
  • I added it. It's showing right when the page renders, even before the button click. – Eddy Nov 10 '14 at 13:14
  • I put a console.log inside the jQuery's success block, and it's being called. But it's also being called if I change the functionname": "saveTasdfestObject" into any other string. – Eddy Nov 10 '14 at 13:18
  • It shouldn't (http://jsfiddle.net/hhvac235/1/) - Do you have the `$("form").submit( function(event) {` ? – ʰᵈˑ Nov 10 '14 at 13:18
  • When I print the response, like this: console.log("success called " + response) from the jQuery success block, the entire php document is printed to the log. What am I doing wrong? – Eddy Nov 10 '14 at 16:23
  • The entire php document being the one with the form, or the one with the `saveTestObject`? – ʰᵈˑ Nov 10 '14 at 16:26
  • @hd, 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? – Eddy Nov 10 '14 at 16:48
  • Would you be able to look in the console and see the request? Also in `sm.php` can you add `echo print_r($_POST, true);` and see if it's actually posting the functionname value? – ʰᵈˑ Nov 10 '14 at 16:57
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
});
oskr
  • 179
  • 1
  • 5
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;
  });

});
MilMike
  • 12,571
  • 15
  • 65
  • 82
  • I imagine that the form inputs are not just for fun - though the OP will need to confirm – Steve Nov 10 '14 at 12:55
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---------------------------