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;
Related
Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").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("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.
I am trying to get a value back through if it found value in database sends/echo result value in it does found sends back/echo 'not_found'.
When I try to compare in the following script it always goes inside if, and never goes to else.
I also tried NULL, FALSE instead not_found does not work.
function showHint(str) {
var xmlhttp;
var url= "check_album.php?q="+str;
document.getElementById("txtHint1").innerHTML=(url);
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) {
if(xmlhttp.readyState.responseText !='not_found') {
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else {
document.getElementById("txtHint3").innerHTML='no result';}
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
and this is check_album.php code which sending result back
require_once('../php/classes/class.add_album.php');
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$album_name = $_GET["q"];
//make new object
$objfile = new add_album();
//call object method with post method value we got and save result in result
$file_found=$objfile->find_album($album_name);
if ($file_found)echo $file_found;
else echo 'not_found';
}
Try this.
if(xmlhttp.responseText !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else
{
document.getElementById("txtHint3").innerHTML='no result';
}
This is because response text may have unwanted spaces Try to trim that response
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
if(xmlhttp.responseText.trim() !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
}else{
document.getElementById("txtHint3").innerHTML='no result';
}
This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 8 years ago.
I'm sending a string via xmlhttp in javascript using the following code:
function SendPHP(str, callback) {
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) {
callback(xmlhttp.responseText); //invoke the callback
}
}
xmlhttp.open("GET", "testpost.php?q=" + encodeURIComponent(str), true);
xmlhttp.send();
}
and some test php:
$q = $_GET['q'];
echo $q;
That worked fine until I started sending a larger string in which case I get the "HTTP/1.1 414 Request-URI Too Long" error.
After a bit of research I found out I need to use "POST" instead. So I changed it to:
xmlhttp.open("POST", "sendmail.php?q=" + str, true);
And:
$q = $_POST['q'];
echo $q;
But this does not echo anything when using POST. How can I fix it so it works like when I was using GET but so it can handle a large string of data?
edit I'm now trying it with:
function testNewPHP(str){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
You should not provide your href with URL parameters, instead of this you should send() them. For addition, you should always encode your parameters with encodeURIComponent() (At least when your request is using the Content-type "application/x-www-form-urlencoded").
your javascript function :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
javascript :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
testpost.php in your home directory :
<?php
var_dump($_POST);
OUTPUT :
array(1) {
["q"]=>
string(12) "This is test"
}
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();
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.