0

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!

Rick Weston
  • 11
  • 1
  • 5
  • What about using jQuery to grab the form elements/inputs you're interested in, and then get the values that way. For example, if the ID of your form was `the_form`, then you could do the following: `$('#the_form input')`. – HartleySan Jul 25 '13 at 04:27
  • The issue is that I don't know what the form inputs will be named prior to the form submission, or rather some of the input names will be made on the fly by the user. I need to pull the name and the value when the form is submitted, then pass those values through. – Rick Weston Jul 25 '13 at 04:33
  • jQuery has some helpers to serialize your form. http://api.jquery.com/serializeArray/ – elclanrs Jul 25 '13 at 04:35
  • @Rick Weston, you can still use `$('#the_form')` to get the inputs, and once you have them, use jQuery methods like `val()` and `attr()` to get the names and value of the inputs. – HartleySan Jul 25 '13 at 06:21
  • I could really use an example that is using my code above so I can understand the process. There seems to be like a million ways to accomplish the same thing with Jquery. ;o) – Rick Weston Jul 25 '13 at 06:46
  • I have updated the code to show the method I am attempting to use to collect and pass the $_POST values to the action function "wplp_edit_member". Currently the values are not being passed, I'm thinking it may just be a syntax issue OR I may be totally missing something as I am not a Jquery expert by any means. – Rick Weston Jul 25 '13 at 20:57

3 Answers3

1

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.

shakib
  • 5,449
  • 2
  • 30
  • 39
  • Maybe i misunderstood, but isnt something like http://jsfiddle.net/pndEh/ you intend to achieve? – shakib Jul 25 '13 at 08:07
0

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).

Community
  • 1
  • 1
  • Thanks for the quick answer, I saw the post you referenced previously, however I don't see how it works in relation to the code that I posted above. Please forgive my lack of Jquery knowledge. Still trying to learn and fit all the pieces together. ;o) – Rick Weston Jul 25 '13 at 04:38
  • Trying to make this work, can you show me how you would integrate this in my code above? I just don't quite see where all the pieces fit yet. ;) – Rick Weston Jul 25 '13 at 06:05
0

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!

Rick Weston
  • 11
  • 1
  • 5
  • On another note, this is also a solution for calling a PHP function from a form submition with AJAX. By using the format of data.action = "your_PHP_Function"; in the code above to add the action. – Rick Weston Jul 26 '13 at 01:41