Faxsy
Faxsy

Reputation: 361

Ajax upload and add to database

I have a form to add team to database, so I would like to insert the team into database and upload the logo to the teams directory. The HTML FORM

        <form action="index.php#list_teams" id="subjectForm" method="post" enctype="multipart/form-data">
        <p>
            <label>Team name</label>
            <input class="text-input medium-input" type="text" id="name" name="name" maxlength="20" />
        </p>
        <br>
        <p>
            <label>Team Logo (50x50px) </label>   
            <div id="image_preview"><img id="previewing" src="images/preview.png" /></div>
            <div id="selectImage">
            <label>Select Your Image</label><br/>
            <input type="file" name="file" id="file" />
            <h4 id='loading' >loading..</h4>
            <div id="message"></div>
            </div>
        </p>
        <br />
        <br />
        <br />
        <p>
            <input class="btn" type="submit" value="Add" />&#32;
            <input class="btn" type="reset" value="Reset" />
        </p>
    </form>

THE JS

$(document).ready(function(){
    $('#subjectForm *').each(function(){
        if(this.type=='text' || this.type=='textarea'){
            $(this).blur(function(){
                validForm(this.form,this.name);
            });
        }
    });
    $('input[type="submit"]').click(function(){
        if(validForm(this.form,'')){
            $.ajax({
                url: 'post.php',
                type: 'POST',
                data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + '&file=' + encodeURIComponent($('#file').val()),
                success: function(data) {
                    $('#notice').removeClass('error').removeClass('success');
                    var status = data.split('|-|')[0];
                    var message = data.split('|-|')[1];
                    $('#notice').html('<div>'+ message +'</div>').addClass(status);
                    $('#notice').fadeIn().animate({opacity:1}, 5000, 'linear', function(){$(this).fadeOut();});
                    $('#name').val('');
                    $('#file').val('');
                }
            });
        }
        return false;
    });
    $('input[type="reset"]').click(function(){
        $('.content-box-content').find('span.input-notification').each(function(){
            $(this).remove();
        });
        $('.content-box-content *').each(function(){
            $(this).removeClass('error');
        })
    });

and here is POST.php

if ($_POST['do'] == 'addteam')
{
$name = urldecode($_POST['name']);
$file = urldecode($_POST['file']);
$db->query_write('INSERT INTO teams(name,image) VALUES ("' .
    $db->escape_string($name) . '","' . $db->escape_string($file) . '")');
if ($db->affected_rows() > 0)
{
    display('success|-|Team has been added into database.');
}
display('error|-|Something went wrong with database!');     
}

I would like to know how I can upload the logo now , I have tried to post on another php file that will upload the file but can't do two ajax posts at submit.

here is my upload code

    if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("../style/images/teams/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "../style/images/teams/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}

so how can I call two posts on ajax or remove the encodeURIComponent on file submit.

Upvotes: 0

Views: 920

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

There are few things you need to change in your code, such as:

  • Use event.preventDefault(); to prevent your form from being submitted in the first place, that way you don't need to return any false value from the function.

    $('input[type="submit"]').click(function(event){
        event.preventDefault();
        //your code
    });
    
  • If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+. You can use FormData in your code in the following way,

    // If required, change $('form')[0] accordingly
    var formdata = new FormData($('form')[0]);
    formdata.append('ajax', 1);
    formdata.append('do', 'addteam');
    

    Because in this way, you don't have to use this,

    data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + ...
    

    You can simply do this,

    data: formdata,
    
  • Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.

    contentType : false,
    processData: false,
    

So, the solution is, keep your HTML form as it is, and change your jQuery in the following way,

$(document).ready(function(){
    $('#subjectForm *').each(function(){
        if(this.type=='text' || this.type=='textarea'){
            $(this).blur(function(){
                validForm(this.form,this.name);
            });
        }
    });
    $('input[type="submit"]').click(function(event){
        event.preventDefault();
        if(validForm(this.form,'')){
            // If required, change $('form')[0] accordingly
            var formdata = new FormData($('form')[0]);
            formdata.append('ajax', 1);
            formdata.append('do', 'addteam');

            $.ajax({
                url: 'post.php',
                type: 'POST',
                data: formdata,
                contentType : false,
                processData: false,
                success: function(data) {
                    $('#notice').removeClass('error').removeClass('success');
                    var status = data.split('|-|')[0];
                    var message = data.split('|-|')[1];
                    $('#notice').html('<div>'+ message +'</div>').addClass(status);
                    $('#notice').fadeIn().animate({opacity:1}, 5000, 'linear', function(){$(this).fadeOut();});
                    $('#name').val('');
                    $('#file').val('');
                }
            });
        }
    });
    $('input[type="reset"]').click(function(){
        $('.content-box-content').find('span.input-notification').each(function(){
            $(this).remove();
        });
        $('.content-box-content *').each(function(){
            $(this).removeClass('error');
        })
    });
});

And on post.php, process your form data like this:

<?php
    if(isset($_POST['ajax']) && isset($_POST['do']) && isset($_POST['name']) && is_uploaded_file($_FILES['file']['tmp_name'])){

        // add team to the database
        if ($_POST['do'] == 'addteam'){
            $name = $_POST['name'];
            $db->query_write('INSERT INTO teams(name,image) VALUES ("' . $db->escape_string($name) . '","' . $db->escape_string($file) . '")');
            if ($db->affected_rows() > 0){

                // now upload logo
                // and when you successfully upload the logo, just do this:
                // display('success|-|Team and logo have been added into database.');


            }else{
                display('error|-|Something went wrong with database!');     
            }
        }
    }   
?>

Upvotes: 2

Related Questions