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?

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This seems to work. Thank you very much for your solution !! I hopefully get this now sorted. Thanks again.
1

Have you heard of the serialize function in jQuery?

$("#search_form").serialize();

2 Comments

Yes, but than all form fields get send even with empty values or am I wrong about it?
Unfortunately yes, you'd have to parse them after posting them :/
0

A simple example:

$.ajax({
    type: 'POST',
    url: http://example.com,
    data: $('form').serialize()
});

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.