jquery form submits twice - forms

I've created a form submit with ajax, but it submits twice???
Is there anyone who knows whats going wrong?
This is my code:
var form = $('#myForm'); // contact form
var submit = $('#offertesturen'); // submit button
var alert = $('.alert'); // alert div for show alert message
$('#myForm')
.on('invalid.fndtn.abide', function () {
var invalid_fields = $(this).find('[data-invalid]');
console.log(invalid_fields);
})
.on('valid.fndtn.abide', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'send_form_email.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('.....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Aanvragen!'); // reset submit button text
$(document).scrollTop(0);
$('#secondModal').foundation('reveal', 'open');
},
error: function(e) {
console.log(e)
}
});
});

Related

Store the user searchword in mysql

I working on a little snippet, a live search with MySQL.
Now i think it could be nice to store/save which searchword the user, did the search on.
Example:
User search on
My new book
Then i want to store that to my databse.
The problem is with my script right now, where i trig the ajax on keyup. Then it will store.
M My My N My Ne My New .... and so on..
and so on, how can i come around this and only store the hole line ..?
$(function() {
$("#searchword").keyup(function(){
var text = $(this).val();
if (text != ' ') {
$('#result').html(" ");
$.ajax({
type: 'post',
url: 'livesearch.php',
data: { 'search': text },
success: function(dataReturn) {
$('#result').html(dataReturn);
}
});
}
});
});
I've created a storeText(txt,time) function that will take your text as first param and time to wait before sending ajax as second param. You can change the second parameter as per your need. Add your ajax call in the function below my comment and you're good to go.
$(function() {
$("#searchword").keyup(function(){
var text = $(this).val();
if (text != ' ') {
//THIS IS WHERE YOU CAN MODIFY THE TIME
storeText(text,1000);
$('#result').html(" ");
$.ajax({
type: 'post',
url: 'livesearch.php',
data: { 'search': text },
success: function(dataReturn) {
$('#result').html(dataReturn);
}
});
}
});
});
var timer;
function storeText(txt,time){
clearTimeout(timer);
timer = setTimeout(function(){
//ADD YOUR SAVE QUERY AJAX HERE
},time);
}
Here's a JSFiddle to see it in action: https://jsfiddle.net/3n2L2v6g/
Try typing anything in the text box, it waits 1000ms before executing the code where your ajax would be.

Extjs4 form item is lost after submit

I have grid in Extjs4 in which I created filefield item.
In my controller I am creating a new form and taking filefield from the grid and giving it to new form as item. After submitting the form I see that filefield is removed from its place, where has it gone?
Here is my code to submit the form:
var me = this;
var fileform = Ext.create("Ext.form.Panel", {
items: [{
xtype: filefield
}]
});
if(fileform.getForm().isValid()){
fileform.getForm().submit({
url: Server.getUrl("test", "upload"),
success: ...
failure: ...
});
}
else
Message

Delete form data for subsequent ajax calls

I have a link that opens a dialog modal asking for a date. When they click submit, javascript takes the form data, generates an ajax call, and returns the response. This works no problem. However if I immediately click the same link again and submit a new date in the form, I get the results from my first ajax POST.
Essentially, subsequent ajax calls are using the original POST data and nothing new. Code has alerts for troubleshooting. Im assuming im setting some var thats not getting reset, but thought this event handler was canceled with the "off", then re-added immediately after and the vars would be in scope to that function alone.
<script>
//Modal submit
$(document).off('click', '#SubmitAllChecks');
$(document).on('click', '#SubmitAllChecks', function(e) {
e.preventDefault();
var form = $('#AllChecks');
var url = form.attr('action');
var method = form.attr('method');
var data = form.serializeArray();
$.each(data, function(k,v) {
alert(v.name + ' : ' + v.value);
});
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
beforeSend: function() {
//add load indicator
window.erpui.startload();
},
success: function(data) {
alert('xhr complete');
$.each(data, function() {
alert(this.value + ' data');
if (this.value == 'error' && this.msg != '') {
window.erpui.endload();
window.erpui.notify.error(this.msg);
window.erpui.notify.commit();
}
else if (this.value == 'success') {
window.erpui.endload();
window.erpui.notify.success(this.msg);
window.erpui.notify.commit();
$('.ui-dialog').remove();
//window.location.href="{% url all_checks %}";
//window.location.reload();
}
});
},
error: function() {
alert('error');
//remove load indicator
window.erpui.endload();
}
});
});
</script>

Select2 with AJAX and Initial Local Data

So I'm trying to get the select2 plugin to work with a Backbone.js / CakePHP app. The idea is that this select2 holds email addresses for contacting people as tasks become completed, but the form is editable. What I want to do is (1) load / display all the already saved email addresses for the task being edited, and (2) I want to still have the select2 perform AJAX searches to list recognized emails.
I keep having this issue where I can either show initial data, OR have the AJAX search feature.
My current code for my select2 box is a Backbone.View, and it looks like:
define([
'backbone',
'jquery',
'jquery.select2'
],
function(Backbone, $, select2) {
var notificationSelector = Backbone.View.extend({
notifications: undefined,
events: {
'change' : 'select2ContactsChanged'
},
initialize: function(attrs) {
this.collection.on('add remove reset', this.render(), this);
this.select2ContactsChanged();
},
render: function() {
var contacts = ["abc#def.com", "joe#banana.com"];
$('.notification-selector').attr('value', contacts);
if(this.select2Control == undefined)
{
// Do Search() + query here
this.select2Control = this.$el.select2({
width: '200px',
placeholder: '#email',
tags: [],
minimumInputLength: 3,
// initSelection: function(element, callback) {
// return $.ajax({
// type: "GET",
// url: "/notifications/fetch/",
// dataType: 'json',
// data: { id: (element.val()) },
// success: function(data) {
// }
// }).done(function(data) {
// console.log(data);
// });
// },
});
}
else
{
// Do Search() + query here
this.select2Control = this.$el.select2({
width: '200px',
placeholder: '#email',
tags: [],
minimumInputLength: 3,
ajax: {
url: '/notifications/search/',
dataType: 'json',
data: function(term, page) {
return {
SearchTerm: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});
}
},
select2ContactsChanged: function() {
var contacts = this.select2Control.val().split(',');
this.collection.reset(contacts);
}
});
return notificationSelector;
});
I read a response by the creator of Select2 to someone else (https://github.com/ivaynberg/select2/issues/392) in which he says to use a 'custom query' to achieve what seems to be what I want. I'm having trouble finding relevant examples or making enough sense of the docs to figure out what he means.
Can anyone spot what I'm doing wrong / missing?
Thanks for your time!
EDIT
I forgot to mention -- the DOM element this is attached to is <input type="hidden" multiple="true" class="notification-selector select2-result-selectable"></input>
Ok, I finally figured out the solution.
I was misunderstanding $.ajax() -- I did not really think about it actually being an asynchronous call. My code to check for the data being returned from the call was running before the AJAX actually finished, so I was always getting undefined.
I assigned a variable to the AJAX call, and set "async: false", and it worked perfectly.
fetchSetNotifications: function() {
var addresses = $.ajax({
method: 'GET',
dataType: 'json',
context: $('#notifications'),
url: '/Notifications/fetch/',
async: false,
alert(addresses);
}
The jqXHR object I get in 'addresses' then contains the response data I want in the "responseText" attribute.

How to Ajaxify a hyperlink (JQuery & Ajax)

I have to dynamically populate content into a DIV on clicking a hyperlink which should pass a value (code) to retrieve the content from server.
How can I achieve this using JQuery, Ajax and Hyperlink? I know how to retrieve content from server using JQuery & Ajax but I am struggling on how to Ajaxify an hyperlink and pass a value?
Well, you could start by giving this link an unique id so that you could reference it from client scripts:
<%= Html.ActionLink(
"link text",
"action",
"controller",
null,
new { id = "myLink" }
) %>
and then you could unobtrusively AJAXify it in a separate file javascript file:
$(function() {
$('#myLink').click(function() {
$.ajax({
url: this.href,
success: function(result) {
// TODO: handle the results here
}
});
return false;
});
});
Of course if the result of this action is a partial view HTML that you would like to inject on some placeholder in the DOM you could use the .load() method:
$(function() {
$('#myLink').click(function() {
$('#result').load(this.href);
return false;
});
});
YAnd if you want to pass some additional values with the AJAX request:
$.ajax({
url: this.href,
data: { someParam: 'some value', someOtherParam: 'some other value' },
success: function(result) {
// TODO: handle the results here
}
});