0

I need to pass an array to a php page with AJAX. This array of input elements gets sent to the other page:

<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith" size="117" >

This is how I prepare it for sending:

var txtCoursesNamewith = $.serialize($('#txtCoursesNamewith').val());

But I get this error when running the script:

TypeError: $.serialize is not a function

How can I send an array with AJAX?

1
  • I assume that you want to serialize several fields. Am I right? Or is it only one value you want to send with ajax? Commented Mar 17, 2013 at 15:22

4 Answers 4

1

I am facing same problem and, i am just using code like this. but first of all please insert one hidden field and set textbox id like this:

<input type="hidden" name="txt_count" id="txt_count" value="3" />
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith1" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith2" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith3" size="117" >

<script type="text/javascript">
var txt_count= $('#txt_count').val();
for (i=1; i<=txt_count; i++){
   queryString += "&txtCoursesNamewith%5B%5D=" + $('#txtCoursesNamewith'+i).val();
}
</script>

finally we can pass queryString variable to ajax, and you can print array.

<?php
echo "<pre>";
print_r($_GET); // or print_r($_POST);    
?>
Sign up to request clarification or add additional context in comments.

Comments

0
var textBoxes;   
$('input[name="txtCoursesNamewith[]"]').each(function() {
textBoxes+=$(this).val()+"|||";
});

Now the textBoxes have all the values of text field with ||| separated and pass to php script and use explode() function to split each input value . may it helps u

Comments

0

You don't need to use .val() because .serialize() works on a the field itself, not on the value. (because it needs to get the name and the value from the field)

You can also call serialize() directly on a jQuery object, rather than using the jquery object as a parameter. Do it like this:

var txtCoursesNamewith = $('#txtCoursesNamewith').serialize();

Hope that helps.

Comments

0

Because $.serialize($('#txtCoursesNamewith').val()) is a string and not a jQuery object, it doesn't have the serialize function.

If you want to serialize the input (with its value), use $('#txtCoursesNamewith').serialize();

$.ajax({
type: 'POST', 
url: your url,
data: $('#'+form_id).serialize(), 
  success: function(data) {
    $('#debug').html(data);
  }
});

Then in php

<?php
  print_r($_POST);
?>

1 Comment

its send me like this its not an arrya txtCoursesNamewith%5B%5D=%D9%84%D9%84%D9%84%D9%84

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.