roxy-p February 2016

Ajax form uses name field data in success message when in JSFIDDLE but doesn't work on my site

I am using a form that displays a success message with the person's name, which is achieved by using the data filled in the name input field of my form.

The form is successful when viewing within JSFIDDLE, which is here.

But when using the code exactly as is on my site, the success message says: "Hi Undefined" instead of "Hi John Appleseed", for example.

How do I get the success message to display the input data from the first field in my form?

Thanks.

JQUERY

$(document).ready(function() {
  var errors = false;
  $('.required').parent().find('.input').on('blur', function() {
    var error_div = $(this).parent().find('.error_message');
    var field_container = $(this).parent();
    if (!$.empty_field_validation($(this).val())) {
      error_div.html('This field is required.');
      error_div.css('display', 'block');
      field_container.addClass('error');
      errors = true;
    } else {
      error_div.html('');
      error_div.css('display', 'none');
      field_container.removeClass('error');
      errors = false;
    }
  });
  $('#email').on('blur', function() {
    var error_div = $(this).parent().find('.error_message');
    var field_container = $(this).parent();
    if (!$.email_validation($(this).val())) {
      error_div.html('Expected Input: email');
      error_div.css('display', 'block');
      field_container.addClass('error');
      errors = true;
    } else {
      error_div.html('');
      error_div.css('display', 'none');
      field_container.removeClass('error');
      errors = false;
    }
  });
  $('#message').on('blur', function() {
    var error_div = $(this).parent().find('.error_message');
    var field_container = $(this).parent();
    if (!$.empty_field_validation($(this).val())) {
      error_div.html('Expected Input: message');
      error_div.css('display', 'block');
      field_container.addClass('er        

Answers


David February 2016

In this function:

success: function(data) {
      var message = 'Hi ' + data.name + '. Your message was sent and received.';
      //...
}

If data.name is undefined then that means whatever the server returned doesn't have a name property. (If the server returned any valid JSON object at all.) You're going to have to debug and see what the server does return. And check your server-side code (which you don't show here) to see what's going on.


In this function:

error: function() {
    var message = 'Hi ' + data.name + '. Your message could not be sent or received. Please try again later';
    //...
}

There is no data variable defined in the function. So data itself is undefined. I'm not really sure what you expect data.name to contain here, or where you think it's coming from, but since you never defined it then it doesn't exist.

Post Status

Asked in February 2016
Viewed 1,869 times
Voted 10
Answered 1 times

Search




Leave an answer