There is a form with input

<form> <input type="text" name="name" value="Имя публикации" /> </form> 

Using jQuery I get data

 inputs = $("form").serialize().split('&'); 

At the exit I get

 ["name=%D0%98%D0%BC%D1%8F+%D0%BF%D1%83%D0%B1%D0%BB%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D0%B8"] 

How to bring the line to normal? If you use decodeURI, then spaces are replaced by pluses.

I need to send the form Ajax with data and files

 function getData(form) { /* get data from form */ var data = new FormData() inputs = form.serialize().split('&'); inputs.forEach(function(item, i, arr) { var tmp = item.split('='); data.append(tmp[0],decodeURIComponent(tmp[1].replace(/\+/g, ' '))); }); /* get files */ form.find("input[type='file']").each(function(){ var key = $(this).attr('name'); var file = $(this).prop('files')[0]; if (file !== 'undefined') { data.append(key, file); } }); return data; } 
  • decodeURIComponent(t).replace(/\+/g, ' ') ? - user207618
  • @Other Thank you. Works) - Oxel Net
  • And why do you get them so much? - Sergey Gornostaev
  • @Other I need to send an Ajax form with the data. Well, I collect data. - Oxel Net
  • Then why these additional actions with breaking on ampersand and decoding? Just do $.post($(form).attr('action'), $(form).serialize(), successCallback) . - Sergey Gornostaev

1 answer 1

Recently, I also encountered the problem of AJAX sending a form with files. Honestly, I could not get jQuery to do this. But there was no problem with the vanilla version:

 $('#job-form').submit(function(event) { if(window.FormData !== undefined) { event.preventDefault(); var form = this; $(form).find('.form-group').removeClass('has-error'); var formData = new FormData(form); var xhr = new XMLHttpRequest(); xhr.open('POST', $(form).attr('action'), true); xhr.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest'); xhr.onreadystatechange = function() { if(xhr.readyState == 4) { if(xhr.status == 200) { result = JSON.parse(xhr.responseText); if(result.status == 'ok') { form.reset(); showModal(result.info); } else if(result.status == 'error') { for(var ndx in result.info) { var holder = $(form).find('[name=' + result.info[ndx].key + ']').closest('.form-group'); holder.addClass('has-error'); if(result.info[ndx].key == '__all__') { showModal(result.info[ndx].desc, 'Ошибка'); } } } } else { showModal('Ошибка отправки формы. Попробуйте повторить попытку позже.', 'Ошибка'); } } }; xhr.send(formData); } });