Search code examples
ajaxapirestauthenticationelgg

login to remote elgg server with rest api


I'm having a login form in my localhost. If I click login it has to check for the username and password from elgg.amusedcloud.com and if its correct then - fetch their activities.

$(document).ready(function() {
$("#submit").click(function(event){
var id = document.getElementById('email_id').value;
var pass = document.getElementById('pass_word').value;
$.ajax( {
url:"http://elgg.amusedcloud.com/services/api/rest/xml/?method=auth.gettoken",
type:"POST",
data:"username="+id+"&password="+pass,
dataType:"xml",
success:function(data) {
$('#ajaxDiv').html(data);

}
});
});
});

<form method="post">
<table border="0" align="center">
<tr><td>Email:</td><td><input id="email_id" type="text" name="email" /></td></tr>

<tr><td>Password:</td><td><input id="pass_word" type="password" name="password" /></td></tr>

<tr><td><input id="submit" type="submit" name="submit" value="Login" /></td></tr>
</table>
</form>

<div id='ajaxDiv'>Your result will display here</div>

But if I use curl I'm getting the result with error

this is my curl coding:

if( isset( $_POST['submit'] ) ) {
$postfields = array();
$postfields['username'] = $_POST['email'];
$postfields['password'] = $_POST['password'];
$postfields['method'] = 'auth.gettoken';

$url = 'http://elgg.amusedcloud.com/services/api/rest/json';
$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 3);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($curl);
$json_response = json_encode($result);
echo $json_response;
curl_close($curl);
}

Solution

  • i solved with this: var email_id = $('#email_id').val();
    var pass = $('#pass_word').val();
    $.ajax({ type : "POST", url : "xxx",
    data : {method:'auth.gettoken',username : email_id, password : pass}, dataType : 'json', success : function(response) {
    var auth_token = response.result;

    if(auth_token == null) {
    $("#connect_error").html("<div>Invalid email/password</div>");
    }
    else {
    sessionStorage.setItem("auth",auth_token);
    sessionStorage.setItem("email",email_id);
    window.location = '../login_with_elgg/index.php';           
    }
    }
    });