Passing values from javascript to servlet not working in chrome - javascript

Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?

What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()

Related

How can Javascript account for returning a 500?

I am using a login form to construct and send a URL (that'd be the "full url" written to storage in the script below) that should return a JSON object.
If the login is correct, the back-end sends me a JSON object with a validation key in it to validate if it cam back successfully. (like this: [{"result":"VALID"}] )
If the login is incorrect, it only provides a 500 error.
Unfortunately, when it gets that 500 error, instead of booting them because the result isn't VALID, the script just gives up because there's no object to validate.
From the Front-End, how can I detect that I have received a 500 error and then trigger "bootThem()"?
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}
Please see below fiddle I have simulated a 500 response from Mock API and handlinkg it:
if (rawFile.readyState === 4 && ((rawFile.status === 200) || (rawFile.status === 500))) {
console.log("fired");
callback(rawFile.responseText);
}
https://jsfiddle.net/asutosh/vdegkyx2/8/
Okay so thanks to Asutosh for the push in the right direction, I was able to adjust my function to boot the user if a 500 error was returned from the JSON call, and allow the user to pass through if there was not.
This was exactly what I needed to handle the 500 error coming back form the JSON:
function bootThem() {
//execute code to reset session and return user to login page.
}
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.addEventListener('error', () => {
console.log("error code");
});
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && (rawFile.status === 500)) {
console.log("500");
bootThem();
callback(rawFile.responseText);
}
if (rawFile.readyState === 4 && (rawFile.status === 200)) {
console.log("200");
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}

How to send AJAX post request and receive back JSON data in Vanilla JS?

I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:
$('.frmSubmitData').on('submit', function(e){
e.preventDefault();
var formData = $('#myForm').serialize();
console.log(formData);
$.ajax({
type: 'POST',
encoding:"UTF-8",
url: 'Components/myTest.cfc?method=testForm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
console.log(obj.FORMDATA);
}else{
alert('Error');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
And here is what I have so far in plain JS:
function sendForm(){
var formData = new FormData(document.getElementById('myForm')),
xhr = new XMLHttpRequest();
xhr.open('POST', 'Components/myTest.cfc?method=testForm');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(formData);
}
I think that something is wrong in way how I handle response with JSON data. If anyone can help me with problem please let me know. Thank you.
Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:
function ajaxReq() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser does not support XMLHTTP.");
return false;
}
}
Then, send the request:
var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var obj = JSON.parse(xmlhttp.responseText);
// do your work here
} catch (error) {
throw Error;
}
}
}

Firefox onClick event does not work

I'm trying to debug a third party script.
It works fine in Chrome. But Firefox won't register the onclick event.
Any idea why FireFox won't play nice?
I tried adding return false; as suggested here but it did not work, adding that above the very last closing bracket just produces more errors when viewed in console.
function ac_event(event, eventdata) {
return ajax({
url: activecampaignevent.ajax_url,
type: 'POST',
data: {
action: 'ac_event',
event: event,
eventdata: eventdata
},
success: function (response) {
console.log('response', response);
}
});
function ajax(options) {
var request = new XMLHttpRequest();
var url = options.url;
var data = encodeData(options.data);
if (options.type === 'GET') {
url = url + (data.length ? '?' + data : '');
}
request.open(options.type, options.url, true);
request.onreadystatechange = onreadystatechange;
if (options.type === 'POST') {
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
} else {
request.send(null);
}
return;
function onreadystatechange() {
if (request.readyState === 4 && request.status === 200){
options.success(request.responseText);
}
}
function encodeData(data) {
var query = [];
for (var key in data) {
var field = encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
query.push(field);
}
return query.join('&');
}
}
}
Click this link to test
you can create event in javascript and assign it with browser event to stop with preventDefault.
document.querySelector("#LinkID").addEventListener("click", function(event){
//do your code here
alert("preventDefault will stop you to go")
event.preventDefault();
}, false);

Ajax response doesn't equal what I think it should

I'm trying to call a displayUsers function, if response equals "loggedIn" (response is coming from echo statement in php for ajax request). It always jumps straight to the else statement and doesn't execute displayUsers(). However, when I alert response it displays loggedIn.
Here is my code:
function ajaxRequest(url, method, data, asynch, responseHandler) {
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST") {
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
}
request.send(data);
}
//loginCheck
function loginCheck() {
var username = document.getElementById("usernameLogin").value;
var password = document.getElementById("passwordLogin").value;
var data="usernameLoginAttempt="+username+"&passwordLoginAttempt="+password;
ajaxRequest("../PHP/CODE/login_check.php", "POST", data, true, loginCheckResponse);
}
function loginCheckResponse(response) {
//check response, if it is "loggedIn" then call show users function
alert(response);
if (response == "loggedIn") {
displayUsers();
} else {
alert("Login Failed. Please try again.")
}
}
// response is an object which you get from ajex.
// You have not written how you call loginCheckResponse()
// call like loginCheckResponse(response.<variable which you return from service page>)
function loginCheckResponse(response)
{
//check response, if it is "loggedIn" then call show users function
alert(response);
if (response == "loggedIn") {
displayUsers();
} else {
alert("Login Failed. Please try again.")
}
}
Changed my code to:
//logged in
function loginCheckResponse(response) {
if(response.trim()=="loggedIn"){
displayUsers();
}
else{
alert("Login Failed. Please try again.");
}
}
It now works. Thanks for the help anyway people.

ajax error only first request is send

$('#show_mess').click(function (){
$('#dropdown_mess').slideToggle("slow");
$('#arrow_mess').slideToggle("slow");
$('#arrow_not').hide("slow");
$('#dropdown_not').hide("slow");
function recall(){ setTimeout(function () {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/ajax/mess_data.php", true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('dropdown_mess').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send();
document.getElementById('dropdown_mess').innerHTML = "<img class='non_auto' id='ajax_loading' src='img/ajax_loading.gif'></img>";
recall();
}, 2000);
};
recall();
});
this function works fine but when each ajax call is done i need to colse and re-oper chrome in order to work, works fine in firefox
You are already using Jquery so why don't you try it's ajax function like below
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
....
});
You can find more information on the manual

Categories

Resources