Codeigniter ajax插入成功重定向

时间:2016-06-13 08:42:17

标签: javascript php jquery ajax codeigniter

我有一个带有ajax的插入函数,现在,当我成功插入一个值时,我想通过ajax重定向页面。

这是我的控制器:

public function create(){


    $data = array('success' => false, 'messages' => array());

    $this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
    $this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');

    if($this->form_validation->run($this) == FALSE){

        foreach ($_POST as $key => $value) {
            # code...
            $data['messages'][$key] = form_error($key);
        }

    }else{

        $data['success'] = true;
        $data = array(
                'PROVINCE' => $this->input->post('PROVINCE'),
            );
        $insert = $this->Provinces_Model->save($data);
        echo json_encode(array("status" => TRUE));

        $this->index;

    }

    echo json_encode($data);
}

这是我的javascript:

<script>

    $('#form-user').submit(function(e){
        e.preventDefault();

        var me = $(this);

        // perform ajax
        $.ajax({
            url: me.attr('action'),
            type: 'post',
            data: me.serialize(),
            dataType: 'json',
            success: function(response){
                if (response.success == true) {
                    // if success we would show message
                    // and also remove the error class
                    $('#the-message').append('<div class="alert alert-success">' +
                        '<span class="glyphicon glyphicon-ok"></span>' +
                        ' Data has been saved' +
                        '</div>');
                    $('.form-group').removeClass('has-error')
                                    .removeClass('has-success');
                    $('.text-danger').remove();



                }else{
                    $.each(response.messages, function(key, value) {
                        var element = $('#' + key);
                        element.closest('div.form-group')
                        .removeClass('has-error')
                        .addClass(value.length > 0 ? 'has-error' : 'has-success')
                        .find('.text-danger')
                        .remove();
                        element.after(value)
                    });
                }
            }
        });
    });

</script>

这个数据成功保存,但不会重定向到另一个页面。

我是ajax的新手,我想了解如何在不加载模板的情况下将其重定向到我的页面。

添加 - 模型

public function save($data)
{
    $this->db->insert($this->table, $data);
    return $this->db->insert_id();
}

4 个答案:

答案 0 :(得分:1)

使用

java.lang.NullPointerException at com.github.dandelion.core.web.AssetRequestContext.get(AssetRequestContext.java:147)at com.github.dandelion.datatables.core.extension.AbstractExtension.addBundle(AbstractExtension.java:224)
at com.github.dandelion.datatables.core.extension.feature.PipeliningFeature.setup(PipeliningFeature.java:71)
at com.github.dandelion.datatables.core.extension.AbstractExtension.setupWrapper(AbstractExtension.java:138)
at com.github.dandelion.datatables.core.extension.ExtensionProcessor.process(ExtensionProcessor.java:83)
at com.github.dandelion.datatables.core.extension.ExtensionProcessor.process(ExtensionProcessor.java:74)
at com.github.dandelion.datatables.core.extension.ExtensionLoader.loadExtensions(ExtensionLoader.java:66)
at com.github.dandelion.datatables.core.generator.DatatableJQueryContent.<init>(DatatableJQueryContent.java:107)
at com.github.dandelion.datatables.jsp.tag.TableTag.setupHtmlGeneration(TableTag.java:385)
at com.github.dandelion.datatables.jsp.tag.TableTag.doEndTag(TableTag.java:254)
at org.apache.jsp.WEB_002dINF.pages.program.viewProgram_jsp._jspx_meth_datatables_005ftable_005f0(viewProgram_jsp.java:243)
at org.apache.jsp.WEB_002dINF.pages.program.viewProgram_jsp._jspService(viewProgram_jsp.java:104)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:584)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:523)
at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:934)
at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:675)
at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:669)
at org.apache.tiles.request.jsp.JspRequest.doInclude(JspRequest.java:123)
at org.apache.tiles.request.AbstractViewRequest.dispatch(AbstractViewRequest.java:47)
at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47)
at org.apache.tiles.request.render.ChainedDelegateRenderer.render(ChainedDelegateRenderer.java:68)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259)
at org.apache.tiles.template.InsertAttributeModel.renderAttribute(InsertAttributeModel.java:188)
at org.apache.tiles.template.InsertAttributeModel.execute(InsertAttributeModel.java:132)
at org.apache.tiles.jsp.taglib.InsertAttributeTag.doTag(InsertAttributeTag.java:299)
at org.apache.jsp.WEB_002dINF.pages.layout_jsp._jspx_meth_tiles_005finsertAttribute_005f4(layout_jsp.java:255)
at org.apache.jsp.WEB_002dINF.pages.layout_jsp._jspService(layout_jsp.java:127)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.tiles.request.servlet.ServletRequest.forward(ServletRequest.java:265)
at org.apache.tiles.request.servlet.ServletRequest.doForward(ServletRequest.java:228)
at org.apache.tiles.request.AbstractClientRequest.dispatch(AbstractClientRequest.java:57)
at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:397)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:238)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:221)
at org.apache.tiles.renderer.DefinitionRenderer.render(DefinitionRenderer.java:59)
at org.springframework.web.servlet.view.tiles3.TilesView.renderMergedOutputModel(TilesView.java:114)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

在你的成功函数中

答案 1 :(得分:0)

{{1}}

答案 2 :(得分:0)

您可以在成功活动中使用此功能。

   setTimeout(function () {
   location = '<?= base_url(); ?>ControllerName/MethodName';
                                }, 2000);
                            
最后你的代码应该看看这个

 if (response.success == true) {
     // if success we would show message
     // and also remove the error class
     $('#the-message').append('<div class="alert alert-success">' +
     '<span class="glyphicon glyphicon-ok"></span>' +
     ' Data has been saved' +
     '</div>');
     $('.form-group').removeClass('has-error')
     .removeClass('has-success');
     $('.text-danger').remove();
   
    function () {
         setTimeout(function () {
         location = '<?= base_url(); ?>ControllerName/MethodName';
                   }
                    , 2000);
             });
         
几次测试&amp;经过验证的代码

答案 3 :(得分:0)

我刚刚添加了

                $('.alert-success').show(10, function() {
                    $(this).delay(3000).hide(10, function() {
                        $(this).remove();
                        //window.location = "<?php echo base_url(); ?>Provinces/index";
                    });
                })

我的javascript现在看起来像

$('#form-user').submit(function(e) {
    e.preventDefault();

    var me = $(this);

    // perform ajax
    $.ajax({
        url: me.attr('action'),
        type: 'post',
        data: me.serialize(),
        dataType: 'json',
        success: function(response) {
            if (response.success == true) {
                // if success we would show message
                // and also remove the error class
                $('#the-message').append('<div>' +
                    '<span class="glyphicon glyphicon-ok text-success"></span>' +
                    ' Data has been saved' +
                    '</div>');
                $('.form-group').removeClass('has-error')
                                .removeClass('has-success');
                $('.text-danger').remove();

                // reset the form
                me[0].reset();

                // close the message after seconds
                $('.alert-success').show(10, function() {
                    $(this).delay(3000).hide(10, function() {
                        $(this).remove();
                        //window.location = "<?php echo base_url(); ?>Provinces/index";
                    });
                })
            }
            else {
                $.each(response.messages, function(key, value) {
                    var element = $('#' + key);

                    element.closest('div.form-group')
                    .removeClass('has-error')
                    .addClass(value.length > 0 ? 'has-error' : 'has-success')
                    .find('.text-danger')
                    .remove();

                    element.after(value);
                });
            }
        }
    });
});