Jquery - Create key value pairs from dynamic form submission - javascript

I am pretty new to jquery and can't seem to figure this issue out.
I need to figure out how to dynamically set the key:value pairs in this code below from a form that has dynamic values for form inputs. The code works if I add the key:value pairs manually, but I don't always know what the form names are going to be as they are created by the user.
Please see the notes in the middle section of code below. I am trying to use the values from .serialize() to pass as the $_POST value.
Here is the value I currently get from the var formValues:
ID=10&user_login=test9&wplp_referrer_id=&&block_unblock=u
However when I try to pull the values in my function using:
$user_id = $_POST['ID'];
The ID of '10' is not being set in $user_id, indicating that the syntax or method I am using to pass the serialized results is not correct below.
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var formValues = $("#wplp_edit_member").serialize(); //Get all the form input values
alert(formValues); //Check form values retrieved for testing only
var numbers = /^[0-9]+$/;
// Validate fields START
var wplp_referrer_id = $("#wplp_referrer_id").val();
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Post data to ajaxurl
$.post(ajaxurl, {
action: "wplp_edit_member", //Call the PHP function to update/save form values
data: formValues, //Use data to pass form field values as $_POST values to the function above
// No More manual inputs of form fields to be passed
//ID:$("#ID").val(),
//user_login:$("#user_login").val(),
//wplp_referrer_id:$("#wplp_referrer_id").val(),
//block_unblock:$("#block_unblock").val(),
},
// Success
function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
}
);
return false;
});
});
Thanks!

If you want to post data as json, you can use a variation of $.fn.serialize(), Add the jquery extension,
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and use it as,
var data = $('#some-form').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
If posting json is not your requirement $.fn.serializeArray can work.
hope this helps.

What you want is to dynamically add properties to a javascript object. How this can be done is all over the web, but also demonstrated here:
Is it possible to add dynamically named properties to JavaScript object?
so in your case, you would set your object up first before calling .post:
var formData = {};
for (...) {
formData[...] = ...;
}
$.post(ajaxurl, formData, function (data) {
...
});
One way you might accomplish the iteration above is to just collect values from all inputs between your <form> tags:
$('form input').each(function ($input) {
formData[$input.attr('name')] = $input.val();
});
There are lots of ways to skin this cat. Also, jQuery has lots of plugins that might be of help here, although usually YAGNI (You Aren't Going To Need It), so just KISS (Keep It Simple, Stupid).

Here is the solution I was able to get working based on the code provided by #shakib
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var numbers = /^[0-9]+$/;
var wplp_referrer_id = $("#wplp_referrer_id").val();
// Validate fields START
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var data = $('#wplp_edit_member').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
return false;
});
});
This is actually a very simple implementation if you understand Jquery/Javascript! ;o)
Thank you to everyone for your input!

Related

Ajax post special characters after serializing a form

AJAX code:
var data = $('#myIDform').serializeObject();
$.post(
'my url',
{data: data},
function(response){
response
});
The serializeObject() function: (I took it from a similar post in here)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
I don't have any kind of parsing or stringify method or so, and whenever I add a new entry on my db with special characters (e.g. 'ñ') it shows perfectly in the response, but the database saves this: 'ñ'
I am not sure the problem is in the database, because the same thing without AJAX, works.
EDIT: When I manually refresh the page it shows as the database, since it's where the data is taken
I have been reading over here and JSON.parse and JSON.stringify dosen't seem to work for me, because I get something strange in the database: '{'I guess I am not doing it correctly or something is working not as intended.
In the .php i parsed it as: $result = $obj->insert ( JSON_parse($_POST['data']) );
And in the .js i strigified it as: var data = JSON.stringify($('#myIDform').serializeObject();
How it looks like in the database: http://prntscr.com/99t6po
EDIT: SOLVED. Database and PHP were in different charsets

JSON parsed object and wild card

I have a function that is supposed to check old data against data. I am parsing data and oldData to get a JSON object respectively as dbData and formData are simply strings containing ID's and values for the HTMML form. The purpuse of the function is to check if the user has made any textchanges some textareas in the HTML form. I want to do this by checking the ID for each textarea and then check if the value in formData and Data are the same. In that case no change has been made and the function will return true.
The data string im parsing looks something like this:
"[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple \",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]"
So for example, i have to check the ID for "textarea1" in dbData and formData and then check if the value is the same. Can this be done using wildcard or is there a better way to archive this?
function CheckValues() {
var isChanged = false;
var formData = $.parseJSON(data);
var dbData = $.parseJSON(oldData);
if(formData !== dbData) {
var isChanged = true;
}
return isChanged;
}
The code shown below works in IE9+, Chrome, FireFox but other
browsers yet to test. The example shows two different values, data and
OldData - data contains "Tea" where as OldData contains "OldTea" so
isChanged flag is true.
function CheckValues() {
var data = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"Tea\"}";
var oldData = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"OldTea\"}";
var formData = JSON.parse(data);
var dbData = JSON.parse(oldData);
var oFormData = Object.keys(formData);
var oDbData = Object.keys(dbData);
var isChanged = false;
if (oFormData.length === oDbData.length)
{
for (var i = 0; i < oFormData.length; i++) {
var propName = oFormData[i];
if (typeof (dbData[propName]) === "undefined") {
isChanged = true;
break;
}
else {
if (formData[propName] !== dbData[propName]) {
isChanged = true;
break;
}
}
}
}
}

Making a variable in JavaScript from AJAX return Value

I scanned a lot of answers here but didn't find a good answer. I'm new to PHP and JavaScript and want to create a variable (for comparison purposes) from a jQuery return value. I'm creating a registration system where I use this to check username availability:
$(document).ready(function() {
$("#username").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
var username = $(this).val();
if(username.length < 2){$("#user-result").html('');return;}
if(username.length >= 2){
$("#user-result").html('<i class="fa fa-refresh fa-spin"></i>');
$.post('core/check_username.php', {'username':username}, function(data) {
$("#user-result").html(data);
});
}
});
});
I can display the return value in a span but for form validation purpose, I need to compare this return value with a set of criteria. How can I declare a variable from this return value?
in your $.post function you get data returned from your ajax-call. just use this to do further stuff with the username:
$.post('core/check_username.php', {'username':username}, function(data) {
$("#user-result").html(data);
var username = data;
if(username == "xxx")
{
// do some stuff here
}
});

how to validate serialized data in Ajax

I have this particular problem, where I need to validate the data before it is saved via an ajax call. save_ass_rub function is called when user navigates to a different URL.
In my application, I have a custom Window and user is allowed to input data. I am able to capture all the data in this step: var data = $('form').serialize(true);. But I need to loop through this and check if data for some specific elements is empty or not. I can't do it when the user is in the custom window. The Custom window is optional for the user. All I want is to alert the user in case he has left the elements blank before the data is submitted.
We are using Prototype.js and ajax .
<script>
function save_ass_rub() {
var url = 'xxxx';
var data = $('form').serialize(true);
var result;
new Ajax.Request( url, {
method: 'post',
parameters: data,
asynchronous: false, // suspends JS until request done
onSuccess: function (response) {
var responseText = response.responseText || '';
if (responseText.length > 0) {
result = eval('(' + responseText + ')');
}
}
});
if (result && result.success) {
return;
}
else {
var error = 'Your_changes_could_not_be_saved_period';
if (window.opener) { // ie undocked
//Show alert in the main window
window.opener.alert(error);
return;
}
return error;
}
}
// Set up auto save of rubric when window is closed
Event.observe(window, 'unload', function() {
return save_ass_rub();
});
</script>
Can some thing like this be done?
After Line
var data = $('form').serialize(true);
var split_data = data.split("&");
for (i = 0; i < split_data.length; i++) {
var elem = split_data[i];
var split_elem = elem.split('=');
if( split_elem[0].search(/key/) && split_elem[0] == '' ){
console.log( split_elem );
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
}
Instead of using the serialized form string, I would use the form itself to do the validation. if $('form') is your form element then create a separate function that checks the form element so its compartmentalized.
function checkform(form)
{
var emptytexts = form.down('input[type="text"]').filter(function(input){
if(input.value.length == 0)
{
return true;
}
});
if(emptytexts.length > 0)
{
return false;
}
return true;
}
and in the save_ass_rub() function
//..snip
if(checkform($('form') == false)
{
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
var data = $('form').serialize(true);
var result;
I only added text inputs in the checkform() function you can the rest of the input types and any other weird handling you would like to that function. As long as it returns false the error will be displayed and the js will stop otherwise it will continue

Run Javascript function before jQuery functions

I am trying to be able to get my form to check if the 2 input boxes have any data input into them before it submits. The reason I am having trouble with this is because I am using the following -
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
})
this.reset();
return false;
});
This makes it so the form is submitted without the page having to refresh, I also have an image appear for a few seconds when the submit button has been pressed -
$(".bplGame1Fade").click(function(){
$("#bplGame1ThumbUp").fadeIn(1000);
$("#bplGame1ThumbUp").fadeOut(1000); });
I don't want these to run unless both the input boxes have data in them. I have tried using OnClick() and OnSubmit(). When using these the message appears saying it isn't a valid entry as I want but once you click OK the form continues to submit.
Is there anyway I can run a JS function to check the input boxes and if one of the boxes is empty, cancel the submission.
Any help with this would be appreciated,
Thanks.
Why dont you just add an if condition to check if you ever get an empty input? You can return the function if it's not valid.
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
var context = this;
var valid = true;
var total = that.find('[name]').length;
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (!value) {
valid = false;
return;
}
data[name] = value;
if (index === total - 1) { //last item
if (valid) {
$.ajax({
url: url,
type: method,
data: data,
});
context.reset();
}
}
});
});
EDIT: You could put the ajax call inside of the foreach. So on the last item, you would make the ajax call if every input had a value.

Categories