开发者

Problem using $.ajax() to send JSON to PHP file

开发者 https://www.devze.com 2023-03-19 06:37 出处:网络
I have not been able to find the answer to this anywhere.I have a click event handler for a form submit button that sends JSON to a php file, which processes the input and returns an XML result.It wor

I have not been able to find the answer to this anywhere. I have a click event handler for a form submit button that sends JSON to a php file, which processes the input and returns an XML result. It worked perfectly when I used $.post() for this, but I needed to have an extra error handler in case there is a connection or server problem. So I turned to the $.ajax() method with it's built in error callback and it has never worked one time. I keep getting a http 200 with "parsererror". I've tried messing with the contentType and other parameter, but nothing works. I'm pullng my hair out on this. Here is the code:

Click handler with $.post() that works perfectly:

      $('[id$=-submit]').click
 (
function()
{
  formName = $(this).attr('id');
  formName = formName.replace('-submit','');
  var isSubmitted = getSubmittedForms(formName);
  if(isSubmitted == 'no')
  {
    var inputJSON = {};
    inputError = 0;
    dataerror = 0;
    submitButtonText = '';
    submitButtonText = $(this).text();
    submitId = $(this).attr('id');
    if (submitButtonText == '')
    {
      $(this).attr('src', 'images/' + formName + '-loading.gif'); 
    }
    else
    {
      $(this).text('Loading');
    }
    $('input[id*='+formName+']').each
    (
      function()
      {
        currentId = $(this).attr('id');
        currentData = $(this).val();
        currentInputId = currentId.replace(formName+'-','');
        compareString = getFormInputRegex(currentInputId);
        regexResult = compareString.test($(this).val());
        if(regexResult != true)
        {
          $(this).val('');
          $('#' + currentId + '-error').show();
          inputError = 1;
          if (submitButtonText == '')
          {
            $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
          }
          else
          {
            $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
          }
        }
        else
        {
          inputJSON[currentInputId] = currentData; 
          $('#' + currentId + '-error').hide();
        }
      }
    )
    if(inputError==0)
    {
      JSONdata = JSON.stringify(inputJSON);
      $.post
      (
        'processForm.php',
        {
          data: JSONdata         
        },
        function(xmldata)
        {
          if(xmldata)
          {
            $(xmldata).find('dataerror').each
            (
              function()
              {
                dataerror = 1;
                $('#' + formName + '-submitted-message').text('An error has occurred, and your information could not be sent at this time.');
                $('#' + formName + '-submitted-message').show();
              }
            );
            if(dataerror != 1)
            {
              $(xmldata).find('inputerror').each
              (
                function()
                {
                  inputError = 1;
                  errorTagName = $(this).text();
                  $('#' + errorTagName).val('');
                  $('#' + formName + '-' + errorTagName + '-error').show();
                }
              );
              if(inputError == 0)
              {
                $('input[id*='+formName+']').each
                (
                  function()
                  {
                    $(this).val('');
                    $(this).next().hide();
                  }
                );
                $('#' + formName + '-submitted-message').show();
                submitClicked = submitClicked + formName + 'qqq';
              }
            }
            if (submitButtonText == '')
            {
              $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
            }
            else
            {
              $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
            }            
          }
        },
        "xml"
      );
    }
  }
  else
  {
    $('#' + formName + '-submitted-message').text('This form has already been submitted.');
    $('#' + formName + '-submitted-message').show();
    clearTimeout(formSubmitTimer);
    formSubmitTimer = setTimeout
    (
      function()
      {
        $('#' + formName + '-submitted-message').fadeOut('fast');
      }
      ,5000
    )
    $('input[id*='+formName+']').each
    (
      function()
      {
        $(this).val('');
        $(this).next().hide();
      }
    );
  }
}
  );

Here is the script using $.ajax() that never works:

  $('[id$=-submit]').click
  (
function()
{
  formName = $(this).attr('id');
  formName = formName.replace('-submit','');
  var isSubmitted = getSubmittedForms(formName);
  if(isSubmitted == 'no')
  {
    var inputJSON = {};
    inputError = 0;
    dataerror = 0;
    submitButtonText = '';
    submitButtonText = $(this).text();
    submitId = $(this).attr('id');
    if (submitButtonText == '')
    {
      $(this).attr('src', 'images/' + formName + '-loading.gif'); 
    }
    else
    {
      $(this).text('Loading');
    }
    $('input[id*='+formName+']').each
    (
      function()
      {
        currentId = $(this).attr('id');
        currentData = $(this).val();
        currentInputId = currentId.replace(formName+'-','');
        compareString = getFormInputRegex(currentInputId);
        regexResult = compareString.test($(this).val());
        if(regexResult != true)
        {
          $(this).val('');
          $('#' + currentId + '-error').show();
          inputError = 1;
          if (submitButtonText == '')
          {
            $('#' + sub开发者_C百科mitId).attr('src', 'images/' + formName + '-submit.gif'); 
          }
          else
          {
            $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
          }
        }
        else
        {
          inputJSON[currentInputId] = currentData; 
          $('#' + currentId + '-error').hide();
        }
      }
    )
    if(inputError==0)
    {
      JSONdata = JSON.stringify(inputJSON);
      $.ajax
      (
        {
          type: "post",
          url: "processFrom.php",
          data: JSONdata,
          dataType: "xml",
          success: function(xmldata, status, xhr)
          {
            $(xmldata).find('dataerror').each
            (
              function()
              {
                alert('Data error detected!');
                dataerror = 1;
                $('#' + formName + '-submitted-message').text('An error has occurred, and your information could not be sent at this time.');
                $('#' + formName + '-submitted-message').show();
              }
            );
            if(dataerror != 1)
            {
              $(xmldata).find('inputerror').each
              (
                function()
                {
                  inputError = 1;
                  errorTagName = $(this).text();
                  $('#' + errorTagName).val('');
                  $('#' + formName + '-' + errorTagName + '-error').show();
                }
              );
              if(inputError == 0)
              {
                $('input[id*='+formName+']').each
                (
                  function()
                  {
                    $(this).val('');
                    $(this).next().hide();
                  }
                );
                $('#' + formName + '-submitted-message').show();
                submitClicked = submitClicked + formName + 'qqq';
              }
            }
            if(submitButtonText == '')
            {
              $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
            }
            else
            {
              $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
            }            

          },
          error: function(XHRerror, textStatusError, thrownError)
          {
            alert(textStatusError);
            $('#' + formName + '-submitted-message').text('An error has occurred, and your information could not be sent at this time.');
            $('#' + formName + '-submitted-message').show();
            if(submitButtonText == '')
            {
              $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
            }
            else
            {
              $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
            }
          }
        }
      );
    }
  }
  else
  {
    $('#' + formName + '-submitted-message').text('This form has already been submitted.');
    $('#' + formName + '-submitted-message').show();
    clearTimeout(formSubmitTimer);
    formSubmitTimer = setTimeout
    (
      function()
      {
        $('#' + formName + '-submitted-message').fadeOut('fast');
      }
      ,5000
    )
    $('input[id*='+formName+']').each
    (
      function()
      {
        $(this).val('');
        $(this).next().hide();
      }
    );
  }
}
 );

and here is the php processing file:

<?php
header('Cache-Control: no-cache');
header("Content-type: text/xml");
require("requirepath.php");
require(REQUIRE_PATH."constants.php");
require(REQUIRE_PATH."autoload.php");
$formData = dtbs::getDb();
function getInputRegex($idname)
{
switch($idname)
{
case 'firstname':
$regexString = '/^[a-zA-Z]+((\s|\-)[a-zA-Z]+)?$/';
case 'lastname':
$regexString = '/^[a-zA-Z]+((\s|\-)[a-zA-Z]+)?$/';
default:
$regexString = '/^[a-zA-Z]+((\s|\-)[a-zA-Z]+)?$/';
} 
return $regexString;
}
$error_number = 0;
$JSON_data = array();
$XML_response = '<'.'?xml version="1.0" encoding="iso-8859-1"?'.'><response>';
if(isset($_POST))
{
$JSON_data = json_decode($_POST['data'], true);
foreach($JSON_data as $key => $value)
{                
$match_string = getInputRegex($key);
$match_result = preg_match($match_string, $value);
if($match_result != 1)
{
$XML_response .= '<inputerror>'.$key.'</inputerror>';
$error_number = 1;
}
}
if($error_number != 1)
{
$XML_response .= '<inputsuccess>inputsuccess</inputsuccess>';
$insert_fields = '(id,';
$insert_data = '(0,';
foreach($JSON_data as $field => $data)
{
$insert_fields .= preg_replace('/[^a-z]/i', "", $field);
$insert_fields .= ',';
$insert_data .= "'$data',";
}
$insert_fields = rtrim($insert_fields, ",");
$insert_fields .= ")";
$insert_data = rtrim($insert_data, ",");
$insert_data .= ")";
$dataInsert = $formData->insert("userdata",$insert_fields,$insert_data);
if($dataInsert === 'queryError')
{
$XML_response .= '<dataerror></dataerror>';
} 
}
}
else
{
$XML_response .= '<dataerror></dataerror>';
}
$XML_response .= '</response>';
echo $XML_response;
?>

Any help would be greatly appreciated. I'm at the end of my rope.

Thanks


Yeah, yer right Slifty, I did dump too much at once but I was way past frustration at the time.

  1. I tried to load firebug but it failed for literally an unkown reason. Never used it before and thought it would come in hand as you said.

  2. I did run the processForm.php script as a normal php page with dummy data and it works swimmingly. It also works swimmingly in conjunction with the click handler receiving it's data via $.post(). When I replace the $.post() with $.ajax() to take advantage of the error callback in case of server/connection problems, it doesn't work at all. The error callback always fires and it gives an http 200 and a "parsererror." When I look at query string when my database class runs the query it tries to insert '0' into the database. So it looks like somehow, someway, that $.ajax is not sending the JSON data. I tried tinkering with the contenType to 'application/json' and tried many things, but nothing seems to work. I don't see any syntax errors. Almost wondering if I need to just go back to using $.post() and the use (I think it's called) .ajaxError() and fire that if there are server/connex issues to be dealt with.


The root of this question is "please help debug!" so I'll throw out some advice for debugging jQuery ajax issues.

  • Look at the "Response" tab in firebug / chrome explorer. This will let you see the request details along with information about what the server's response. It's possible your PHP is throwing errors somewhere.
  • Try skipping out on the AJAX step by loading the relevant PHP page in a browser window which will help you cut half of the complications and isolate the bug to either the client or server side.
  • Try running the ajax in a more simple fashion. Your current call has a lot of extra logic surrounding it. What happens when you just call the page with a simple script?

Note: If possible, refine your question to cut out the code that you have found explicitly irrelevant to the bug, it will make it easier for us to provide useful advice. Where is the error being thrown, for instance?

0

精彩评论

暂无评论...
验证码 换一张
取 消