Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

upload file using ajax

// add jquery
// <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
$(document).ready(function() {
  $("#form").on('submit', (function(e) {
    e.preventDefault();
    $.ajax({
      url: $(this).attr('action'),
      type: "POST",
      data: new FormData(this),
      contentType: false,
      cache: false,
      processData: false,
      success: function(response) {
        $("#form").trigger("reset"); // to reset form input fields
      },
      error: function(e) {
        console.log(e);
      }
    });
  }));
});
Comment

file upload in php through ajax

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'upload.php', // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });
});
Comment

file upload in php through ajax

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}
Comment

file upload in php through ajax

var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
    url: "upload.php",
    type: "POST",
    data : formData,
    processData: false,
    contentType: false,
    beforeSend: function() {

    },
    success: function(data){




    },
    error: function(xhr, ajaxOptions, thrownError) {
       console.log(thrownError + "
" + xhr.statusText + "
" + xhr.responseText);
    }
});
Comment

ajax file upload input

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Uploads With AJAX</title>
</head>
<body>
    <form id="file-form" action="fileUpload.php" method="post" enctype="multipart/form-data">
        Upload a File:
        <input type="file" id="myfile" name="myfile">
        <input type="submit" id="submit" name="submit" value="Upload File Now" >
    </form>

    <p id="status"></p>
    <script type="text/javascript" src="fileUpload.js"></script>
</body>
</html>

Code language: HTML, XML (xml)
Comment

file upload in php through ajax

<?
$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

        $uploaddir = $target_dir;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
                $files[] = $uploaddir . $file['name'];
            } else {
                $error = true;
            }
        }
        $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    } else {
        $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
    }

    echo json_encode($data);
?>
Comment

file upload in php through ajax

async function saveFile() 
{
    let formData = new FormData();           
    formData.append("file", sortpicture.files[0]);
    await fetch('/uploads', {method: "POST", body: formData});    
    alert('works');
}
Comment

file upload in php through ajax

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }

?>
Comment

file upload in php through ajax

move_uploaded_file(

    // this is where the file is temporarily stored on the server when uploaded
    // do not change this
    $_FILES['file']['tmp_name'],

    // this is where you want to put the file and what you want to name it
    // in this case we are putting in a directory called "uploads"
    // and giving it the original filename
    'uploads/' . $_FILES['file']['name']
);
Comment

ajax file upload

$(function() {
    // Configure Cloudinary
    // with the credentials on
    // your Cloudinary dashboard
    $.cloudinary.config({ cloud_name: 'YOUR_CLOUD_NAME', api_key: 'YOUR_API_KEY'});
    // Upload button
    var uploadButton = $('#submit');
    // Upload-button event
    uploadButton.on('click', function(e){
        // Initiate upload
        cloudinary.openUploadWidget({ cloud_name: 'YOUR_CLOUD_NAME', upload_preset: 'YOUR_UPLOAD_PRESET', tags: ['cgal']}, 
        function(error, result) { 
            if(error) console.log(error);
            // If NO error, log image data to console
            var id = result[0].public_id;
            console.log(processImage(id));
        });
    });
})
function processImage(id) {
    var options = {
        client_hints: true,
    };
    return '<img src="'+ $.cloudinary.url(id, options) +'" style="width: 100%; height: auto"/>';
}
Code language: JavaScript (javascript)
Comment

PREVIOUS NEXT
Code Example
Javascript :: kendo dropdownlist value jquery 
Javascript :: how to disable right click in javascript 
Javascript :: convert stream to string javascript 
Javascript :: input in node js 
Javascript :: javascript detect click outside element 
Javascript :: instalar react native paper 
Javascript :: find item in object js 
Javascript :: js id style backgroundColor change 
Javascript :: javascript add div before element 
Javascript :: javascript push item to beginning of array 
Javascript :: groupby javascript by instances 
Javascript :: javacript open url in new tab 
Javascript :: discord.js get attachment url 
Javascript :: how to create a screen recorder using javascript only 
Javascript :: tailwind css calc 
Javascript :: how to get domain name in react 
Javascript :: sqlite3 multithreading nodejs 
Javascript :: data-dismiss= modal in jquery 
Javascript :: increment day date javascript 
Javascript :: jquery select by name attribute 
Javascript :: check if string is valid json dart 
Javascript :: get current url angular 
Javascript :: javascript max length with elipsis 
Javascript :: neffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory 
Javascript :: javascript loop through object values 
Javascript :: usehistory 
Javascript :: javascript select all table rows 
Javascript :: how to find text in jquery with find function 
Javascript :: electron quit app from renderer 
Javascript :: express js basic example 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =