I want to send a file in a JSON using an AJAX without using formData, is it possible?

1

I have a form that I sent with an ajax. I extract the data with jquery and I put them in prototype to send them in ajax with a dataType: 'json'. Come on normal.

	 var datos = {
	 	nombre : $('#nombre').val()
	 }
	$.ajax({
		url: '../js/file.php',
		type: 'post',
		dataType: 'json',
		data: dato,
	})
	.complete(function() {
		console.log("success");
	})
<form action="" method="get" accept-charset="utf-8">
	<input type="text" id="nombre">
	<button type="submit">enviar</button>
</form>

But now I want to send a file in the form but using the same prototype and I do so

 var datos = {
	 	nombre : $('#nombre').val(),
	 	foto :  $('#foto').prop('files')[0],

	 }

now at the time of sending the ajax gives me this error

  

jquery-3.2.1.min.js: 4 Uncaught TypeError: Illegal invocation

Now I understand that I have to convert the files into binary so they can be sent to the server and that's why the form data object is used. My question is if at this point there is no other method? well I understand that form data is XMLHttpRequest technology. Thanks

    
asked by Sr. K 18.01.2018 в 17:26
source

1 answer

0

Using JSON

Well, I did it by transforming the file into Base64 and sending it as string

For example :

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

And your json would be more or less like this:

"data:text/plain;base64,aG9sYQ==" 

The configuration I use is the following:

The form that has enctype="multipart/form-data" and preferably that is in POST so that nothing unusual happens, being:

<form action="" method="post" enctype="multipart/form-data">
    <input type="text" id="nombre">
    <button type="submit">enviar</button>
</form>

Removed accept-charset="utf-8" I do not know if it affects, but you can do your tests and tell us.

And in our javascript code

        $('#nuestroForm').on('submit',(function(e) {
            e.preventDefault(); //importante 
            var formData = new FormData(this);

            $.ajax({
                type:'POST',
                url: 'nuestra url',
                data:formData,
                cache:false,
                contentType: false,
                processData: false,
                success:function(data){
                    console.log("success");
                    console.log(data);
                },
                error: function(data){
                    console.log("error");
                    console.log(data);                      
                }
            });
        }));

See that I do not have dataType: 'json' and that's how it works.

ajax documentation in jQuery

  

processData (default: true)

     

Type: Boolean By default, data passed in

     

to the data option as an object (technically, anything other than a   string) will be processed and transformed into a query string, fitting   to the default content-type "application / x-www-form-urlencoded". If   you want to send to DOMDocument, or other non-processed data, set this   option to false.

     

contentType (default: 'application / x-www-form-urlencoded;   charset = UTF-8 ')

     

Type: Boolean or String

     

When sending data to the   server, use this content type. Default is   "application / x-www-form-urlencoded; charset = UTF-8", which is fine for   most cases. If you explicitly pass in to content-type to $ .ajax (), then   it is always sent to the server (even if no data is sent). As of   jQuery 1.6 you can pass false to tell jQuery to not set any content   type header Note: The W3C XMLHttpRequest specification dictates that   the charset is always UTF-8; specifying another charset will not force   the browser to change the encoding. Note: For cross-domain requests,   setting the content type to anything other than   application / x-www-form-urlencoded, multipart / form-data, or text / plain   will trigger the browser to send a preflight OPTIONS request to the   server.

    
answered by 18.01.2018 / 17:57
source