HTTP login API authentication by using javascript? - javascript

function login1() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var url = "http://agero-dev.apigee.net/v1/id/auth/login";
var http = getHTTPObject();
if (http.status == 200 ) {
this.http.open("post", url, false, user, pass);
this.http.send("");
document.location = job-list.html;
} else {
alert("Incorrect username and/or password!");
}
return false;
}
function getHTTPObject() {
var xmlhttp = false;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
Please look at the above code, while giving wrong username and password, it showing an alert, but while using correct login, it doesnt redirecting to job-list.html page, please advice?

You can use readyState to check whether response is ready.
http.onreadystatechange=function() {
if (http.status == 200 && http.readyState == 4) {
.... //your code
window.location = job-list.html;
}
}
http.open("post", url + '?user=' + user + '&pass=' + pass, true);
http.send();

Related

ajax.responseText to paragraph

I have a search form where when someone enters the salary(which is unique in my case), it returns the corresponding values from the database. I am using ajax to do that, i have managed to retrieve the value in input fields. I have an onchange event on my input text which calls in "UpdateCityState"
I would like to show the values inside paragraphs and not input field.
<p id='employee_name'></p>
<p id='employee_age'></p>
<p id='safe_code'></p>
<script>
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var employee_salary = document.getElementById("employee_salary").value;
if(employee_salary)
{
var param = "?employee_salary=" + employee_salary;
var url = "test04.php";
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
var employee_name = document.getElementById('employee_name');
var employee_age = document.getElementById('employee_age');
var safe_code = document.getElementById('safe_code');
if(!!ajax.responseText) {
var result = JSON.parse(ajax.responseText);
if(!!result){
employee_name.value = (!!result.employee_name) ? result.employee_name : '';
employee_age.value = (!!result.employee_age) ? result.employee_age : '';
safe_code.value = (!!result.safe_code) ? result.safe_code : '';
}
}
}
}
I tried replacing employee_name.value with employee_name.text but no luck
If you replace value with innerHTML everything should work.

Ajax calls in symfony framework

I wanna make ajax calls in symfony2. I already done with ajax with flat php and i have no idea how to set up in this symfony framework.
<html>
<head>
<script>
function showBook(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showAuthor(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAuthor.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="">
Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)">
<br><br>
Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)">
</form>
<br>
<div id="txtHint"><b>book info will be listed here...</b></div>
</body>
</html>
Where should i pass this request?? to controller??
how to set routes??
is there any way to use flat php instead of controller??
You would pass the request to a controller action exposed using a route:
http://symfony.com/doc/current/book/routing.html
Then in your html code, if you are using twig and including javascript in a script tag, you can do
xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}");
If you want to access the route in an attached .js file, you can use FOSJsRoutingBundle to generate the route url
If you are in a form, you can do something like :
$(document).submit(function () {
var url = $('form').attr('action');
var data = $('form').serialize();
$.post(url, data, function (data) {
window.location.href = data.redirect;
})
.fail(function () {
$('form').replaceWith(data.form);
});
});
You just need to send the correct url :
$(document).on('click', 'a', function () {
var url = window.location.href;
$.get(url, function (data) {
$('.container').replaceWith(data);
});
});
It is also possible to use a routing generate, simply add:
"friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.
AppKernel.php :
new FOS\JsRoutingBundle\FOSJsRoutingBundle()
Then config it in your routing.yml :
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
And finally use "expose" arg in your routing :
#Route("/{table}/index", name="beta.index", options={"expose"=true})
I use annotation routing
In your JS :
var url = Routing.generate('beta.index', { 'table': 'foo' });
Hope it'll help you :)

validate multiple ajax call complete successfully in javascript

In my application i'am making two ajax call for getting some data from database based on another variable value.
code part:
var xmlHttp;
var redirect;
function populate_site(obj, passedselect) {
xmlHttp = GetXmlHttpObject();
var site_type;
if (obj.value) {
site_type = obj.value
}else {
site_type = document.app.site_type.value;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Get_Site_List";
url=url+"&site_type=" + site_type;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged() {
if (xmlHttp.readyState == 4){
document.getElementById('site_id').innerHTML = xmlHttp.responseText;
}
}
function Populate_Process_List(obj, process_id_param) {
var action_id;
if (obj.value) {
action_id = obj.value
}else {
action_id = document.app.action_id.value;
}
xmlHttp = GetXmlHttpObject();
if (obj.value == '') {
document.getElementById('process_id').innerHTML = ' ';
return false;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Fetch_User_Process_List";
url=url+"&action_id=" + action_id;
url=url+"&process_id=" + process_id_param;
url=url+"&gp_flag=" + 'YES';
xmlHttp.onreadystatechange= Process_Data_StateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function Process_Data_StateChanged() {
if(xmlHttp.responseText != 'NA') {
if (xmlHttp.readyState == 4){
document.getElementById('process_id').innerHTML = xmlHttp.responseText;
}
}
}
function GetXmlHttpObject(){
var xmlHttp1=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp1=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp1=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp1;
}
And validating site_id and process_id variable using JavaScript.
Problem facing is whenever user press the submit button before ajax call loading is not completed (since me passing async parameter of the open() method has as true). Even while validating the site_id and process_id variable using JavaScript is not getting captured.
Validation code:
var siteaddindex = document.app.site_id[document.app.site_id.selectedIndex].value;
if(siteaddindex == "null"){
alert("Please select site location.");
document.app.site_id.focus();
return false;
}
var process_id = document.app.process_id.value;
if (process_id == '') {
alert("Please select process");
return false;
}
Please let me know how to perform validation of above fields, since those fields are mandatory.

Javascript does not return servlet response

I have wriiten welcome screen which basically use below javascript to call creditCheck servlet. Within servlet, there is method which will check the username and password. Servlet returns value properly. alert is not getting generated after servlet excutation within javascript.
however if execute simple servlet ( not doing anything, just printing variables), it will generate alert.
below is my javascript within JSp file:
############################################
<script type="text/javascript">
function getXmlHttpRequestObject(){
var xmlHttp = false;
if (window.XMLHttpRequest){
return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safari
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP"); // For the browsers IE6, IE5
}
else {
alert("Error due to old verion of browser upgrade your browser");
}
}
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost() {
if(xmlhttp) {
var username = document.getElementById("uname");
var password = document.getElementById("pass");
xmlhttp.open("POST","CredCheck",true);
xmlhttp.onreadystatechange = handleServletPost;
req.onreadystatechange = callback;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("uname=" + username.value + "&pass=" + password.value );
}
}
function handleServletPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Ajax calling error");
}
}
}
</script>
#
I have changed xmlhttp.open("POST","CredCheck",true); to
xmlhttp.open("POST","CredCheck",false);
xmlhttp.onreadystatechange = handleServletPost;

How can I re-write this code without jQuery?

How can I rewrite this code without using jQuery? I need to do it in a mobile app where I can't use jQuery.
$.ajax({
type: "POST",
url:"../REST/session.aspx?_method=put",
data: JSON.stringify(dataObject, null,4),
cache: false,
dataType: "json",
success: onSuccessLogin,
error: function (xhr, ajaxOptions){
alert(xhr.status + " : " + xhr.statusText);
}
});
You can try this:
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
// What you want to do on failure
alert(xmlhttp.status + " : " + xmlhttp.responseText);
 }
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// What you want to do on success
onSuccessLogin();
}
}
xmlhttp.open("POST", "../REST/session.aspx?_method=put", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Cache-Control", "no-cache"); // For no cache
xmlhttp.send("data=" + JSON.stringify(dataObject, null,4));
As for how to do more stuff with only javascript without jQuery library take a look at W3Schools AJAX Tutorial or Mozilla - Using XMLHttpRequest
And as duri said, you will have to find a way to convert dataObject to string, as not all browsers support JSON object.
try this
var xmlHttp = createXmlHttpRequestObject();
//retrieves the xmlHttpRequest Object
function createXmlHttpRequestObject()
{
//will store the refrence to the xmlHttpRequest Object
var xmlHttp;
//if running in internet explorer version below 7
if(window.ActiveXObject)
{
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = false;
}
}
else
{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error Creating the xmlHttpObject");
else
return xmlHttp;
}
function callThisFunction()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
var queryString = JSON.stringify(dataObject, null,4);
var url = "../REST/session.aspx?_method=put";
xmlHttp.open("POST", url, true);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", queryString.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = checkHandleServerResponse;
xmlHttp.send(queryString);
}
}
function checkHandleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var JSONFile = 'jsonFormatData = '+xmlHttp.responseText;
eval(JSONFile);
if(jsonFormatData.description == 'Success')
{
//showDialog('Success','Login Successful','success',3);
location.href='default.aspx';
//setTimeout(function(){location.href='myGrupio.php';},3000);
}
else
showDialog('Error','You Need a Valid Login.','error',3);
}
else if(xmlHttp.status == 400)
{
setTimeout( function()
{
alert('you have error');
},3000);
}
else
alert("Error Code is "+xmlHttp.status)
}
}
For the Ajax request itself, have a look at the XMLHttpRequest object (special treatment for IE).
To parse the JSON response (dataType: 'json'), use JSON.parse (you might need the json2.js library).
jquery is already javascript. It's a library, entirely written in javascript. So you can use it within every javascript project. If you want to write a rest client yourself, you might look at this article
You may also consider using jQuery Mobile edition - very light - 17KB minified. 1.0 is alpha now, but I think it will be more stable and portable than self-baked code.

Categories

Resources