Call a PHP function after onClick HTML event

前端 未结 4 1452
迷失自我
迷失自我 2021-02-08 15:16

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

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-08 16:07

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

    //your_page.php
    
     $_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.';
      } 
    }
    ?>
    
    
    
    
       

    Add New Contact


    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

    Add New Contact


提交回复
热议问题