-2

I'm not familiar with ajax and I'm trying to submit a form using one PHP page and ajax so that after form is submitted/updated the page doesn't refresh completly. the php page is loaded on a div section of a parent page.

Can someone point me in the right direction how to submit the form without refreshing the entire page?

Below the code I have so far, and it is only all in one php file. Thank you

<?php
$servername = "data";
$username = "data";
$password = "data";
$database = "data";
$successAdd="";
$errorAdd="";
$connect = mysql_connect($servername, $username, $password) or die("Not   Connected");
mysql_select_db($database) or die("not selected");
 if (isset($_POST['Add'])) {

$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
    if ($file_error == 0) {
        $file_name_new = $venueName . '.' . $file_ext;
        $file_destination = 'images/category/' . $file_name_new;
        if (move_uploaded_file($file_tmp, $file_destination)) {
            $sql = "INSERT INTO `categorytable`(`category`) VALUES ('$venueName')";
            $result = mysql_query($sql, $connect);
            if ($result != 0) {
                $successAdd = "Success fully done";
            } else {
                $errorAdd = "Not done ";
            }
        }
    } else {
        $errorAdd = "Something is wrong";
    }
} else {
    $errorAdd = "Only png file allowed";
}
}


if (isset($_POST['Update'])) {
    $venueName = $_POST['cname'];
    $file = $_FILES['file'];
    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];
    $file_ext = explode('.', $file_name);
     $file_ext = strtolower(end($file_ext));
    $allowed = array('png');
    if (in_array($file_ext, $allowed)) {
       if ($file_error == 0) {
            $file_name_new = $venueName . '.' . $file_ext;
             $file_destination = 'images/category/' . $file_name_new;
             if (move_uploaded_file($file_tmp, $file_destination)) {
            $successAdd = "Success fully done";
            }else{
             $errorAdd = "Not Updated";  
            }
        } else {
            $errorAdd = "Something is wrong";
        }
    } else {
        $errorAdd = "Only png file allowed";
        }
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Test</title>




    </head>
    <body>
    <h3 style="color: red"><?php echo $errorAdd; ?></h3>
    <h3 style="color: green"><?php echo $successAdd; ?></h3>
    <!--<div style="float: left;width: 50%">-->
    <h1>Add Category</h1>
    <form action="" method="POST" enctype="multipart/form-data" id="add-category" >
        Category Name <input type="text" name="cname" value="" /><br/>
        Category Image <input type="file" name="file"  accept="image/x-png"/><br/>
        <input type="submit" value="Add" name="Add"/>
    </form>
    <!--</div>-->

    <!--<div style="float: left;width: 50%">-->
    <h1>Update Category</h1>
    <form action="addCategory.php" method="POST" enctype="multipart/form-data" >
        Select Category<select name="cname">
            <?php
            $sql = "SELECT * FROM `categorytable`";
            $result = mysql_query($sql);
            while ($row = mysql_fetch_array($result)) {
                ?>
                <option value="<?php echo $row[1]; ?>"><?php echo    $row[1]; ?></option>
            <?php } ?>
        </select><br/>
        Category Image <input type="file" name="file"  accept="image/x-png"/><br/>
        <input type="submit" value="Update" name="Update"/>
    </form>
    <!--</div>-->

    <div style="width: 25%;margin: 20px auto;float: left">
        <table border="1">
            <tr>
                <th>Category Name</th>
                <th>Category Image</th>
            </tr>
            <?php
            $sql = "SELECT * FROM `categorytable`";
            $result = mysql_query($sql);
            while ($row = mysql_fetch_array($result)) {
                ?>
                <tr>
                    <td><?php echo $row[1]; ?></td>
                    <td>
                        <img src="images/category/<?php echo $row[1]; ?>.png" height="50"/>
                    </td>
                </tr>

                <?php
            }
            ?>
        </table>

    </div>


</body>

J.Rem
  • 545
  • 2
  • 6
  • 24
  • 1
    What ajax? There is no ajax in there at all. There is no javascript, period. – Marc B Sep 14 '16 at 19:05
  • 3
    We should start with avoiding `mysql_connect` :) – Gynteniuxas Sep 14 '16 at 19:05
  • Check this [AJAX tutorial](http://stackoverflow.com/questions/6009206/what-is-ajax-and-how-does-it-work) – Hail Hydra Sep 14 '16 at 19:07
  • You need a lot of good tutorials. This question is way too broad. – GolezTrol Sep 14 '16 at 19:07
  • You are open to SQL injections. Seems like you are just looking for AJAX tutorial, http://learn.jquery.com/ajax/. – chris85 Sep 14 '16 at 19:10
  • Thank you, I know there is no js and ajax in there. I'm just triyng to help with something and what I want to do is to take the form above so that when I submit it doesn't refresh everything but just submits the data. I know I can use ajax and js but I'm not familiar with it. The way it is now it submits but refresh the entire page which is not I'm looking for. – J.Rem Sep 14 '16 at 20:20

1 Answers1

0

First things first, swap to PDO, ASAP. This will save you TONS of time and can help with SQL execution time, when used correctly (You can find a quick PDO tutorial here). To answer question, I would recommend you start with importing the jQuery library. It allows near effortless manipulation of the DOM.

Then, just do something like

$('#your-form-id-here').submit(function(clickEvent){
    $.ajax({
       url: 'http://www.foo.com/',
       data: $('#your-form-id-here').serialize(),
       method: 'POST',
       success: function(Response){
          //If the request is successful, this code gets executed
       },
       error: function(){
          //If the request failed, this code gets executed
       }

    });

    return false; <----This prevents the page from refreshing
});

Now lets break it down a bit

data: $('#your-form-id-here).serialize() <-- This gets all of your form data ready

NOTE: There's way more to it than this. You'll need to do some server-side stuff to make this work right. For instance, if you want a JSON object back, you'll need to return it. In php, I like to do something like

if(My request succeeded){
   echo(json_encode(array(
      'status'   => 'success',
      'message'  => 'Request description/whatever you want here'
   )));
}
Native Coder
  • 1,792
  • 3
  • 16
  • 34
  • Thank you Native, I tried to do that and I also imported the jquery library hoewever, the data doesn't go to database for some reason, it goes through success event but doesn't seem to submit any data at all. – J.Rem Sep 14 '16 at 20:29
  • One gotcha I came across. if the datatype is "json" the success function will get called everytime you get a valid json object back (this doesn't necessarily mean that your request succeeded). So try console.log(Response) in the success function, and check in the dev console to see exactly what the server is sending back. – Native Coder Sep 14 '16 at 20:30
  • Nothing Nada. I have an index.php and I load the content of the code above: addCategory.php to a div "container". So I don't want the entire index.php to refresh. I just want the section from addCategory.php to refresh after data is submitted. – J.Rem Sep 14 '16 at 20:54
  • Well you are trying to mix server-side and client-side logic there. I would create a file that is meant to be called via AJAX. that file would return the rendered HTML to the AJAX request. then just use jQuery to replace the HTML of the div with the HTML that the server sent back. Make sense? The problem with what you want to do is that PHP just renders stuff. The client (web browswer) never even get's the glimpse the PHP. The server runs the PHP script, and the output of that script gets sent to the client – Native Coder Sep 14 '16 at 21:19
  • Well, after a little more research I realized that I couldn't use serialize() because I was sending a form with post method. I wanted to pass a file via ajax. So I had to use FormData instead. Now, it is working however it is always goes thru 'success' wheter I fill all the fields or not. – J.Rem Sep 14 '16 at 22:21
  • Yes, as long as you get a valid response from the server it will go through the success call back. Read the note on my answer above ;) – Native Coder Sep 15 '16 at 14:02