Stop form submition?

I have a form which stores data to mysql.It works fine and there are no errors.The form contains name,price,category and image field when i click on submit button the data is inserting into database perfectly.but when i miss uploading an image it is not submitting but the page is refreshing when i click on submit button by which i am lossing all the data of other fileds.Finaly, what my doubt is i need to stop refresh when i miss uploading a image. Mycode is

<form enctype="multipart/form-data" action="#" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<label>Name:</label><input type="text" name="name" id="name" size="25"/><br />
<label >Price:</label><input type="text" name="price" id="price" size="25"/><br />
<label>category:</label>
<?php

       $con=mysql_connect("","","");

        if(!$con)
        {
            die('couldnot connect to database'.mysql_error());
        }

       mysql_select_db("dbname",$con);

        $dropdown=0;
            $result=mysql_query("select DISTINCT(category) from category") or die("No such table"."<br/><br/>".mysql_error());
            while($row=mysql_fetch_array($result))
                 {
                     $dropdown.="\r\n<option value='{$row['category']}'>{$row['category']}      </option>";
                }


        ?>
          <?php   echo "<select name= 'category' id='category' style='width:14em;'>".$dropdown."</select>";?><br />

         <label style="color:#FFFFFF;font-weight:bold">Description:</label></td><td> <input type="text" name="description" id="des" 
         size="40"/><br />
         <label style="color:#FFFFFF;font-weight:bold">Upload Image:</label></td><td><input name="userfile" type="file" /><br /><br
         >

        <input type="submit" value="Submit" id="submit" style="color:#2594BA;font-size:18px;text-decoration:none;background:#FFF;
        padding:3px;border-radius:5px;padding-left:8px;padding-right:8px;"/><br><div id="errormessage">insert data</div>
    </form>
</div>
<?php

    if(!isset($_FILES['userfile']))
    {


    }
    else
    {
        try {
            $msg= upload();  //this will upload your image
            echo $msg;  //Message showing success or failure.
        }
        catch(Exception $e) {
        echo $e->getMessage();
        echo 'Sorry, could not upload file';

        }
    }

    // the upload function

    function upload() {
        if(empty($_FILES['userfile']))
        {
            die();
        }

       /*database connection code;*/
        $maxsize = 10000000; //set to approx 10 MB

        //check associated error code

         if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {

            if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {    

                if( $_FILES['userfile']['size'] < $maxsize) {  

                         $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
                       mysql_connect($host, $user, $pass) OR DIE (mysql_error());

                        mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());

                        $sql = "INSERT INTO menu(name,description,price,picture,category)
                        VALUES
                        ('{$_POST['name']}','{$_POST['description']}','{$_POST['price']}','images/{$_FILES['userfile']['name']}','{$_POST['category']}');";

                        // insert the image
                        mysql_query($sql) or die("Error in Query: " . mysql_error());

                        $msg='<p>data successfully inserted into database with id ='. mysql_insert_id().' </p>';
                }
                 else {
                    $msg='<div>File exceeds the Maximum File limit</div>
                    <div>Maximum File limit is '.$maxsize.' bytes</div>
                    <div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
                    ' bytes</div><hr />';
                    }
            }
            else
                $msg="File not uploaded successfully.";

        }
        else
         {
            $msg= file_upload_error_message($_FILES['userfile']['error']);
            echo $msg;
         }
    }

    // Function to return error message based on error code

    function file_upload_error_message($error_code) {
        switch ($error_code) {
            case UPLOAD_ERR_INI_SIZE:
                return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
            case UPLOAD_ERR_FORM_SIZE:
                return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
            case UPLOAD_ERR_PARTIAL:
                return 'The uploaded file was only partially uploaded';
            case UPLOAD_ERR_NO_FILE:
                return 'No file was uploaded';
               case UPLOAD_ERR_NO_TMP_DIR:
                return 'Missing a temporary folder';
            case UPLOAD_ERR_CANT_WRITE:
                return 'Failed to write file to disk';
            case UPLOAD_ERR_EXTENSION:
                return 'File upload stopped by extension';
            default:
                return 'Unknown upload error';

        }

    }
   ?>

Answers


You can use javascript to validate and limit the form submission like below. It returns false if the userfile field is empty.

function validate_form(thisform)
{
    with (thisform)
    {
        if (userfile.value==="")
        {
            return false;
        }
    }
    return true;
}

in your for tag

<form onsubmit="return validate_form(this)">

  1. You can add the html5 "required" attribute in the client side.
  2. You can also validate in the JS by checking if it's value is null. For that you can use javascript's document.getElementsByName method or you can use Jquery's $('#id').val() method.

PS: I would recommend that you validate it server-side as well.


Stopping the page refresh server side is needlessly complex. This is because, according to the Request-Response model, the user has made their request. The page refresh has all but happened. But what you can do, is use some client side script to prevent the request from ever firing. Most commonly, Javascript is perfect for this:

function validate()
{
     if($('nameTxt').text() != "" && $('otherTxt').text() != "" ...)
     {
        this.submit();
     }
}

NOTE: I've assumed the use of jQuery in my example. People often use frameworks with javascript, but this isn't necessary. See JJPA's answer for a Framework free option.


I have solved my problem. I have just added validation to file type.That's it. and thanks for your valuable suggestions.


Need Your Help

Determining Order of Method Calls in Java Eclipse

java eclipse

Imagine you are handed a Java Eclipse Project. In this project there are a bunch of classes that call methods on each other, pass parameters and get things done, so the classes withing the project ...

Make 100% width div fit within another div and avoid horisontal scrollbar

html css

So I don't want any horisontal scrollbars but I want the div to fill 100% of it's parent. The code works in FF and IE8 but not for IE7 and below. How can I solve this preferably with CSS only?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.