I have the following AJAX function with JQuery:
var formData = $('#FonykerEditForm').serialize();
$.ajax ({
type: 'POST',
url: '<?php echo $html->url('/fonykers/edit',true); ?>',
data: formData,
dataType: 'json',
success: function(response) {
message.html(response.msg);
message.fadeIn();
if(!response.ok) {
message.removeClass('success');
message.addClass('error');
} else {
message.removeClass('error');
message.addClass('success');
username = $('#FonykerUsername').val();
email = $('#FonykerEmail').val();
}
$('#save-account-button').removeAttr('disabled');
$('.input-text').removeClass('ok');
$('.input-combo').removeClass('ok');
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
$('#save-account-button').removeAttr('disabled');
}
});
The problem I'm having is that a type file field in my form is not getting submitted along with the rest of the data of the form, how can I include the file in the data of the ajax request?
I tried this link and this works fine for me.
http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
Example:
$( '#my-form' ).submit( function( e ) {
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );
Like I said in the comment above, sending files via ajax is not straightforward. If you wish to try it anyway. The normal approach I've seen is to create a new iframe, add a file input field to it, select your file and submit it programmatically. This way, the iframe does the submission in the background.
Take a look at how this plugin does it:
https://github.com/valums/file-uploader/blob/master/client/fileuploader.js#L995
https://github.com/FineUploader/fine-uploader
Basically an AJAX will submit data in the form of key/value pairs.. Since files are binary data, you can't submit files using Ajax.. You'll need to submit the data using a standard form submit instead and on the server since accept a form/multipart
Related
To give you a better understanding consider my ajax request:
$.ajax({
url: '{% url "validate-upload-single" %}',
type: "POST",
data: JSON.stringify({
'mainForm': Myform,
'currentForm': 1,
}),
dataType: 'json', // response type
Where:
var Myform = new FormData( $(this)[0] );
The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend
DJANGO VIEW:
print('SORTING THE POST REQUEST')
body = request.body.decode('utf-8')
serialized = loads(body)
print(f'POST: {request.POST}')
print(f'Body: {body}')
print(f'Serialized: {serialized}')
RESULT:
SORTING THE POST REQUEST
POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}>
Body: {"mainForm":{},"currentForm":1}
Serialized: {'mainForm': {}, 'currentForm': 1}
I've tried $("form").serializeArray() but this only return text data, files seem to be missing
I guess the problem is with contentType header - it should be 'multipart/form-data'. Check this link to make it work with jQuery.ajax
In the .js file you HAVE TO add the fist block of csrf token for properly working.
//Getting csrf token
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Then you use json in you ajax, getting the template that you want to display by variable here "html_form":
// Submit post on submit
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
//Send data to server for getting back sorted
$.ajax({
url: '/schedule/sort_group/',
async: true,
type: 'post',
data: { //data sent with the post request
group_field_value: $("#select_group").children("#group-option:selected").val(),
lector_field_value: $("#select_lector").children("#lector-option:selected").attr("name"),
},
dataType: 'json',
success: function (data) {
$("#change_by_select").html(data.html_form);
}
});
});
In the views.py file at the bottom you need to determine the data like that:
data['html_form'] = render_to_string('schedule/select_sort.html', context,
request=request)
return JsonResponse(data)
So I suggest the information that you want to retrieve from the server put into the particular another file, whatever it would be (dictionary or lists or other data structures or html templates).
I hope it would help. Feel free to ask any questions.
I have always used query ajax request to something simple like preventdefault form submit and adding beforesend function or complete function after the form is submitted like this to my nodejs backend:
$.ajax({
type: "POST",
url: "/contact",
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
setTimeout(function(){
console.log('Here')
$(".loading_msg").fadeOut("slow");
$("#message").val("")
},3000)
}
});
Now, I have a sitution where I have to submit only part of the form input elements. There are also input elements inside the form which is dynamically generated.
Is there a way for me to send only input boxes with id's or classes that I want rather than the entire form?
If you want to send some particular data to your server, you can config the data by yourself like the following:
$.ajax({
type: "POST",
url: "/contact",
data: {
myKey1: $("#myKey1").val(),
myKey2: $("#myKey2").val()
},
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
setTimeout(function(){
console.log('Here')
$(".loading_msg").fadeOut("slow");
$("#message").val("")
},3000)
}
});
I'm trying to send multiple data from client to server using ajax json.
case First: when i send my form inputs data from client to server it was going well.
case second:now one modification done in my form and i am generating dynamic multiple rows with textboxes .and it's values should also pass using same ajax method but my try go in vain so any idea would be appreciated.
Refer below article for more coding part details about this question.
enter link description here
I am trying like this
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var fields = $("#WireDimTbl tbody").find(":input").serializeArray();
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
user.REVISION = $("#Revision").text();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: JSON.stringify({ user: user,fields:fields}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Data has been added successfully.");
window.location.reload();
},
error: function (response) { alert(response.responseText); }
});
return false;
});
At Sever side part what modification should be done.how would i define parameter object with same strucutre at server side and how would i store in db.
I want to use form validation methods of CI for validating my input data. As the form submitted via AJAX I'm using serializeArray() to post data to my controller so I don't have to post on by one data or wrinting some each() function. The problem is that form validation look for data in $_POST. Using serialize() didn't help neither. Is there any solution beside extending form validation library?
here my code:
(controller)
$form_data = $this->input->post('form_data');
$this->load->library('form_validation');
$this->form_validation->set_rules('p_company_name', 'نام شرکت', 'required');
if ($this->form_validation->run() == FALSE)
{
echo "fail";die(); // if i use serialize() or serializeArray()
}
else
{
echo "success";die(); // if i use label:value for each form input
}
js code:
$.ajax({
type: "POST",
cache: false,
url: url,
data: {'form_data': form_data},
dataType: "html",
success: function(res, textStatus, xhr)
{
// do something
},
error: function(xhr, textStatus, thrownError)
{
//do something else
},
complete: function()
{
// do some final thing
},
async: true
});
Thanks in advance
post your data as:
data: form.serialize(),
and it will work as normal (form being a normal jquery reference to your page form, not just the word "form")
I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.
Here is what I have now:
<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" />
<div id=created></div>
What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.
I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).
This code should do it. You don't need the Form plugin for something as simple as this:
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
This works also for file upload
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
$('#created').html(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
You must use AJAX to post the form if you don't want the page to be refreshed.
$('#create').submit(function () {
$.post('create.php', $('#create').serialize(), function (data, textStatus) {
$('#created').append(data);
});
return false;
});