我试图通过JS函数插入多个记录.JS函数调用执行插入的另一个YII控制器的动作。
我正在从MySql表读取数据,对数据执行某些操作并将更改的数据保存到数组post_data。后来我将这个数组转换为url格式并将参数作为参数传递给JS函数。此函数具有ajax来调用另一个控制器来执行插入。
我想插入2个表。插入第一个contact_details表,然后插入工程师表,所以我希望这个ajax调用以串行方式运行。即,我希望下一次插入仅在上一次插入完成后才开始。
我的代码是:
<script>
function call_migration_api(post_data)
{
//console.log( 'post data in js func = '+post_data);
//var db_data = post_data.serialize();//tried this, but not working.
var db_data = post_data;
$.ajax({
type: "POST",
url:"http://localhost/amica_migration/rapport/chs/Migrationapi/createengineer",
data: db_data,
success: function(server_response)
{
console.log(server_response)
}//end of success
});//end of $.ajax
}//end of function.
</script>
<?php
//reading all values in $post_data array.
foreach ( $post_data as $key => $value)
{
$post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);
echo "<script>call_migration_api('$post_string');</script>";// Call to AJAX function.
?>
迁移API代码:
<?php
public function actionCreateEngineer()
{
$engineer_model=new Engineer();
$contactdetails_model=new ContactDetails();
//****** RETRIVING CONTACT DETAILS ***********
$contactdetails_model->address_line_1= $_POST['address_line_1'];
$contactdetails_model->town= $_POST['town'];
$contactdetails_model->postcode_s= $_POST['postcode_s'];
$contactdetails_model->postcode_e= $_POST['postcode_e'];
$contactdetails_model->telephone= $_POST['telephone'];
$contactdetails_model->email= $_POST['email'];
//********** SAVING CONTACT ***************
if($contactdetails_model->save())
{
echo "<br>Contact Model Saved";
$engineer_model->contact_details_id=$contactdetails_model->id;
$engineer_model->delivery_contact_details_id=$contactdetails_model->id;
//****** RETRIVING ENGINEER DETAILS ***********
$engineer_model->first_name=$_POST['first_name'];
$engineer_model->last_name=$_POST['last_name'];
$engineer_model->active=$_POST['active'];
$engineer_model->id=$_POST['engg_id'];
//****** SAVING ENGINEER DETAILS ***********
if($engineer_model->save())
{
echo "<br>Engineer saved";
}
else
{
echo "<br>Engineer not saved******** ENGG ERROR = ";
print_r($engineer_model->getErrors());
}
}//end of if contact save.
else
{
echo "<br>Contacts NOT SAVED ///////// CONTACT ERROR = ";
print_r($contactdetails_model->getErrors());
}
}//end of create engineer.
?>