Grab Form Data as an Object - javascript

My goal is to contruct an object with data of my form.
After doing some googling, people suggested me to use serialize()
Now, I got this from my form data
_method=PUT&_token=rs8iLxwoJHSCj3Cc47jaP5gp8pO5lhGghF1WeDJQ&max_down=256&max_up=256&cpe_mac=000D6766F2F6&device_mac=503275AE7A69
Is there a way to convert that long string into an object ?
Is there a any other way to achieve this ?
Any direction on this will mean a lot to me !
I've tried
$( "form#editRateLimitForm" ).on( "submit", function( event ) {
event.preventDefault();
var serialize = $( this ).serialize() ; // Nothing printing out
console.log(serialize); // _method=PUT&_token=rs8iLxwoJHSCj3Cc47jaP5gp8pO5lhGghF1WeDJQ&max_down=256&max_up=256&cpe_mac=000D6766F2F6&device_mac=503275AE7A69
});

I have used this approach many times.
$("form#editRateLimitForm").on("submit", function( event ) {
event.preventDefault();
var formObj = {},
formData = $(this).serializeArray(),
i;
for (i in formData) {
formObj [formData[i]['name']] = formData[i]['value'];
}
console.log(formObj);
});
console.log should show
{_method: 'PUT', token:'rs8iLxwoJHSCj3Cc47jaP5gp8pO5lhGghF1WeDJQ', max_down: '256',
max_up: '256', cpe_mac: '000D6766F2F6', device_mac: '503275AE7A69'}

Related

How to pass attribute to jquery autocomplete

I am having a serious problem with trying to use a jquery autocomplete and javascript is not my strongest skill.
I am using the jquery.auto-complete plugin found here:
https://github.com/Pixabay/jQuery-autoComplete which is a rewrite of the devbridge.com version.
so far, getting it to work has been no problem, but now i am stuck with a problem and really need some help.
i have a form for data entry for a very large database. nothing special, but a very large database with lots of fields and about 80% of the data is simple text fields that have very similar or duplicated values, but still varied enough that nothing really other than an autocomplete will make life easier. this can be very time consuming and tedious, especially when database is 1M+ records.
so since i have around 40 fields that require lookups, this is my current code:
$(window).on('load', function () {
var xhr;
$('[data-autocomplete]').autoComplete({
source: function(term, response){
try { xhr.abort(); } catch(e){}
xhr = $.get( '/api.php',
{ field: $(this).attr('data-autocomplete'),
search: term,
}, function(data){ response(data); });
}
});
...
and this is my field:
<input type="text" name="data[title]" id="data[title]" data-autocomplete="title" />
but for some reason, i can't get the value of the attribute "data-autocomplete" to be passed to the autocomplete function. it just comes up as undefined and that is critical for the search
what i need is a way that i can bind the autocomplete on page load to any text input with an attribute of "data-autocomplete" (so far so good) and then pass that value to the autocomplete thus creating an url of:
api.php?field=[data-autocomplete]&search=[term]
sounds simple, but seems to be exceedingly difficult. my other option is to duplicate the autocomplete statements some 40+ times and that just seems ridiculous!
so can somebody please give me some direction? thank you!
Loop over the elements in an each loop so you can isolate instances.
$('[data-autocomplete]').each(function() {
let xhr,
$input = $(this),
field = $input.attr('data-autocomplete');
$input.autoComplete({
source: function(term, response) {
try {
xhr.abort();
} catch (e) {}
xhr = $.get('/api.php', { field: field, search: term}, response);
}
});
});
The first thing I notice is that you have an erroneous comma after the variable "term" in your get call:
xhr = $.get( '/api.php',
{
field: $(this).attr('data-autocomplete'),
search: term, <-- code-breaking comma.
}, function(data){ response(data); });
It's also possible that your get call's reference to this is no longer refferring to the expected object.
Try something like this instead:
$( window ).on( 'load', function () {
let xhr, me = this;
$( '[data-autocomplete]' ).autoComplete( {
source: function( term, response ) {
try { xhr.abort(); } catch( e ){}
xhr = $.get( '/api.php',
{
field: $( me ).attr( 'data-autocomplete' ),
search: term
},
function( data ){ response( data );
} );
}
} );
} );

Trying to create reusable custom ajax form plugin

Updated code - working
(function($) {
$.fn.mbajaxform = function( mbopts ) {
var mb_form_items = $(this).find('input, submit, button'),
mb_form_type = mb_mbtheme_js[0],
mb_get_page_slug = mb_mbtheme_js[1],
mb_redirect = mb_mbtheme_js[2],
mb_redirect_time = mb_mbtheme_js[3],
mb_form_disable = mb_mbtheme_js[4];
// create the defaults
let mbdefaults = {
beforeSend: function( el, beforeSend ) {
},
success: function( el, success ) {
},
complete: function( el, complete ) {
},
error: function( el, error ) {
}
};
// extend the defaults
let mboptions = $.extend( {}, mbdefaults, mbopts );
return this.each( function() {
// the variable for this
var $this = $(this);
function beforesend_callback(e) {
mboptions.beforeSend( $this, e );
}
function success_callback(e) {
mboptions.success( $this, e );
}
function complete_callback(e) {
mboptions.complete( $this, e );
}
function error_callback(e) {
mboptions.error( $this, e );
}
// run the function
$this.on( mb_form_type, function(mb) {
// stop the default function of buttons
mb.preventDefault();
var mb_ajax_form_data = new FormData( $this[0] );
// do the ajax
$.ajax({
method: "POST",
data: mb_ajax_form_data,
contentType: false,
processData: false,
beforeSend: beforesend_callback,
success: success_callback,
complete: complete_callback,
error: error_callback
});
});
});
};
}( jQuery ));
$("#mbform").mbajaxform();
Original question
This is my first attempt at creating a plugin but was following a few tutorials hoping it would work first go - rookie!
I have an AJAX form that I noticed was being repeated (such as password resets, theme settings, user creation) across a few sub-sites within my network (using Wordpress Multisite), so I decided it could be more beneficial to create a function that was able to be extended (if changes needed) but otherwise apply the defaults.
see edit revisions for older code
At a glance looks like you might not be referencing the correct options variable.
You're setting it with the name mboptions
let mboptions = $.extend({}, mbdefaults, mbopts);
but then trying to access it using options
options.beforeSend($this, e);
And when you're trying to bind the submit event you're not accessing the event name from the options object. So instead of
$this[mb_form_type](function(mb) {...});
I think
$this.on(mboptions.mb_form_type, function(mb) {...}):
is a bit more readable (also you can later remove the binding with this.off(mboptions.mb_form_type) if you need to ;)

Having an issue with AJAX call on Paste event jQuery

I am trying to get the pasted contents of a form text field to trigger an AJAX action which connects to a php script to deal with the data and then sends the relevant response.
The php script is working perfectly so I know the problem isn't there.
The jQuery function also works perfectly, by alerting whatever is pasted into the text field if I do this
$(document).ready(function(){
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
alert (url);
}, 100);
});
});
But when I try to add the AJAX business it all fails.
I'm obviously doing it wrong but I don't know the correct way to do it.
The way I'm calling AJAX is the same method I use in a whole bunch of other scripts and it works fine in those so it must be to do with where it's being called.
I've tried (left off the doc ready to save clutter) :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
}, 100);
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
});
And also tried :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
}, 100);
});
And I've also tried setting the url var directly in the data var :
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : $(capture).val(),
'check' : check
};
But nothing is working.
I suspect this is to do with the setTimeout function.
Is there a specific way of firing an AJAX call when also using setTimeout?
Just for clarity. I'm trying to trigger an AJAX call on paste event.
try to increase the time, I mean
setTimeout(function(){...
,1000}
try experimenting with different times.
If you get the answer then your post call is eating up the time.

jQuery: Textbox text change event after autocomplete?

I'm using jquery autocomplete plugin for a textbox:
$('#TargetArea').autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })'
});
It works fine. Now, I want to do is: when the textbox text changed, call an action to get data from database, then show the data in another div.
$('#TargetArea').change(function () {
var url = "/My/Test";
var target = $("#TargetArea").val();
$.post(url, { Target: target }, function (data) {
$("#resultId").html(data);
});
})
However, this change event never triggered. If I comment out the autocomplete part, then it works fine. Anyone knows what the problem is? or, How I should do this?
Thanks
I think you should use the change event of the autocomplete plugin.
See the documentation here: http://api.jqueryui.com/autocomplete/#event-change
Check it, I think it should works.
$( "#TargetArea" ).autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })',
change: function( event, ui ) {}
});
you can make this either
1 - Initialize the autocomplete with the change callback specified:
$( '#TargetArea' ).autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })',
change: function( event, ui ) {
var url = "/My/Test";
var target = $("#TargetArea").val();
$.post(url, { Target: target }, function (data) {
$("#resultId").html(data);
});
}
});
or
2- Bind an event listener to the autocompletechange event:
$('#TargetArea').autocomplete({
source: '#Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })'
});
$( '#TargetArea' ).on( "autocompletechange", function( event, ui ) {
var url = "/My/Test";
var target = $("#TargetArea").val();
$.post(url, { Target: target }, function (data) {
$("#resultId").html(data);
});
});
This will be triggered when the field is blurred, if the value has changed.
Source : http://api.jqueryui.com/autocomplete/#event-change

jQuery Submit Form on Enter Not Working

In the script below I've got the code to allow me to add a new line by pressing shift+enter but when I just press enter the code does nothing. I also get no errors. I've removed the resize caret so there is no need to mess with that. What is the bug in my code keeping me from submitting the form?
Disclaimer: yes I know there are multiple posts on this subject but none of them fix my problem so I'm hoping it's a new problem.
<script>
$('#myFormActivity .commentTextarea').keypress(function(event){
if (event.keyCode==13 && !event.shiftKey) {
event.preventDefault();
$( "#myFormActivity" ).submit(function(event1) {
alert("sent");
// Stop form from submitting normally
event1.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
activityid = $form.find( "input[name='activityid']" ).val(),
comment = $form.find( "textarea[name='comment']" ).val(),
url = "process/insertComment.php";
// Send the data using post
var posting = $.post( url, { activityid: activityid, comment: comment } );
// Put the results in a div
posting.done(function( data ) {
$(this).children('.commentTextarea').val('');
});
return false;
});
return false;
}
});
</script>
The class commentTextarea is the class assigned to the textarea element inside of the form which has the ID of myFormActivity.
What you are doing in your keypress event when you say
$( "#myFormActivity" ).submit(function(event1) {
is binding an event to the form submit, not triggering it. Something like (I haven't actually tested it) the following is more what you want I think (note the mime-type on the script tag and that the events should be bound in a document ready):
<script type="text/javascript">
$(function(){
$('#myFormActivity .commentTextarea').keypress(function(event){
if (event.keyCode==13 && !event.shiftKey) {
event.preventDefault();
$( "#myFormActivity" ).submit();
return false;
}
});
$( "#myFormActivity" ).submit(function(event1) {
alert("sent");
// Stop form from submitting normally
event1.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
activityid = $form.find( "input[name='activityid']" ).val(),
comment = $form.find( "textarea[name='comment']" ).val(),
url = "process/insertComment.php";
// Send the data using post
var posting = $.post( url, { activityid: activityid, comment: comment } );
// Put the results in a div
posting.done(function( data ) {
$(this).children('.commentTextarea').val('');
});
return false;
});
});
</script>

Categories

Resources