从Javascript调用AJAX后,标头PHP无法正常工作

时间:2016-10-30 05:30:26

标签: javascript php jquery ajax

所以,这可能是一个愚蠢的问题,但如果我收到AJAX响应,是否可以在php文件中执行头函数?

在我的情况下,我有一个登录表单,从PHP脚本中获取错误代码(由我硬编码的自定义错误编号用于测试)通过AJAX(以避免重新加载页面)并使用JS警告相关消息,但是如果用户名和密码是正确的,我想创建一个PHP cookie并进行重定向。但是我认为AJAX只允许获取数据,对吧?

这是我的代码:

JS

$.ajax({
    type: 'POST',
    url: 'validate.php',
    data: $this.serialize(),
    success: function(response) {
        var responseCode = parseInt(response);
        alert(codes[responseCode]);
    }
});

PHP

if(empty($user)){
    echo 901;
}else{
    if(hash_equals($user->hash, crypt($password, $user->hash))){
        setCookie(etc...); //this is
        header('admin.php'); //what is not executing because I'm using AJAX
    }else{
        echo 902;
    }
}

如果问题根本没有意义,请抱歉,但我找不到解决方案。提前谢谢!

编辑:我没有包含剩下的代码以避免复杂的东西,但如果你需要它来给一个anwser我会马上添加它! (:

4 个答案:

答案 0 :(得分:0)

你是对的,你不能那样混杂。 php会立即执行,因为它不知道javascript并且将在运行时由服务器解释,而js将由浏览器解释。

一种可能的解决方案是使用js设置cookie并使用js重定向。或者,您可以让接收登录请求的服务器在登录请求成功时设置cookie,并让js在从服务器获得成功响应后执行重定向。

答案 1 :(得分:0)

你不能这样做,因为ajax请求进程在支持并返回特定的响应,如果你想存储cookie和重定向,那么你应该在javascript方面做到这一点,同时你得到响应成功

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class) 
        ->add('dateAdded', DateType::class, array(
            'data' => new \DateTime(),
        ))
    ;

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
        $product = $event->getData();
        $form = $event->getForm();

        if (!$product) {
            return;
        }

        if ($dateAdded = $product->getDateAdded()) {
            $form->add('dateAdded', DateType::class, array(
                'data' => $dateAdded,
            ));
        }
    });
}

答案 2 :(得分:0)

如果ajax响应满足您的重定向条件,您可以使用以下内容:

$.ajax({
    type: 'POST',
    url: 'validate.php',
    data: $this.serialize(),
    success: function(response) {
        var responseCode = parseInt(response);
        alert(codes[responseCode]);
        window.location="%LINK HERE%";
    }
});

你使用ajax来避免加载页面有点讽刺,但无论如何你都会在另一个页面中重定向。

答案 3 :(得分:0)

测试以json格式发送数据:

的Javascript

$.ajax({
   type: 'POST',
   url: 'validate.php',
   data: $this.serialize(),
   success: function(response) {
      if(response.success){
         window.location="%LINK HERE%";
      }else{
         var responseCode = parseInt(response.code);
         alert(responseCode);
         ...
      }
   }
});

PHP

header("Content-type: application/json");

if(empty($user)){
    echo json_encode(['success' => false, 'code' => 901]);
}else{
    if(hash_equals($user->hash, crypt($password, $user->hash))){
       echo json_encode(['success' => true, 'data' => response]);
    }else{
       echo json_encode(['success' => false, 'code' => 902]);
    }
}