Ajax和PHP表单 - 500(内部服务器错误)

时间:2015-09-05 19:21:22

标签: javascript php ajaxform

我有一个将发送到电子邮件的联系表单,但是当我尝试发送时,我收到500内部服务器错误。

我已经检查了可能的错误,例如HTML文件中的错误变量名称和这些东西。

我的主持人是Digital Ocean。

这是我的js代码:

  var form = $('#form-contact');
  var formMessages = $('#form-messages');

  $(form).submit( function( event ) {

    event.preventDefault();

    var formData = $(form).serialize();

    $.ajax({
      type  : 'POST',
      url   : $(form).attr('action'),
      data  : formData,
      beforeSend: function(){
         $(".load").show();
      },
    })

    .done( function( response ) {
      $(".load").hide();

      $(formMessages).removeClass('error');
      $(formMessages).addClass('success');

      $(formMessages).text(response);

      $('#form-contact input').val('');
      $('#form-contact textarea').val('');
    })

    .fail( function( data ) {
      $(".load").hide();

      $(formMessages).removeClass('success');
      $(formMessages).addClass('error');

      // Sending
      if ( data.response !== '' ) {
        $(formMessages).text( data.responseText );
      } else {
        $(formMessages).text( 'error.' );
      }

    });

  } );

在这里,我的PHP代码:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Get the form fields and remove whitespace.
  $name = strip_tags(trim($_POST["user_name"]));
  $name = str_replace(array("\r","\n"),array(" "," "),$name);
  $email = filter_var(trim($_POST["user_email"]), FILTER_SANITIZE_EMAIL);
  $message = trim($_POST["user_message"]);

  // Check that data was sent to the mailer.
  if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
      // Set a 400 (bad request) response code and exit.
      http_response_code(400);
      echo "error.";
      exit;
  }

  // Set the recipient email address.
  $recipient = "mail@here.com";

  // Set the email subject.
  $subject = "New contact from " . $name;

  // Build the email content.
  $email_content = "Name: ". $name;
  $email_content .= "\nE-mail: ". $email;
  $email_content .= "\n\nMessage:\n " . $message;

  // Build the email headers.
  $email_headers = "From: $name <$email>";

  // Send the email.
  if (mail($recipient, $subject, $email_content, $email_headers)) {
      // Set a 200 (okay) response code.
      http_response_code(200);
      echo "Thanks, your message was sent.";
  } else {
      // Set a 500 (internal server error) response code.
      http_response_code(500);
      echo "OOps! Sorry, error.";
  }

  } else {
      // Not a POST request, set a 403 (forbidden) response code.
      http_response_code(403);
      echo "Problem with your request!";
  }

1 个答案:

答案 0 :(得分:1)

// // StateTableViewController.m // #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1 #define kLatestKivaLoansURL [NSURL URLWithString:@"http://www.sensored.com"] //2 #import "StateTableViewController.h" #import "ResViewController.h" @interface StateTableViewController() @end @implementation StateTableViewController - (void)viewDidLoad { [super viewDidLoad]; dispatch_async(kBgQueue, ^{ NSData *data = [NSData dataWithContentsOfURL:kLatestKivaLoansURL]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; }); } ////new code??? NSArray *allStatesFinalArray; - (NSArray *)fetchedData:(NSData *)responseData { //parse out the json data NSError *error; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; NSArray *getCompaniesArray = [json objectForKey:@"CompaniesCD"]; //2 get all company info NSArray *getStatesArray = [getCompaniesArray valueForKey:@"state"];//get only states NSSet *getOneStateSet = [NSSet setWithArray:getStatesArray];//get rid of duplicates NSArray* allStatesFinalArray= [getOneStateSet allObjects];//nsset to array NSLog(@"allstatesfinalarray log 1 : %@", allStatesFinalArray);//return allStatesFinalArray; return allStatesFinalArray;// return an array of just one state } ////end newcode??? #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. //return 0; NSLog(@"allstatesfinalarray log 2 : %@", allStatesFinalArray);//return allStatesFinalArray; return [allStatesFinalArray count]; } ////NOTE ABOVE LOG RETURNS CORRECTLY!!!! - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //get log after this step of the array NSLog(@"here is the list going to tableview: %@", allStatesFinalArray); static NSString *CellIdentifier = @"stateCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; cell.textLabel.text = [allStatesFinalArray objectAtIndex:indexPath.row]; return cell; } //////NOTE ABOVE LOG RETURNS SEVERAL NILLS???????? - (IBAction)done:(id)sender { [self dismissViewControllerAnimated:YES completion:nil]; } @end 来自您自己的代码:500

你得到它的原因是因为http_response_code(500);返回false,这意味着它没有正确配置。您需要安装并设置postfix或fakesendmail。