0

I've been trying to make a form and post the data in other php file through ajax. This was working fine and it was cool. The data was posted without reloading the page. But now I've added a file upload in that form and now it's not working. The error says undefined index: file . I think this is because I didn't use multipart/form-data. How can I do this without using the <form> tag ? I'm saying this because if I use <form> the page gets reloaded.

This is my code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Home | Facemash | Created by Incredible Saurav</title>

    <!-- core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet">

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function sendContact() {
    var valid;  
    valid = validateContact();
    if(valid) {
        $.ajax({
        type:"POST",
        url: "req.php",
        data:'name1='+$("#name1").val()+'&email='+$("#email").val()+'&phone='+$("#phone").val()+'&file='+$("#file").val()+'&purpose='+$("#purpose").val()+'&message='+$("#message").val(),
        success: function(data){
        $("#mail-status").html(data);
        },
        error:function (){}
        });
    }
}

function validateContact() {
    var valid = true;   
    $(".demoInputBox").css('background-color','');
    $(".info").html('');

    if(!$("#name1").val()) {
        $("#name1-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#name1").css('background-color','#FFFFDF');
        valid = false;
    }

    if(!$("#email").val()) {
        $("#email-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#email").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#email").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
        $("#email-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Invalid</a>");
        $("#email").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#phone").val()) {
        $("#phone-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#phone").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#file").val()) {
        $("#file-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#file").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#message").val()) {
        $("#message-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#message").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#purpose").val()) {
        $("#purpose-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Are you kidding me ?</a>");
        $("#purpose").css('background-color','#FFFFDF');
        valid = false;
    }

    return valid;
}
</script>
    </head><!--/head-->
<body>
    <section id="contact-page">
        <div class="container">
            <div class="row contact-wrap"> 
                                <div id="frmContact">
                                <div id="mail-status"></div>

                    <div class="col-sm-5 col-sm-offset-1">
                        <div class="form-group">
                            <label style="font-size:15px">Name</label>
                            <span id="name1-info" class="info"></span>
                            <input type="text" name="name1" id="name1" class="form-control" placeholder="Please enter your Name">
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Email</label>
                            <span id="email-info" class="info"></span>
                            <input type="email" name="email" id="email" class="form-control" placeholder="Please enter your Email">
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Phone</label>
                            <span id="phone-info" class="info"></span>
                            <input type="number" name="phone" id="phone" class="form-control" placeholder="Please enter your Phone no.">
                        </div>

                    </div>
                    <div class="col-sm-5">
                         <div class="form-group">
                            <label style="font-size:15px">Purpose</label>
                            <span id="purpose-info" class="info"></span>
                            <select type="text" name="purpose" id="purpose" class="form-control" >
                              <option value="2">To add a Picture</option>
                              <option value="0">To remove a Picture</option></select>
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Upload </label>
                            <span id="file-info" class="info"></span>
                            <input type="file" name="file" id="file" class="form-control">
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Message</label>
                            <span id="message-info" class="info"></span>
                            <textarea name="message" id="message" required="required" class="form-control" rows="2" placeholder="Please enter your message" ></textarea>
                        </div>                        
                        <div class="form-group">
                            <button type="submit" name="submit" class="btn btn-primary btn-lg" onClick="sendContact();">Submit Message</button>
                        </div>
                    </div>

                </div> 
            </div>  <!--/.row-->
        </div><!--/.container-->
    </section><!--/#contact-page-->

    <script src="js/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
    </body>
</html>

And this is my req.php file where it is posted:

<?php
 $purpose = $_REQUEST['purpose'];
 $name1 = $_REQUEST['name1'];
 $name = $_FILES['file']['name'];
 $tmp_name = $_FILES['file']['tmp_name'];
 $email = $_REQUEST['email'];
 $phone = $_REQUEST['phone'];
 $message = $_REQUEST['message'];
$data = "Name: $name1\nEmail: $email\nPhone: $phone\nPurpose: $purpose\nFilename: $name\nMessage: $message\n\n----------------------\n--------------------\n\n";

$fh = fopen("requests.txt", "a");

if(fwrite($fh,$data)==false)
{
    fclose($fh);
    echo "<p style='background-color:red;color:white;width:100%;padding:5px'>Error occurred while writing to file !</p>";
}
else
{
    fclose($fh);
        if (isset($name)) {
    if(!empty($name)) {
        $location = 'uploads/';
    if (move_uploaded_file($tmp_name, $location.$name)) {
        echo "<br><br><p style='background-color:green;color:white;width:100%;padding:5px'>Your picture was added successfully !</p>";
    }else{
        echo 'please chose a file.';
    }
    }
}
    echo "<br><br><p style='background-color:green;color:white;width:100%;padding:5px'>Your picture was added successfully !</p>";
}


?>
Divya Kumari
  • 33
  • 1
  • 5
  • You cannot just use AJAX to upload a file. To keep the page from reloading you capture the event that sends the form data and use `preventDefault()` to stop the normal action of that event. Since you're using jQuery you should get rid of any inline JS and cpature the evnts in the jQuery code where it is easier to deal with. – Jay Blanchard Jul 06 '15 at 17:13
  • It was fine till "You cannot just use AJAX to upload a file" but after what you said jumped up off my head – Divya Kumari Jul 06 '15 at 17:15
  • Have a look at [this](http://www.peachpit.com/articles/article.aspx?p=1766159). – Jay Blanchard Jul 06 '15 at 17:17
  • Can you please edit this file ad show me how can I do the same using JQuery – Divya Kumari Jul 06 '15 at 17:18
  • The link I gave you has the code needed to do what you want to do @DivyaKumari – Jay Blanchard Jul 06 '15 at 17:18
  • possible duplicate of [How can I upload files asynchronously?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – Jay Blanchard Jul 06 '15 at 17:28

1 Answers1

-1

If you're using AJAX you won't need a form, it is redundant.

Example of what you should have:

Html structure:

<div>
  <input type="text" id="name"/>
  <input type='file' accept='image/png,image/jpg,image/jpeg,image/bmp' id='image'>

  <button id="send">Send</button>
</div>

jQuery structure:

var image = null;

$(document).on('change', '#image', function(event)
{
   image = event.target.files;
});

$(document).on('click', '#send', function(event)
{
   event.stopPropagation();
   event.preventDefault();

   var data = new FormData();

   $.each(image, function (key, value) 
   {
      data.append('image', value);
   });

   data.append('name', $('#name').val());

   $.ajax(
   {
      url: yourUrl,
      type: 'POST',
      data: data,
      cache: false,
      processData: false,
      contentType: false,
      success: function(response)
      {

      }
   });
});

In PHP, you just need to print_r($_FILES) and print_r($_POST) to know which values you can access and work with.

But I can tell you right now that you'll be accessing $_FILES['image'][] since it was the name I set as ID.

Linesofcode
  • 5,327
  • 13
  • 62
  • 116
  • Why is a form redundant with AJAX? – Jay Blanchard Jul 06 '15 at 17:19
  • A form is suppose to redirect you to somewhere, which you don't want to. Therefore, using a form in this situation won't give you any better results. – Linesofcode Jul 06 '15 at 17:22
  • But you're using form elements? Without a form tag the HTML would be invalid. – Jay Blanchard Jul 06 '15 at 17:23
  • In the jQuery? Yes, that's why it's redundant. But in this situation, it won't redirect you to anywhere. The `formData` is only needed because you're sending images, otherwise you could just send an array of objects. – Linesofcode Jul 06 '15 at 17:24
  • So, it *is* invalid HTML? – Jay Blanchard Jul 06 '15 at 17:25
  • No, it's not invalid just because I'm not using a form tag. You don't need form tags to send values from HTML to PHP. You can access to that values no matter if you have a form attached or not. – Linesofcode Jul 06 '15 at 17:28
  • I understand that - but the HTML will not validate without the form tags if you're using input tags. – Jay Blanchard Jul 06 '15 at 17:28
  • The HTML will not validate? What do you mean by that? – Linesofcode Jul 06 '15 at 17:29
  • Oh I see what you're meaning. It won't indeed. You'll have to checkout the response from `success function()` – Linesofcode Jul 06 '15 at 17:30
  • There is valid HTML and invalid HTML. Input tags not inside of form tags will be invalid HTML. – Jay Blanchard Jul 06 '15 at 17:30
  • Just because you don't put input tags inside form elements will decrease any performance or reliability of your website. But feel free to implement that as form. – Linesofcode Jul 06 '15 at 17:35
  • We have accessibility requirements that cause us to have to validate our HTML. You really shouldn't be teaching bad habits just because they work for you. There are a myriad of reason for making sure you create valid HTML. – Jay Blanchard Jul 06 '15 at 17:38