2016-02-29 4 views
0

С плагином Я добавляю короткий код, который помещает форму на страницу. На сервере у меня есть эта функция:Wordpress и AJAX - вывод из массива

 function ajax_calc(){ 
    // with the POST 

      if(isset($_POST['action']) && $_POST['action'] == 'ajax_calc'){ 
    //clearing and adapting input string 
       $width  = str_replace(',','.',trim(htmlspecialchars($_POST['width'])));  

       $length  = str_replace(',','.',trim(htmlspecialchars($_POST['length']))); 

       $height  = str_replace(',','.',trim(htmlspecialchars($_POST['height']))); 

       $m_rul  = str_replace(',','.',trim(htmlspecialchars($_POST['m_rul'])));  

       $k_zap  = str_replace(',','.',trim(htmlspecialchars($_POST['k_zap']))); 

    // an error if not a float number 
       if(!(float)$width || $width ==''){  
        echo implode(array('loadmsgerr'=>'Error! Width should be number only!')); 

       } 
       elseif(!(float)$length || $length ==''){ 
        echo implode(array('loadmsgerr'=>'Error! Lenght should be number only!')); 

       } 
       elseif(!(float)$height || $height ==''){ 
        echo implode(array('loadmsgerr'=>'Error! Height should be number only!')); 

       } 
       else{ 
    // return result  
        $Perimeter = ($width + $length) * 2 ; // 
        $Square = $Perimeter * $height;  //         // there will be other calculations... 

        $it_test = 10*$k_zap + $m_rul; 

//  here we have an ARRAY with data 
        $answers = array('S' => $Square, 'P' => $Perimeter, 'it_test' => $it_test);      
        echo json_encode($answers); 
          } 
        } 
      } 

Далее, у меня есть JS:

jQuery(document).ready(function(){ 
// catch a click 
    jQuery('#calC#form_calc_id').on('submit', function(e){ 
     jQuery('#calc .result').show().text(ajax_calc_object.loadingmessage);//Обработка... 
//AJAX with POST on url. DataType is json for array   
     jQuery.ajax({ 
      type: 'POST', 
      dataType: 'json', 
      url: ajax_calc_object.ajaxurl, 
      data: { //data from our form 
       'action': 'ajax_calc', // 
       'width': jQuery('#calC#width').val(), 
       'length':jQuery('#calC#length').val(), 
       'height': jQuery('#calC#height').val(),        
//    'security': jQuery('#security').val() 
       'm_rul': jQuery('#pa_м-в-рулоне').text(), 
       'k_zap': jQuery('#pa_k-zap').text(), 

      }, 
      success: function(data){ 
       var resperr = data.loadmsgerr; 

       if(!resperr){//if its all clear 
        json.parse(data); 
        jQuery('#calc .result').html(data.S + data.P); //put the answer to .result taget div 

       } 
       else{ 
        jQuery('#calc .result').text(resperr); //or an error message 
       } 

      }, 
      error: function(xhr, textStatus, errorThrown) {//console log 
       if (xhr.status != 0) { 
        var msg = ' (' + xhr.status + ') '; 
        if (textStatus) msg += ': ' + textStatus; 
        if (xhr.status < 200) { 
         msg = 'AJAX Informational ' + msg; 
        } else if (xhr.status < 300) { 
         msg = 'AJAX Success ' + msg; 
        } else if (xhr.status < 400) { 
         msg = 'AJAX Redirection ' + msg; 
        } else if (xhr.status < 500) { 
         msg = 'AJAX Client Error' + msg; 
        } else { 
         msg = 'AJAX Server Error' + msg; 
        } 
        console.log(msg); 
       } else { 
        console.log(errorThrown); 
       } 
      } 
     }); 
     e.preventDefault(); 
    }); 
}); 

Проблема заключается в том, что я не имею никакого результата на моей странице. консоли говорит:

AJAX успеха (200): parsererror

С моей функции я вижу это:

{ "S": "", "P": "" , "it_test": "19"} 0

Я думаю, что все это от 0 в конце строки json. Но я не могу понять, почему он появляется там.

+0

Вы также можете опубликовать свой PHP-код? – Mark

+0

функция находится в файле плагина WordPress, ее слишком большой для чтения здесь .. к тому же, теперь у меня есть ответ) –

ответ

0

Если мы положим wp_die() в конце функции ajax_calc(), 0 не появится.