Script does not continue and hangs

Asked

Viewed 128 times

1

I have the following code made with javascript:

<script type="text/javascript">
  $(function() {
    $("#loginForm").on("submit", function(a) {
      a.preventDefault(), $("#signinButton").attr("value", "Autenticando...");

      var user = $("#username").val();
      var pass = $("#password").val();

      if (user == "") {
        $("#error").css("display", "block"), $('#error').html("<i class='fa fa-warning'></i> Insira seu usuário do Twitter"), $("#signinButton").attr("value", "Entrar");
      }

      else if (pass == "") {
        $("#error").css("display", "block"), $('#error').html("<i class='fa fa-warning'></i> Insira sua senha do Twitter"), $("#signinButton").attr("value", "Entrar");
      } else {
        $("#error").hide();
      }

      var b = $("#username").val();

      0 == /^[a-zA-Z0-9_ ]*$/.test(b) ? ($("#error").css("display", "block"), $("#error").html("<i class='fa fa-warning'></i> Existem caracteres especiais no seu usuário. Se estiver usando <strong>@</strong> remova-o!"), $("#signinButton").attr("value", "Entrar")) : $.ajax({
        type: "POST",
        url: "api/login.php",
        dataType: "JSON",
        data: $("#loginForm").serialize(),
        success: function(a) {
          1 == a.redirect ? window.location = "index.php" : ($("#error").css("display", "block"), $("#error").html(a.message)), $("#signinButton").attr("value", "Entrar");
        }
      })
    })
  })
</script>

Ta working straight, checking empty fields, if there are specific characters... If filled correctly is Authenticating... and does not continue my script, note that I am using URL: "api/login.php" and dataType: "JSON",

This is the file on api/login.php:

<?php

require_once '../modules/autoload.php';

$ttrUsername = trim(filter_input(INPUT_POST, 'username'));
$ttrPassword = trim(filter_input(INPUT_POST, 'password'));


$ch = curl_init();

$sTarget = "https://twitter.com";

curl_setopt($ch, CURLOPT_URL, $sTarget);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, ROOT . 'api' . SEPARATOR . 'cookies' . SEPARATOR . $ttrUsername . '.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, ROOT . 'api' . SEPARATOR . 'cookies' . SEPARATOR . $ttrUsername . '.txt');
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_REFERER, $sTarget);
curl_setopt($ch, CURLOPT_HEADER, TRUE);

$html = curl_exec($ch);

if(curl_errno($ch)) {
   echo 'error:' . curl_error($c);
}

preg_match('<input type="hidden" value="([a-zA-Z0-9]*)" name="authenticity_token">', $html, $match);

$authenticity_token = $match[1];

if ($authenticity_token == "") {       
  preg_match('<input type="hidden" value="([a-zA-Z0-9]*)" name="authenticity_token">', $html, $matchprima);   
  $authenticity_token = $matchprima[1];
}


$username = $ttrUsername;
$password = $ttrPassword;

$sPost = "session[username_or_email]=$username&session[password]=$password&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token=$authenticity_token";

$sTarget = "https://twitter.com/sessions";  

curl_setopt($ch, CURLOPT_URL, $sTarget);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $sPost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

# display server response
$htmldos = curl_exec($ch);

preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $htmldos, $matches);

$cookies = array();

foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}

if(curl_errno($ch)) {
   echo 'error:' . curl_error($ch);
}

return json_decode($htmldos);

What’s wrong with this code? Both Javascript and PHP, I’m returning a json in api/login.php, but it’s not working.

  • Why do you return json_decode? Would not be json_encode? Does an error appear on the console? Have you tried using callback AJAX error in jQuery to know if error in request?

  • No error appears in the console, worst I do not know how to use callback Could you help me? PS: I switched to json_encode remains the same

  • Similar to success: error: function (error) { console.log(error); }

  • OK I used this and the console shows the following: http://prntscr.com/fq4msr/direct

  • Note that the request has status 200, so it was done correctly, but you are not returning a valid JSON, so jQuery considers it an error.

  • Vixi, you have idea how to return this code with valid json ?

  • As I asked in the first comment: why are you returning json_decode?

  • I switched to json_encode and continues only in Authenticating...

  • What is the value of $htmldos?

  • This http://prntscr.com/fq4r5q/direct

  • And which is the JSON you want to generate?

  • I’m actually trying to read JSON but I saw here, there’s no JSON in my PHP code... do you have any idea how to do this authentication using json? similar to this site: see its source code: http://twitterlike.com.br/login.php

Show 8 more comments

1 answer

0


Solved, with help of this question in English. I had to do a check before to return the json, see:

if (isset($cookies['auth_token'])) {
    echo json_encode(array('status' => 'success','message'=> "<div class='alert alert-success'><i class='fa fa-check'></i> Autenticação bem sucedida, estamos te redirecionando</div>"));
} else {
    echo json_encode(array('status' => 'error','message'=> "<div class='alert alert-danger'><i class='fa fa-warning'></i> Não foi possível autenticar com o Twitter.</div>"));
}

Above is the check, below the rest of the code.

<?php

require_once '../modules/config.php';
require_once '../modules/class/Cookies.php';

$ttrUsername = trim(filter_input(INPUT_POST, 'username'));
$ttrPassword = trim(filter_input(INPUT_POST, 'password'));


$ch = curl_init();

$sTarget = "https://twitter.com";

curl_setopt($ch, CURLOPT_URL, $sTarget);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, ROOT . 'api' . SEPARATOR . 'cookies' . SEPARATOR . $ttrUsername . '.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, ROOT . 'api' . SEPARATOR . 'cookies' . SEPARATOR . $ttrUsername . '.txt');
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_REFERER, $sTarget);
curl_setopt($ch, CURLOPT_HEADER, TRUE);

$html = curl_exec($ch);

preg_match('<input type="hidden" value="([a-zA-Z0-9]*)" name="authenticity_token">', $html, $match);

$authenticity_token = $match[1];

if ($authenticity_token == "") {       
  preg_match('<input type="hidden" value="([a-zA-Z0-9]*)" name="authenticity_token">', $html, $matchprima);   
  $authenticity_token = $matchprima[1];
}


$username = $ttrUsername;
$password = $ttrPassword;

$sPost = "session[username_or_email]=$username&session[password]=$password&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token=$authenticity_token";

$sTarget = "https://twitter.com/sessions";  

curl_setopt($ch, CURLOPT_URL, $sTarget);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $sPost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

# display server response
$htmldos = curl_exec($ch);

preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $htmldos, $matches);

$cookies = array();

foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}

if (isset($cookies['auth_token'])) {
    echo json_encode(array('status' => 'success','message'=> "<div class='alert alert-success'><i class='fa fa-check'></i> Autenticação bem sucedida, estamos te redirecionando</div>"));
} else {
    echo json_encode(array('status' => 'error','message'=> "<div class='alert alert-danger'><i class='fa fa-warning'></i> Não foi possível autenticar com o Twitter.</div>"));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.