Call a PHP function after onClick HTML event

139,490

Solution 1

There are two ways. the first is to completely refresh the page using typical form submission

//your_page.php

<?php 

$saveSuccess = null;
$saveMessage = null;

if($_SERVER['REQUEST_METHOD'] == 'POST') {
  // if form has been posted process data

  // you dont need the addContact function you jsut need to put it in a new array
  // and it doesnt make sense in this context so jsut do it here
  // then used json_decode and json_decode to read/save your json in
  // saveContact()
  $data = array(
    'fullname' = $_POST['fullname'],
    'email' => $_POST['email'],
    'phone' => $_POST['phone']
  );

  // always return true if you save the contact data ok or false if it fails
  if(($saveSuccess = saveContact($data)) {
     $saveMessage = 'Your submission has been saved!';     
  } else {
     $saveMessage = 'There was a problem saving your submission.';
  } 
}
?>

<!-- your other html -->

<?php if($saveSuccess !== null): ?>
   <p class="flash_message"><?php echo $saveMessage ?></p>
<?php endif; ?>

<form action="your_page.php" method="post">
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>

<!-- the rest of your HTML -->

The second way would be to use AJAX. to do that youll want to completely seprate the form processing into a separate file:

// process.php

$response = array();

if($_SERVER['REQUEST_METHOD'] == 'POST') {
  // if form has been posted process data

  // you dont need the addContact function you jsut need to put it in a new array
  // and it doesnt make sense in this context so jsut do it here
  // then used json_decode and json_decode to read/save your json in
  // saveContact()
  $data = array(
    'fullname' => $_POST['fullname'],
    'email' => $_POST['email'],
    'phone' => $_POST['phone']
  );

  // always return true if you save the contact data ok or false if it fails
  $response['status'] = saveContact($data) ? 'success' : 'error';
  $response['message'] = $response['status']
      ? 'Your submission has been saved!'
      : 'There was a problem saving your submission.';

  header('Content-type: application/json');
  echo json_encode($response);
  exit;
}
?>

And then in your html/js

<form id="add_contact" action="process.php" method="post">
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input id="add_contact_submit" type="submit" name="submit" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>
    <script type="text/javascript">
     $(function(){
         $('#add_contact_submit').click(function(e){
            e.preventDefault();  
            $form = $(this).closest('form');

            // if you need to then wrap this ajax call in conditional logic

            $.ajax({
              url: $form.attr('action'),
              type: $form.attr('method'),
              dataType: 'json',
              success: function(responseJson) {
                 $form.before("<p>"+responseJson.message+"</p>");
              },
              error: function() {
                 $form.before("<p>There was an error processing your request.</p>");
              }
            });
         });         
     });
    </script>

Solution 2

<div id="sample"></div>   
 <form>
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>

<script>

    $(document).ready(function(){
         $("#submitButton").click(function(){
            $("#sample").load(filenameofyourfunction?the the variable you need);
         });
    });

</script>

Solution 3

You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:

<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
    {
    $new = '{';
    $new .= '"fullname":"' . $_GET['fullname'] . '",';
    $new .= '"email":"' . $_GET['email'] . '",';
    $new .= '"phone":"' . $_GET['phone'] . '",';
    $new .= '}';
    return $new;
    }

function saveContact()
    {
    $datafile = fopen ("data/data.json", "a+");
    if(!$datafile){
        echo "<script>alert('Data not existed!')</script>";
        } 
    else{
        $contact_list = $contact_list . addNewContact();
        file_put_contents("data/data.json", $contact_list);
        }
    fclose($datafile);
    }

// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled

{ ?>

<form>
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact"/>
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->

Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...

Other thought, IE doesn't support placeholder.

Solution 4

 cell1.innerHTML="<?php echo $customerDESC; ?>";
 cell2.innerHTML="<?php echo $comm; ?>";
 cell3.innerHTML="<?php echo $expressFEE; ?>";
 cell4.innerHTML="<?php echo $totao_unit_price; ?>";

it is working like a charm, the javascript is inside a php while loop

Share:
139,490
Shinigamae
Author by

Shinigamae

Young programmer. Good PlayStation player. Coffee lover. http://vn.linkedin.com/in/ntkhanh/

Updated on November 24, 2020

Comments

  • Shinigamae
    Shinigamae over 3 years

    Purpose: Call a PHP function to read data from a file and rewrite it. I used PHP only for this purpose - FileIO - and I'm new to PHP.

    Solution? I tried through many forums and knew that we cannot achieve it normal way: onClick event > call function. How can we do it, are there other ways, particularly in my case? My HTML code and PHP code is on the same page: Admin.php. This is HTML part:

    <form>
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>
    

    This is PHP part:

    function saveContact()
    {
        $datafile = fopen ("data/data.json", "a+");
        if(!$datafile){
            echo "<script>alert('Data not existed!')</script>";
        } 
        else{
            ...
            $contact_list = $contact_list . addNewContact();
            ...
            file_put_contents("data/data.json", $contact_list);
        }
    
        fclose($datafile);
    }
    
    function addNewContact()
    {
       $new = '{';
       $new = $new . '"fullname":"' . $_GET['fullname'] . '",';
       $new = $new . '"email":"' . $_GET['email'] . '",';
       $new = $new . '"phone":"' . $_GET['phone'] . '",';
       $new = $new . '}';
       return $new;
    }
    

    Have a look at these code, I want to call saveContact when people click on Add Contact button. We can reload page if need so. FYI, I use JQuery, HTML5 in page as well. Thanks,

  • inhan
    inhan about 12 years
    ...and the other is to use an AJAX call.
  • Lawrence Cherone
    Lawrence Cherone about 12 years
    you have XSS in your form with action="<?php echo $_SERVER['PHP_SELF']?>"
  • prodigitalson
    prodigitalson about 12 years
    @Lawrence: Well it wasnt supposed to be production code but i changed it for you :-)
  • Shinigamae
    Shinigamae about 12 years
    Great, neat and detail solutions. Regards, @prodigitalson. I'll try them both to see which is better in my case.
  • Shinigamae
    Shinigamae about 12 years
    Me either. If I forced to use a server-side language in my webiste, I'll try ASP.NET. But this is an small demonstration, so I choose PHP for its simple environment (XAMPP, Dreamweavaer, done). I have no idea a bout MySQL though. Thanks for your idea, @Frank Presencia Fandos , I often forget to add breaks to code. Currently test/demo on Chrome/Firefox only, for better HTML5 support :)
  • Francisco Presencia
    Francisco Presencia about 12 years
    I really recommend you to learn the basics about mysql. It's the most used around there and to learn the basics is really easy. When you implement it, the mysql for your site could be as easy as this, the 2nd example.
  • Shinigamae
    Shinigamae about 12 years
    Thanks again, @Frank Presencia Fandos, I am going to learn it.
  • Shinigamae
    Shinigamae about 12 years
    @prodigitalson the 2nd solution has an error, file process.php, line 11, it should be '=>' instead of '=', FYI. I have another question. In 2nd case, the event is triggered right after clicking Submit button. How about I want to write a onClick event - I want to check for offline and online status, we only post data in case online mode - the offline part isn't problem, but I don't know how to call process.php in onClick event? Can we achieve this? More information, I want to 'post' data through a call of Javascript function. If you want to see my demo for more details, please pm me your email.
  • prodigitalson
    prodigitalson about 12 years
    Typo corrected. As far changing to the click handler on the button you can just change the selector and event function youre binding to - i changed example 2 to reflect this. As far as checking status you need to include logicto do you status check before you make the ajax call to post the data. Beyond that pleas post another question.
  • Shinigamae
    Shinigamae about 12 years
    My bad, sorry, I'll create another next time. Appreciate your help till now :) @prodigitalson
  • Shinigamae
    Shinigamae almost 12 years
    Are $customerDESC, @comm etc. functions we want to call, and cells is the sender elements like buttons?