0

I am trying to read the values of an input array and pass them to my backend PHP, but am not able to get this working. I have the following html:

<input name='field[]' class='myclass' value='test1'>
<input name='field[]' class='myclass' value='test2'>
<input name='field[]' class='myclass' value='test3'>

<input id='post_this_val' type='button' value='Post'>

I want to read these values in jQuery and POST the values to my backend PHP, which will then process the results. This is what I do:

$('#post_this_val').live('click', function () {
    var inpVal = $('input.myclass').map(function(i, el) {
                            return el.value;
                    });
    $.post('/my/php/function', {data: inpVal});
});

The above POST is not working- my php function is not even getting called and the page simply reloads on clicking the POST button. Suggestions please.

1
  • you're missing a "return false;" Commented Mar 12, 2012 at 7:15

2 Answers 2

4

Easiest way to get form values is to wrap those inputs in a form, bind a submit event, and use .serialize() method. The plus of using this method is, if you have a form with input type text and submit, doesn't matter whether the user is submitting using enter, or clicking on the submit button, the handler will still be called.

html:

<form id="myForm">
   <input  name='field[]' class='myclass' value='test1'>
   <input name='field[]' class='myclass' value='test2'>
   <input name='field[]' class='myclass' value='test3'>
   <input id='post_this_val' type='button' value='Post'>
</form>

js:

$('#myForm').live('submit', function(e) {
   $.post('/my/php/function', $(this).serialize());
   e.preventDefault();
   return false;
});
Sign up to request clarification or add additional context in comments.

Comments

0

Just to add to the good answer of andreas, sometimes, complicated problems are caused by the simplest of errors.

Once you check the syntax and everything, I would recommend you install Firebug to check what is exactly going on.

On the net panel of Firebug you can see if the post was successful and if there was a response.

In this case the error could be among several things from incorrect spelling of URL to misspelled variables.

Firebug will help identify these errors, regardless of the cause.

Hope this helps!

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.