strange behaviour - serialize - javascript

i have this code:
var sizes = ["1/9","1/8","1/7","1/6","1/5","1/4","1/3","1/2","1/1","2/1","3/1","4/1","5/1","6/1","7/1","8/1","9/1"];
var slider = new dijit.form.HorizontalSlider({
value:8,
name:"value"+[i],
slideDuration:0,
onChange:function(val){
dojo.byId('value'+[i]).value = sizes[val];
},
minimum:0,
maximum:sizes.length-1,
discreteValues:sizes.length,
intermediateChanges:"true",
},node);
now, when i made:
$("#custom").submit(function() {
var formdata = $("#custom").serializeArray();
$.ajax({
url: "insert.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data) {
}
});
For example, if i choose the value 1/8 it is sent as 1, or 9/1 as 16.
What i want is send the fraction value, that is showed in the input box, but as i said, not sent to the insert.php
Any idea ? thanks

At the beginning during the init of the slider an <input type="hidden" name="input0" ... /> will be created.
After using the slider this input get the current slider value (a number between 0 and sizes.length - 1). The onChange sets an other html input tag with the value from the array called sizes.
While submitting the serializeArray() takes the values of all input fields which have a name attribute.
In my EXAMPLE I gave the input field that will be filled at the onChange a name attribute, so the serialization takes both values.
HTML:
<form action="#" id="custom">
<div id="slider0"></div>
<input type="text" id="value0" data-dojo-type="dijit.form.TextBox" name="value0" />
<input type="submit" value="submit" />
</form>

Related

Prevent redirecting after post

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me.
There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former.
So, the code:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
There is my JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.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(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere.
I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.
The trick to prevent form submission is return false onsubmit as below:
<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data">
<!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" />
<br>
<label id="nameerror"></label>
<br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" />
<br>
<label id="emailerror"></label>
<br> Select a file
<br />
<label id="draganddroperror"></label>
<br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple />
<br />
<button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button>
</form>
Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val()) {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.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(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
}
});
} else {
alert("Please select file!");
}
return false;
}
I hope this gives you the clear understanding.
You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.
var submitButton = document.getElementById('btnSubmit');
submitButton.addEventListener('click', sendData);
// Then you will have access to the event in the sendData function
function sendData(ev) {
ev.preventDefault();
...
}
Live example
A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.
var form = document.getElementById('form');
form.addEventListener('submit', sendData);
Live example
In function sendData() you should pass event param like this
function sendData(evt) {
}
and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.
Add type attribute with the value of button and you are done:
<button id="btnSubmit" type="button" ...
By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

Change Dynamic field of Typeahead

I'm programming a form with dynamic typeaheads fields, and i have found a problem when i want to show and select the suggestions.
I have two first fields, a input select and a input typeahead. When a option is selected, it's load a list of values in the input typeahead. The problem comes when i create(dynamically) a clone of this pair of fields and i want to get de list of values in the correct typeahead.
I get the id of the field (idTypeAhead) when i focus in the field and i use it in the typeahead.
This is the code:
//TYPEAHEAD
$('input.typeahead').focus(function(){
idTypeAhead = parseInt($(this).attr('id').replace('typeAhead_',''));
selectAttr = $('select#selectAttr_'+idTypeAhead).find('option:selected').val();
if(selectAttr=="null"){
selectAttr=0;
}
});
$("input#typeAhead_"+idTypeAhead).on("typeahead:select").typeahead({
name:'input#typeAhead_'+idTypeAhead,
displayKey: 'input#typeAhead_'+idTypeAhead,
input: 'input#typeAhead_'+idTypeAhead,
container:'input#typeAhead_'+idTypeAhead,
display: $(this),
suggestion: $(this),
minLength : 1,
sorter : this.query,
source : function(query, process){
return $.ajax({
url:'/aplicaciones/jsonValorAttr?selectAttr='+selectAttr,
dataType: 'json',
type:'POST',
success: function(data){
states = [];
map = {};
$.each(data, function (i, state) {
map[state] = state;
states.push(state);
});
process(states);
}
});
}
});
I have this code in form (i use Spring STS). Also i have two buttons "+" and "-". When i click "+", i clone this two fields and increase de id number of each element. When i click "-", i remove a pair of fields. (example: selectAttr_101 ->newclone: selectAttr_102).
<div class="controls">
<form:select path="rolHerramientaID" id="selectAttr_101" cssClass="field-required lstAtributos" cssErrorClass="select-error">
<form:option value="null" selected=""><spring:message code="altaAplicacion.form.seleccionar" />
</form:option>
<c:forEach var="selectAtributos" items="${resultAtributos}" varStatus="rowCount">
<form:option value="${selectAtributos.atributosId}">${selectAtributos.nombreAtributo}</form:option>
</c:forEach>
</form:select>
<form:errors path="rolHerramientaID" class="help-block" /></div>
</div>
<div class="control-group required">
<label for="input01" class="control-label"><spring:message code="altaAplicacion.form.valor" /></label>
<div class="controls">
<input id="typeAhead_101" class="input-medium typeahead" type="text" data-provide="typeahead" autocomplete="on">
</div>
How can i change the container of the typeahead dynamically?
I've been searching for the solution for this problem and found your post, with some small changes that worked for me.
I've stated the fixed input field in the form as typeAheadId_1 and created a function before create the typeahead object to manipulate the typeahead index.
on the insert operation, I increase the counter and destroy the typeahead object before each dynamic fields wrapping and recreate the typeahead object
(passing the counter) after the fields creation.
For edition (some dynamic fields are created direct in the form), I've created a REST service to return how many fields were wrapped and start counting from this.
It worked perfect for me.
If you didn´t solve or need some help, please let me know!
Following codes are working for me -
var typeaheadSettings = {
source: function (query, result) {
$.ajax({
url: "{{url('/work-order/get_parts_suggestion')}}",
data: 'txt=' + query,
dataType: "json",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
};
$('.typeahead').typeahead(typeaheadSettings); /* init first input */
$('.typeahead').on('added',function(){
$('.typeahead').typeahead(typeaheadSettings);
});
add this line after appending/creating dynamic element -
$('.typeahead').trigger('added');
Reference - https://www.bootply.com/61431

submit event not capturing submit type input

I have a Ajax GET request as mentioned below
$(document).ready(function() {
$('#comment-edit-form').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: '/comments/edit/' + $(this).attr('comment_pk') + '/',
data: $(this).serialize(),
success: function(data){}
});
return false;
});
});
The form is something like this
<form method="get" id="comment-edit-form">
..
<input class="btn btn-primary" type="submit" name="preview" value="Preview">
<input class="btn btn-primary" type="submit" name="submit" value="Submit">
</form>
In this form, I have two different submit buttons! each has different operation!
The GET request URL I traced is something like below
?input1=1&input2=2...
I am expecting ?input1=1&input2=2&submit=
or ?input1=1&input2=2&preview=
Why I am not able to observe "submit" or "preview" names in the request??
This is because jQuery only serializes the nodeTypes input, select, textarea and keygen with input types that are not submit,button, image, file or reset.
Looking at the jQuery source code, you can tell that form elements' input type is checked against the following regular expression:
/^(?:submit|button|image|reset|file)$/i
This check is in .serializeArray which is called by .serialize in your code.
For the interested reader - this is the complete filter:
return this.name && // has a name
!jQuery(this).is(":disabled") && // is not a disabled input
rsubmittable.test(this.nodeName) && // is either input, select,textarea or keygen
!rsubmitterTypes.test(type) && // the test explained above
(this.checked || !manipulation_rcheckableType.test(type)); // checked

Looping through an ajax script to process forms on a page

I have a page with lots of small one line forms, each of which has 5 items. The forms have the id form1, form2, form3, etc, and the id of the items and the submit button follows the same pattern. I have written out the following ajax script for processing the forms one at a time, where the variable $n corresponds to the form and item number. What I am not sure about is how to loop through this script for each form on the page. Do I need to somehow count the number of forms on the page first and then create a loop, and if so how do I do this?
$(".submit$n").click(function() {
var action = $("#form$n").attr('action');
var form_data = {
name: $j("#name$n").val(),
date: $j("#date$n").val(),
attended: $j("#attended$n").val(),
paid: $j("#paid$n").val(),
method: $j("#method$n").val(),
is_ajax: 1
};
$j.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success')
$j("#form$n").fadeOut(800);
console.log(response);
}
});
return false;
});
});
I'm sorry but I don't think this is being set up correctly, and neither is the accepted answer...it's just very messy. I'm not sure if your original code is replicated for every form you have (because the whole $n variable thing confuses me and makes me think you have it several times), but it isn't needed if so. Here's what I would use:
$(document).ready(function () {
$(".submit").click(function () {
var $this = $(this);
var $form = $this.closest("form");
var action = $form.attr('action');
var form_data = {
name: $form.find("[id^=name]").val(),
date: $form.find("[id^=date]").val(),
attended: $form.find("[id^=attended]").val(),
paid: $form.find("[id^=paid]").val(),
method: $form.find("[id^=method]").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function (response) {
if (response == 'success') {
$form.fadeOut(800);
}
console.log(response);
}
});
return false;
});
});
Just give all the submit buttons a class of "submit", and this should work fine. Just to make sure, your HTML would have the format of this:
<form id="form1" action="page1.php">
<input type="text" id="name1" name="name1" /><br />
<input type="text" id="date1" name="date1" /><br />
<input type="text" id="attended1" name="attended1" /><br />
<input type="text" id="paid1" name="paid1" /><br />
<input type="text" id="method1" name="method1" /><br />
<input type="submit" class="submit" value="Submit" />
</form>
Just so you understand what's happening, the Javascript finds the submit button's parent form when it's clicked. Then, with that form, it finds all descendents that have an id attribute that starts with "name", "date", etc. You can do this because you have clearly separated controls into their own forms. So with this code, you can be assured that when you click a submit button, you're grabbing all of the controls' values from the form that it's in.
Add a common class to all your submit buttons, like: <input type="submit" id="submit1" name="submit1" class="submit" />
And then change your code to:
$('.submit').on('click', function() {
var n = this.id.substr(6);
// n is the number of the form. 6 because the word submit has 6 characters.
// You might want to do this some other way.
// you can get the rest of the values by doing
$('#name' + n).val()
// and so on
});

Get value of each on blur() event

I have a page which contain a bunch of text area generated by a PHP script. There is a hidden input type that contains an id of a variable. Basically what I want to do is to call the .ajax() JQuery method on .blur() on any of the text areas and pass the value of the textarea + the id from the hidden input.
All of my text areas are named like this: tr1,tr2,tr3,etc. And the hidden fields:tr_id1,tr_id2,etc
So how can I get the value from both elements so I can use them somewhere else?
This may give you an idea
HTML
<textarea name="tr1"></textarea>
<input type="hidden" name="tr_id1" value="1" />
<br />
<textarea name="tr2"></textarea>
<input type="hidden" name="tr_id2" value="2"/>
​
JS
​$(function(){
$('textarea').on('blur', function(e){
var txtAval=$(this).val();
var txtId=$(this).prop('name').replace('tr','');
var txtHval=$('input:hidden[name="tr_id'+txtId+'"]').val();
// txtAval contains textarea's value and txtHval contains text input's value
$.ajax({
type: "POST",
url: "some_url",
data: {txtarea:txtAval, txthidden:txtId}
//or
//data: "txtarea="+txtAval+"&txthidden="+txtId
}).done(function(msg) {
// ...
});
});
});​
jQuery ajax reference: Here.
See the values on the console here.

Categories

Resources