0

I have a form and want to send the data via AJAX in a JSON Format over to my PHP File. I use jQuery to handle all the events.

I now got stuck and try to find for hours to find a way.

My Data String looks right now like this:

search = {name:$('#name').val(),group:$('#group').val()};

But I have now decided that I only want fields send over, if there is actually a Value set in it. So I created the follwoing part:

$('#search_form input[type=text]').each(function(n,element){
  if ($(element).val() != '') 
  {
    search_fields = {test :$('#'+element.id).val()};
  }
});

I now want to replace the part where it says test with the input field name and than I would have the value sitting next to it. I hope I explain it right. How would I be able to do this? Because it could be up to 3 Input Fields and I want them to add themself if they have a value or leave them out. Any hint?

Luka
  • 748
  • 2
  • 9
  • 36

4 Answers4

1

Take a look at this question:

Convert form data to JavaScript object with jQuery

I think you'll want to look at using JQuery's .serialize() or .param() to make it simpler to get you form value into JSON

Community
  • 1
  • 1
Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
1

you should use something like

var search = [];
$('#search_form input[type=text]').each(function(){
    search.push({name: $(this).attr("name"), value: $(this).val()});
});

so use JSON.stringify() function to encode it as JSON string If you use this solution, you don't need to use get_object_vars on PHP side

Omid
  • 4,575
  • 9
  • 43
  • 74
  • This seems to work. Thank you very much for your solution !! I hopefully get this now sorted. Thanks again. – Luka Feb 02 '12 at 21:29
1

Have you heard of the serialize function in jQuery?

$("#search_form").serialize();
Chris Kempen
  • 9,491
  • 5
  • 40
  • 52
0

A simple example:

$.ajax({
    type: 'POST',
    url: http://example.com,
    data: $('form').serialize()
});
Apostle
  • 482
  • 2
  • 7
  • 23