【问题标题】:How to submit form ajax in symfony2?如何在 symfony2 中提交表单 ajax?
【发布时间】:2023-04-10 22:25:01
【问题描述】:

我即将使用 Ajax 提交我的表单,我已经使用 POST 成功提交了我的表单,但不知道如何将 Ajax 与 Symfony

一起使用

构建

    $builder->add('name', 'text', array('constraints' => array(new NotBlank()), 'attr' => array('placeholder' => 'Name')))
        ->add('gender', 'choice', array('empty_value' => 'Select Gender', 'constraints' => array(new NotBlank()), 'choices' => \AppBundle\Entity\Records::$gender_list, "required" => true))
        ->add('dateOfBirth', 'birthday', array('label' => 'Date Of Birth','required'=>true))
        ->add('image_path', 'file', array('label' => ' ','required'=>false, 'data_class' => null, 'constraints'=>array(new Assert\File(                                             array('mimeTypes'=>$mime_types, 'maxSize'=>'2048k' )))))
        ->add('country_of_birth', 'entity', array('empty_value' => 'Country of Birth',
            'class' => 'AppBundle\Entity\Location',
            'property' => 'country',
            'label' => 'Country of Birth'
        ))
        ->add('religion', 'entity', array('empty_value' => 'Select Religion',
            'class' => 'AppBundle\Entity\Religion',
            'property' => 'name',
            'label' => 'Religion'
        ));

动作

        $success = false;
        $record_rep = new \AppBundle\Entity\Records();
        $form = $this->createForm(new \AppBundle\Form\AddPersonType(), $record_rep);

        if ($this->getRequest()->getMethod() == 'POST') {
            $form->submit($request);
            if ($form->isValid()) {
                $data = $form->getData();
                $file = $data->getImagePath();
                $image = $file->getClientOriginalName();

                $new_image_name = $this->hanldeUpload($image, $file);
                $this->savetoDB($data, $record_rep, $new_image_name);
                $success = true;
            }
        }
        return $this->render('AppBundle:Homepage:add_person_form.html.twig', array('form' => $form->createView(), 'success'=>$success ));
    }

【问题讨论】:

    标签: javascript php jquery ajax symfony


    【解决方案1】:

    使用 jQuery,使用serialize() 表单并将其发布到您的路线。

    $('#form').submit(function(e) {
    
        e.preventDefault();
        var url = "{{ path('YOUR_PATH') }}";
        var formSerialize = $(this).serialize();
        
        $.post(url, formSerialize, function(response) {
            //your callback here
            alert(response);
        }, 'JSON');
    });
    

    在你的行动中

    if ($form->isSubmitted() && $form->isValid()) {
    
    ....
    
      // or return new JsonResponse($anyData);
      return new Response(json_encode(['status'=>'success']));
    }
    

    这样应该没问题。但是您可以在路由中添加一些参数,例如格式、方法等。

    【讨论】:

    • 我的操作已经渲染了 html,所以当我尝试你的解决方案时,它总是渲染成功值 = false,所以除了我有图像之外,我还需要在我的视图中处理它,所以这个块 ajax要执行吗?
    • 看起来顶部代码块的最后一行应该是}); 而不是} -HTH
    • return new Response(json_encode(array('status'=>'success')); 缺少最后一个右括号。应该是return new Response(json_encode(array('status'=>'success'))); -HTH
    • 不再适用于 symfony 4。它说“无法检查未提交的表单是否有效。在 Form::isValid() 之前调用 Form::isSubmitted()。”
    【解决方案2】:

    对于阿贾克斯:

     $("#person").submit(function(e){
    
    
        var formURL = "{{ path('form') }}";
        var formData = new FormData(this);
        $.ajax({
            url: formURL,
            type: 'POST',
            data:  formData,
            mimeType:"multipart/form-data",
            contentType: false,
            cache: false,
            processData:false,
            success: function(data, textStatus, jqXHR)
            {
    
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
            }
        });
        e.preventDefault(); //Prevent Default action.
        e.unbind();
    });
    $("#person").submit();
    

    为了行动

    if ($request->isXmlHttpRequest()) {
    
    ....
    
        return new Response(json_encode(array('status'=>'success')));
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-27
      • 2014-09-12
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多