[英]Laravel 4: Save data into database using ajax from a bootstrap modal
我正在将一个旧的php项目升级为laravel 4项目。 我有一个功能,可以从引导模式使用ajax添加公司数据。 但是此代码不适合我当前的laravel项目,因为我在此文件上使用了mysql_connect和mysql_select_db。 我已经对其进行了测试,但仍然可以使用,但是我想使用诸如company.store之类的命名路由。 我目前正在为该项目使用平稳路由,它可以完美运行。 这是我的旧代码与当前laravel项目的结合,实际上,该代码可以完美地工作。
create.blade.php
function addNewCompany(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser doesn't support ajax!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//txtMessage is used to show message returned from the ajaxRequest
document.getElementById('txtMessage').value = ajaxRequest.responseText;
}
}
var companyName = document.getElementById('txtCompanyName').value;
ajaxRequest.open('POST', '{{ URL::asset("assets/query/saveCompany.php") }}');
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("companyName=" + companyName);
}
saveCompany.php //我放在public / assets / query文件夹中
<?php
$companyName = $_POST["companyName"];
$con=mysql_connect("localhost","root","");
mysql_select_db("dbname", $con);
$sql = "INSERT INTO `companies` (`companyName`)
VALUES ('$companyName')";
$result = mysql_query($sql, $con);
if($result)
{
echo "Company added successfully";
}
else
{
echo mysql_error();
}
?>
因此,与其将ajax请求发送到saveCompany.php文件,不如通过将请求发送为company.store来使用资源丰富的路由。
首先,您必须在app/config/database.php
文件中配置数据库连接。
然后放入routes.php :
Route::controller('companies', 'CompanyController');
车型/ Company.php
<?php
class Company extends Eloquent{
protected $table = 'companies';
protected $guarded = [''];
}
控制器/ CompanyController.php
<?php
class CompanyController extends Controller {
public function getAddCompany(){
return View::make('create');
}
public function postCompany(){
$company = new Company(Input::all());
$company->save();
return Redirect::action('CompanyController@getAddCompany');
}
}
create.blade.php
function addNewCompany(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser doesn't support ajax!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//txtMessage is used to show message returned from the ajaxRequest
document.getElementById('txtMessage').value = ajaxRequest.responseText;
}
}
var companyName = document.getElementById('txtCompanyName').value;
ajaxRequest.open('POST', '{{ URL::action("CompanyController@postCompany") }}');
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("companyName=" + companyName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.