jQuery Ajax form submission

I am using ajax to send data to the server, I have multiple inputs with the same name so I am using the below code to send the data, but I have one issue that is I want to send the input value to the server which does not have empty, null, undefined and zero value in textbox.

for example, if I have 5 inputs with the name as name[] and there are I filled in only 2 input.
when I submit the form then only 2 inputs will send through ajax.
Please help how me achieve the goal.

$("form#formid").unbind("submit").bind("submit", function(event) {
    event.preventDefault();

    var name = [];
    $('input[name="name[]"]').each(function() {
    name.push(this.value);
    });

    $.ajax({
        url: "./url.php",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            username: name,
        }),
        cache: false,
        success: function(response) {

        }
    });
});

so…whats wrong with what you’ve got? add an if to your push line and youre done…

At the end there is one comma to much after username : user

I am getting this type of array in payload name: ["value1", "value2", " ", " ", " "] but it should be name: ["value1", "value2"] bcz I have input only in two textbox

So… add an if, so that if the value is empty, you don’t push it into the array.

Also, your backend should also be filtering the input to make sure nothing gets accidentally submitted.

How I push only the filled textbox in my ajax?
is this correct…

var name = [];
   $('input[name="name[]"]').each(function() {
   name !== "" && !== "0" && !== null && !== undefined ? "" : name.push(this.value) : "";
});

if (this.value !== "") {

is this right…

var name = [];
   $('input[name="name[]"]').each(function() {
   name !== "" && !== "0" && !== null && !== undefined ? "" : name.push(this.value) : "";
});

By definition, form field values are strings, so, you will either get an empty string “” if nothing has been entered in a field or you will get a “0” if a zero has been entered in a field. These are the only two values you need to test for.

Next, you should trim user entered data before validating it. You should also not write out code for every possible value. Use an array instead and test if a value is in the array. This lets you change the operation of the code simply by modifying the entries in the array.

See this example code -

// define what to remove
const remove = ["","0"];

// define a filter() call-back function named 'filter'
function filter(item) {
  if (remove.includes(item)) {
    return false;
  }
  return true;
}

Your code would become -

    var name = [];
    $('input[name="name[]"]').each(function() {
		// trim each data item
		name.push(this.value.trim());
    });
	// filter the array of data
	name = name.filter(filter);
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.