Gravy
Gravy

Reputation: 12445

Degradeable jquery ajax forms with PHP - Code Repetition

Assuming I have a form which I wish to submit. I have built it and the form action="". As such, I can access the posted data via if(isset($_POST['something']))

EXAMPLE form.php (CODE NOT CHECKED AND JUST TO ILLUSTRATE POINT):

<?php
    $result = '';

    if (isset($_POST['something']) {
        $sql = 'SELECT * FROM aTable WHERE Name = :name';
    $stmt = $db->prepare($sql); 
    $stmt->execute(array(':name' => $_POST['something']);   
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);    
    }
?>

<form action="" method="post">
    <input type="text" name="something" />
    <input type="submit" value="post" />
</form>

<div id="result">
    <pre>
    <?php echo $result; ?>
    </pre>
</div>

Now I wish to process the form with jquery/js if the user has got js enabled.

I know how to do this. However I have a problem with database access e.g. having the same query run in 2 php files. One in my original form page which is utilised when js it turned off and returns an associative array of data. I then have an ajaxData.php which returns json but is basically the same sql query.

EXAMPLE AJAXDATA.php

<?php
    $result = '';

    if (isset($_POST['something']) {
        $sql = 'SELECT * FROM aTable WHERE Name = :name';
    $stmt = $db->prepare($sql); 
    $stmt->execute(array(':name' => $_POST['something']);   
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);    

    echo json_encode($result);
    }

?>      

This is inefficient in my opinion because I am writing the same code, same data access etc... twice - once for form.php and once for ajaxdata.php.

How should I structure my forms/files so that ajax uses the same database access & sql code as the normal form submit?

Upvotes: 0

Views: 244

Answers (1)

Arif
Arif

Reputation: 1726

For html change
Add onSubmit event to handle js enable/disable

     <form action="" method="post" onSubmit="return process_ajax();">
       <input type="text" name="something" />
       <input type="submit" value="post" />
     </form>

in precess_ajax() return false so that form will not be submitted, and if js is disabled form will be submitted. All parameters must be same as if form posted. Send an extra parameter in AJAX say ajaxForm to test on server side if post is by form or AJAX

Now for server side PHP code Check for the extra paratmeter ajaxForm if it is set or have value that you sent in AJAX send JSON response else send HTML page. Your code will look like this

      if (isset($_POST['something']){
        $sql = 'SELECT * FROM aTable WHERE Name = :name';
        $stmt = $db->prepare($sql); 
        $stmt->execute(array(':name' => $_POST['something']);   
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);    
        if(isset($_POST['ajaxForm'])){
          //send JSON response
        }
        else{
          //show html page here
        }   
      }

    ?> 

Upvotes: 1

Related Questions