2015-10-14 115 views
0

我正在創建一個自定義wordpress插件,它有一個前端形式,我希望數據與AJAX一起發送到數據庫,並且還返回響應以更新前端表。WordPress前端AJAX表單提交500內部服務器錯誤

一切看起來不錯,直到我點擊 「提交」 按鈕

所以我的AJAX是:

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

    var formData = { 
     'user'    : $('input[name=userid]').val(), 
     'cardname'    : $('input[name=card]').val(), 
     'setname'    : $('input[name=setname]').val(), 
     'quantity' : $('input[name=quantity]').val(), 
     'multiverseid' : $('input[name=multiverseid]').val() 
    }; 

    // process the form 
    $.ajax({ 
     type  : 'POST', // define the type of HTTP verb we want to use (POST for our form) 
     url   : ''+base_url+'/website/wp-content/plugins/test/public/js/process.php', // the url where we want to POST 
     data  : formData, // our data object 
     dataType : 'html', // what type of data do we expect back from the server 
     encode   : true, 
     success : function(updatedTable) { 
      $('div#tableHolder').html(updatedTable); 
     } 
    }) 

     }); 

// stop the form from submitting the normal way and refreshing the page 
    event.preventDefault(); 

    }); 
}); 

的process.php文件,將增加的數據是:

global $wpdb; 

$wpdb->insert( 
'wp_mycards', 
array( 
    'user' => $_POST[userid], 
    'cardname' => $_POST[cardname], 
    'setname' => $_POST[setname], 
    'quantity' => $_POST[quantity], 
    'multiverseid' => $_POST[multiverseid] 

    ) 
); 



$data="<table><tr><td>Image</td><td>Name</td><td>Set</td><td>Quantity</td></tr>"; 

$user_ID = get_current_user_id(); 
$cards = $wpdb->get_row("SELECT * FROM $wpdb->wp_mycards WHERE user = ".$user_ID.""); 

while ($row = mysql_fetch_assoc($cards)) { 

    $data.='<tr><td align="center"><img src="http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid='.$row[multiverseid].'&type=card" width="30" height="42" /></td><td align="left">'.$row[cardname].'</td><td align="center">'.$row[setname].'</td><td align="center">'.$row[quantity].'</td></tr>'; 

    } 

$data.="</table>"; 

echo $data; 

- 我運行它在Firefox和螢火蟲它給我500內部服務器錯誤 - 後值是好的

回答

0

AJAX在WordPress中有點不同。就像在後端使用AJAX一樣,WordPress已經準備好使用Ajax,並且只需要使用正確的功能。

在WordPress中,每個AJAX請求都要通過wp-admin文件夾中的admin-ajax.php文件,並且需要一些操作才能掛鉤。 AJAX請求URL應該指向這個文件。在這裏閱讀一個完整的教程如何做到這一點:https://premium.wpmudev.org/blog/using-ajax-with-wordpress/

它可以看起來有點複雜,首先,買一旦你得到它並不那麼困難。您將需要此功能:

wp_ajax_my_action

wp_ajax_nopriv_my_action

wp_localize_script

+0

我已經添加了需要 '的wp-config.php文件' 在頂部,現在它似乎工作...除userid之外的數據都存儲在db –

+0

這是一個非常糟糕的做法,至少要添加wp-load.php,而不是wp-config.php。請參閱http://ottodestruct.com/blog/ 2010 /不要-包括-WP-負載請/ – ThemesCreator