How to rewrite Ajax code from jQuery to JS - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Friday, March 31, 2023

How to rewrite Ajax code from jQuery to JS

I have WORKING code on jquery, which is sending the name of the file to php. And then the code is uploading that file to the folder using php and displaying it in html.

so now i need to do it not with jquery, but with javascript

i have it using js, but the code isnt working

Ajax using js (Not Working)

const fldrnmn=document.querySelectorAll('.fldrnmn')
fldrnmn.onchange=(e)=> {
  var file = new FormData();
  var fldr = e.target.getAttribute('data-fldr');
  // alert(fldr)
  file.append('file', e.target.files[0]);
  file.append('bubu', fldr);
  $.ajax({
    url: 'all.php',
    data: file,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function (res) {
      e.target.closest('.bord').innerHTML = `<img src='assets/img/${fldr}/${res}' width='100%'>`;
      e.target.closest('.lci').value = res;
    }
  })
}

Ajax using jquery (working)

$('.fldrnmn').change(function () {
  var file = new FormData();
  var fldr = $(this).attr('data-fldr');
  // alert(fldr)
  file.append('file', $(this)[0].files[0]);
  file.append('bubu', fldr);
  $.ajax({
    url: 'all.php',
    data: file,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function (res) {
      $('.bord').html(`<img src='assets/img/${fldr}/${res}' width='100%'>`)
      $('.lci').val(res);
    }
  })
})

all.php

if(isset($_FILES['file'])) {    
    $pr_fileName = $_FILES['file']['name'];
    $pr_fileTMP = $_FILES['file']['tmp_name'];
    $fldr = $conn -> real_escape_string($_POST['bubu']);
    $cut = explode('.', $pr_fileName);
    $loc = 'assets/img/'.$fldr.'/'.$pr_fileName;
    if(end($cut)=='jpg'||end($cut)=='jpeg'||end($cut)=='png'){
        move_uploaded_file($pr_fileTMP, $loc);
        echo $pr_fileName;
        
    }
}

part of HTML

      <td>
          <button class="delete" data-table="header" id="43">delete</button>
          <input type="file" name="header-image" data-fldr="slide" class="form-control fldrnmn  image-header">
          <input type="hidden" name="header-img" value="" class="lci" placeholder="image name">
          <input type="hidden" name="id" value="43">
          <div class="col-8  dddd bord "></div>
      </td>

P.S.

  1. the problem is in js, do not advise solutions with changing the code in other parts of the code
  2. html uses a lot of 'bord', 'lci', 'fldrnmn' classes, thats why i am using querySelectorAll


source https://stackoverflow.com/questions/75891563/how-to-rewrite-ajax-code-from-jquery-to-js

No comments:

Post a Comment