We help IT Professionals succeed at work.

How to send a javascript array via AJAX (jquery)?

evibesmusic
evibesmusic asked
on
441 Views
Last Modified: 2017-05-09
Experts,

I feel like a dummy but, I can't figure out the correct syntax to send an array of email addresses via AJAX?

My current script sends all of the email address in one long text string vs. a format that I can actually use on the back end?

What syntax do I need to use to have the values sent in an array vs. a long string?

String being sent by my script:
PARAMS
addresses: joe.blow@mysite.comjohn.doe@mysite.comsally.smith@kp.org

I'm expecting the array to be sent like this:
PARAMS
addresses[]:
joe.blow@mysite.com
john.doe@mysite.com
sally.smith@kp.org

//SEND EMAIL WHEN SEND BUTTON IS PRESSED
$("#send_email").click(function(){
	if(confirm('Press "OK" to send email.\n\nPress "Cancel" to continue without sending email.')){
		var clinician_array = [];
		var clinician_text = '';
		$(".clinician_checkbox").each(function(){
			if($(this).prop('checked')==true){
				clinician_array.push($(this).attr('id'));
			}
		});
		var clinician_array_length = clinician_array.length;
		for(i=0; i < clinician_array_length; i++){
			clinician_text+= clinician_array[i];
		}//END FOR LOOP
		//SEND EMAIL VIA AJAX
		$.ajax({
			method: 'POST',
			url: 'scripts/email.php?args=email',
			data: {
				addresses: clinician_text	
			}
		}).done(function(){
			alert('Data sent');
		}).fail(function(){
			alert('Error');
		});//END AJAX
	}//END IF
});//END #send_email FUNCTION

Open in new window

Comment
Watch Question

Full Stack Developer
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks...that was painfully obvious...if I don't want the values as a string...don't turn them into a string.

Cheers.
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Interested to know - if you are getting values from a form - why not just serialize the form?

Also if you want the checked checkboxes your selector could be

$(".clinician_checkbox:checked").each(function(){
    clinician_array.push(this.id);
});

Open in new window


Serialise array

$clinician_array = $('formselector').serialize();
$.ajax({
   url: 'scripts/email.php?args=email',
   method: 'POST',
   data: $clinician_array
}).done(...

Open in new window

Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.