繁体   English   中英

如何向控制器发送 ajax post 请求?

[英]How To Sending ajax post request to Controller?

如何将数据从 ajax post 发送或转发到控制器? 我已经从 ajax 获得了 id_user 数据以用于编辑功能到控制器,但无法将其转发或发送到控制器,因此“href”或重定向页面操作不起作用,如何将 ajax 发布数据发送到控制器? 对不起,如果有什么遗漏,如果不清楚你可以问我,我请求你的帮助..

注意我使用:php native mvc

这是我查看 user_management.php 的代码

<?php
$main_controll = new App_UserManagement_Control_UserManagement();
$data_from_ctr = $main_controll->usermanagement();
?>

<script type="text/javascript">
$(document).ready(function(){
    $('.delete').click(function(event){
        event.preventDefault();
        if(confirm("Are you sure want to delete ?")){
            var username = $(this).attr("username");
            var url = $(this).attr("href");
            $.ajax({
                type:'post',
                url: url,
                data:{username:username},
                success: function(data){
                    alert("Data Berhasil dihapus")
                    location.href = '<?php echo BASE_URL. "app.php/usermanagement/user_management "?>';

                },
                error:function(err){
                    alert("Data Gagal Dihapus")
                }
            });
        }
    });

    $('.edit').click(function(event){
        event.preventDefault();

        var id_user =$(this).attr("id_user");
        var url =$(this).attr("href");

        console.log(id_user);
        $.ajax({
            type:'post',
            url: url,
            data:{id_user:id_user},
            success: function(data){
                alert(data)
                //window.location.href = '<?php //echo BASE_URL. "app.php/usermanagement/edit_user "?>';
                location.href = '<?php echo BASE_URL. "app.php/usermanagement/edit_user "?>';
            },
            error:function(err){
                alert(err)
            }
        });
    });
 });

</script>

   <fieldset>
     <legend> User Management </legend>  

    <br />

 <span style="font-size: 15px;">
           <a style="text-decoration: underline" href="<?php echo BASE_URL. "app.php/usermanagement/add_user"?>">Add User</a>
 </span>
 <br /><br />
<table cellspacing="2" cellpadding="2" border="0" align="left" id="tablecontent">                      
    <thead style="background-color:#eee;">
        <th width="25">#</th>
        <!--<th width="25">id</th>-->
        <th width="80">Username</th>
        <th width="117">Name</th>
        <th width="117">Company Code</th>
        <th width="117">Company Name</th>
        <th width="80">User Access</th>
        <th width="80">Login Status</th>
        <th width="80">User Status</th>
        <th width="200">Action</th>

    </thead>
    <tbody>
        <?php if($data_from_ctr['user'] !== NULL): ?>
        <?php $i = 1; foreach ($data_from_ctr['user'] as $row):
         ?>
        <!--?php 
        $No=0;
        foreach($data_from_ctr['user'] as $row) {

            $No++;
        ?>-->

        <tr>
        <td><?php echo $i++; ?></td>
        <!--<td><?php //echo $row ['idx'] ?></td>-->
        <td><?php echo $row ['_user'] ?></td>
        <td><?php echo $row ['_fullName'] ?></td>
        <td><?php echo $row ['_pyrCode'] ?></td>
        <td><?php echo $row ['_desc'] ?></td>
        <td><?php echo $row ['group_user'] ?></td>
        <!--<td><?php //echo $row ['_flag'] ?></td>-->
        <td>
        <?php
        $status = $row['_flag'];
        if($status == 0){
            echo "Offline";
        }elseif ($status == "") {
            echo "Online";
        }else{
            echo "Online";
        }
        ?>
        </td>
        <td>
        <?php
        $active = $row ['active'];
        if($active == 1){
            echo "Active";
        }else{
            echo "Non Active";
        }       

        ?>
        </td>
        <td>
            <a class="edit" href="<?php echo BASE_URL. "app.php/usermanagement/edit_user "?>" id_user="<?php echo $row ['idx'] ?>">Edit</a>
            &nbsp;
            <a class="delete" href="<?php echo BASE_URL. "app.php/usermanagement/delete "?>" username="<?php echo $row ['_user'] ?>">Delete</a>
            &nbsp;
            <a onclick="///return confirm('Are you sure want reset {{ row._fullName }} password ?')" href="#">Reset Password</a>
            </td>       
        </tr>
          <?php endforeach; ?>
          <?php endif; ?>
    </tbody>
</table>
</fieldset>  

这是我的视图 edit_user.php

<?php
$main_controll = new App_UserManagement_Control_UserManagement();
$data_from_ctr = $main_controll->edit();
?>

<?php include_once APP_TEMPLATE_DIR . 'header_content.php'?>

<script type="text/javascript">
$(document).ready(function(){
    $('#level').change(function(){
        var val =$(this).val();
        if(val == '03' || val == '04'){
            $('.limit').show();
        }else{
            $('.limit').hide();
        }
    });


    $('#access').change(function(){
        var val = $(this).val();
        if(val == 'user'){
            $('.level').show();
        }else{
            $('.level').hide();
            $('.limit').hide();
        }
    });

 $('#acctAccessed').chosen();

    $("#chkall").click(function(){
        if($("#chkall").is(':checked')){
            $(".chosen-select option").prop('selected', true);
        }else{
            $(".chosen-select option").prop('selected', false);
        }
        $(".chosen-select").trigger("chosen:updated");
    });
    $(".chosen-select").chosen();
});

</script>

<form method="POST">
<fieldset>
    <legend> Edit User Management </legend>
    <table border="0" width="700" id="usermanagement">
    <tbody>
        <tr>
            <td width="160"><strong>Company</strong></td>
            <td width="10">:</td>
            <td width="193" colspan="2" class="company"><span class ="id_company"><?php echo Session::get('pyrCode'); ?></span> <?php echo $data_from_ctr['account']['desc']['desc'];?></td>
        </tr>
        <tr class="odd">
            <td width="150"><strong>Username</strong></td>
            <td width="10">:</td>
            <td colspan="2">
            <input type="text" name="username" id="username" value="<?php echo $data_from_ctr['user']['_user']; ?>" /></td>
        </tr>
        <tr>
            <td width="150"><strong>Email</strong></td>
            <td width="10">:</td>
            <td colspan="2">
                <input type="text" name="email" id="email" value="<?php echo $data_from_ctr['user']['email']; ?>" />
            </td>
        </tr>
        <tr class="odd">
            <td width="150"><strong>Status User</strong></td>
            <td width="10">:</td>
            <td colspan="2">
           <input type="radio" name="status_active" value="<?php echo $data_from_ctr['user']['active']; ?>"  checked="" id="aktif"/>
                    &nbsp;Active
            <input type="radio" name="status_active" value="<?php echo $data_from_ctr['user']['active'];?>" id="nonaktif" />
                    &nbsp;Non Active
            </td>
            </tr>
        <tr>
            <td width="150"><strong>Name</strong></td>
            <td width="10">:</td>
            <td colspan="2">
                <input type="text" name="name" id="name" value="<?php echo $data_from_ctr['user']['_fullName']; ?>" />
            </td>
        </tr>
        <tr class="odd">
            <td width="150"><strong>Phone Number</strong></td>
            <td width="10">:</td>
            <td colspan="2">
                <input type="text" name="phone" id="phone" value="<?php echo $data_from_ctr['user']['_noHP']; ?>" />
            </td>
        </tr>
        <tr>
            <td width="150"><strong>Access Control</strong></td>
            <td width="10">:</td>
            <td colspan="2">
            <select id="access" name="access">
                <option value="user">User</option>
                <option value="admin_bank">Admin Bank</option>
                <option value="admin_client">Admin Client</option>
            </select>

            </td>
        </tr>
        <tr class="odd level">
            <td width="150"><strong>Level</strong></td>
            <td width="10">:</td>
            <td colspan="2">
            <select id="level" name="level">
                <option value="01">Inputer</option>
                <option value="02">Verificator</option>
                <option value="03">Authorize 1</option>
                <option value="04">Authorize 2</option>
                <option value="05">COPS</option>
            </select>
            </td>
        </tr>
                <tr style="display: none" class="odd limit">
                <td width="150"><strong>Limit Transaction</strong></td>
                <td width="10">:</td>
                <td colspan="2">
                    <input type="text" name="limit" value="<?php echo $data_from_ctr['user']['limit']; ?>" />
                </td>
            </tr>
        <tr>
            <td width="150"><strong>Account Access</strong></td>
            <td width="10">:</td>
            <td colspan="2">
            <select id="acctAccessed" name="acctAccessed[]" multiple="multiple" class="chosen-select" style="width:350px;" data-placeholder="Select account">
            <?php foreach ($data_from_ctr['account']['account'] as $data) :?>    
            <option value="<?php echo $data['id'] ?>"><?php echo $data['_giro_OB']; ?></option>
            <?php endforeach; ?>
            </select>
            <input id="chkall" type="checkbox" >Select All</input>
        </td>
            </tr>
        <tr class="odd">
            <td width="150">&nbsp;</td>
            <td width="10">&nbsp;</td>
            <td colspan="2"><input class="btnsubmitdis" type="submit"  value="Save" /></td>
        </tr>


    </tbody>
    </table>
</fieldset>

<?php include_once APP_TEMPLATE_DIR . 'footer_content.php'; ?>

这是我的控制器 usermanagement.php

    public function edit(){

            Template::setTitle('Edit User Management');

            $id_user = (int)Request::post('id_user');

            //echo json_encode($iduser);

            //$iduser = (int)Session::get('idx');

            $result = $this->getUserbyId($id_user);      

            $dataresult = json_decode($result, true);
            if($dataresult === NULL) {
                echo "<script language = \"javascript\">window.alert(\"\Tidak Ada Data\");";
                echo "javascript:history.back();</script>";
                return false;
            }
            $data = $dataresult;
            return $data;

if(Request::isPost()){

            $username = Request::post('username');
            $name = Request::post('name');
            $level =Request::post('level');
            $access =Request::post('access');
            $phone = $this->formatPhone($post['phone']);
            $limit = Request::post('limit');
            $email = Request::post('email');
            $status_active = Request::post('status_active');
            $existing_username = Request::post('existing_username');

            //validasi jika username dan comp-code sudah ada

            if(!array_key_exists('acctAccessed')){
                $data_post_rek_acc = array();
            }else{
                $account_access = Request::post('acctAccessed');
                $data_post_rek_acc = array();
                foreach ($account_access as $act) {
                $data_post_rek = array('idRek' => $act,
                    'userName'=> $username);
                $data_post_rek_acc[] = $data_post_rek;
                }

            }

            /*$data_update= array(''

            );*/


            $id_user = (int)Request::post('id_user');

            $url= "http://localhost:8585/update-usermanagement/$id_user";

            $curl = curl_init($url);

            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($curl, CURLOPT_FAILONERROR, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                        'Content-Type: application/json',
                        'Content-Length: '.strlen($payload)
                    ));
            $result = curl_exec($ch);
            return $result;

        }else{
        $user_comp_code = Session::get('pyrCode');
        /*API URL */
        $url = "http://localhost:8585/add-account/$user_comp_code";

        /*init cURL resource */
        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec ($curl);

        if ($result === FALSE){

            die('Curl failed: ' . curl_error($curl));
        }
        curl_close($curl);

        //echo $url;echo $result;  die;

        $dataresult = json_decode($result, true);
        $data['account'] = $dataresult;
        return $data;
        }

    }

    public function getUserbyId($id_user){

        //$id_user = Request::post('id_user');

        echo json_encode($id_user);

        if(!empty($id_user)){

            $url="http://localhost:8585/get-user/$id_user";

            $curl = curl_init($url);

            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPGET, 1);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $result =  curl_exec($curl);


            if($result === FALSE){

                die('Curl failed: ' .curl_error($curl));
            }
            curl_close($curl);
            return $result;
        }
    }

        if(Request::isPost()){

            $username = Request::post('username');
            $name = Request::post('name');
            $level =Request::post('level');
            $access =Request::post('access');
            $phone = $this->formatPhone($post['phone']);
            $limit = Request::post('limit');
            $email = Request::post('email');
            $status_active = Request::post('status_active');
            $existing_username = Request::post('existing_username');

            //validasi jika username dan comp-code sudah ada

            if(!array_key_exists('acctAccessed')){
                $data_post_rek_acc = array();
            }else{
                $account_access = Request::post('acctAccessed');
                $data_post_rek_acc = array();
                foreach ($account_access as $act) {
                $data_post_rek = array('idRek' => $act,
                    'userName'=> $username);
                $data_post_rek_acc[] = $data_post_rek;
                }

            }

            /*$data_update= array(''

            );*/


            $id_user = (int)Request::post('id_user');

            $url= "http://localhost:8585/update-usermanagement/$id_user";

            $curl = curl_init($url);

            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($curl, CURLOPT_FAILONERROR, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                        'Content-Type: application/json',
                        'Content-Length: '.strlen($payload)
                    ));
            $result = curl_exec($ch);
            return $result;

        }else{
        $user_comp_code = Session::get('pyrCode');
        /*API URL */
        $url = "http://localhost:8585/add-account/$user_comp_code";

        /*init cURL resource */
        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec ($curl);

        if ($result === FALSE){

            die('Curl failed: ' . curl_error($curl));
        }
        curl_close($curl);

        //echo $url;echo $result;  die;

        $dataresult = json_decode($result, true);
        $data['account'] = $dataresult;
        return $data;
        }

    }

    public function getUserbyId($id_user){

        //$id_user = Request::post('id_user');

        echo json_encode($id_user);

        if(!empty($id_user)){

            $url="http://localhost:8585/get-user/$id_user";

            $curl = curl_init($url);

            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPGET, 1);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $result =  curl_exec($curl);


            if($result === FALSE){

                die('Curl failed: ' .curl_error($curl));
            }
            curl_close($curl);
            return $result;
        }
    }

这是edit.php

<?php
$ctr = new App_UserManagement_Control_UserManagement();
$ctr ->edit();
?>

这是我的问题

我已经从 ajax 获取数据 id_user在此处输入图像描述

但我无法将数据值 id_user 传递给控制器​​并且无法重定向页面 edit_user.php在此处输入图像描述

如果我可以将数据值从 ajax 传递到控制器并且可以重定向页面 edit_user.php,我想喜欢这个

在此处输入图片说明

这是我的数据从 ajax 显示到警报(数据)的新问题,没有真实页面 edit_user.php 示例:我想编辑用户名 derry_save在此处输入图像描述

新错误:这是我的数据 id_user,我在 var id_user 中捕捉到使用警报在此处输入图片说明

这是警报(数据)jquery 的结果在此处输入图片说明

不幸的是(在您的情况下),ajax 是异步的,这意味着您的 click 函数启动 ajax 调用,然后继续运行而无需注意它的作用(因此最后不返回任何内容)。

成功函数稍后调用(当 ajax 成功返回时)并且是一个完全不同的函数,因此它的返回 true 与您原来的点击函数无关。

综上所述,您将需要使用 javascript 来覆盖锚标记的自然行为(直接转到 google.com)以及之后发生的事情(重定向)。

请看看这是否有帮助

$('.delete').click(function(event){
    event.preventDefault();
    $link  = $(this); 
    if(confirm("Are you sure want to delete ?")){
        var username = $(this).attr("username");
       alert(username);
        var url = $(this).attr("href");
        $.ajax({
            type:'post',
            url: url,
            data:{username:username},
            success: function(data){
                alert("Data Berhasil dihapus")

               window.location.href = $link.attr('href');

            },
            error:function(err){
                alert("Data Gagal Dihapus")
            }
        });
    }
});

在 edit.php 你可以这样做

$post_data = $_POST;
$ctr = new App_UserManagement_Control_UserManagement();
$ctr->edit($post_data);

然后在编辑功能中的控制器上,您可以获得这些值

public function edit($post_data){
    echo '<pre>';
    print_r($post_data);die;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM