problem with jquery post data to jsp page - javascript

I have the following html page Index.html , script.js and calculate.jsp file when i run the html page and hit submit button using tomcat server it gives error saying calculate.jsp file not found .Is their any syntax problem in the javascript file to call the jsp page .
<html>
<head>
<title>Simple jQuery and JSP example</title>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script src="SCRIPT.js" type="text/javascript"></script>
</head>
<body>
<form id="form" action="calculate.jsp" method="post">
Enter number:
<input id="number" type="text" name="number" />
<input id="submit" type="submit" value="Calculate Square Root" name="submit"/>
</form>
<p id="result"></p>
</body>
</html>
Javascript file SCRIPT.js
$(document).ready(function() {
$('#form').submit(function() {
var number = $('#number').val();
$.ajax({
type: "post",
url: "calculate.jsp",
data: "number=" + number,
success: function(msg) {
$('#result').hide();
$("#result").html("<h3>" + msg + "</h3>")
.fadeIn("slow");
}
});
return false;
});
});
calculate.jsp
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
int number = 0;
if(request.getParameter("number").matches("[\d]+")) {
number = Integer.parseInt(request.getParameter("number"));
out.println("Square root of " + number + " is " + Math.sqrt(number));
}
else {
out.println("Enter a number!");
}
%>

Here are some steps you can do to find out what is going wrong :
Add a console.log("submitting the form") at the first line in $('#form').submit function.
Add another print console.log("got message") in the "success" callback.
You can use chrome, Firefox+Firebug or IE 8 and above for this.
I usually use chrome and my following instructions refer specifically to chrome as it is easiest with it.
Click ctrl+j in chrome to open the developer's panel.
Go to 'Network'.
Reload "index.html" (your main page)
Make sure there are no errors displayed in the console below. ( if there are please post them here or handle them).
Assuming there are no errors : you should see your print "submitting the form" and a network call to "calculate.jsp" on the developers panel.
you can click on it to see the details - see the URL you are actually requesting for. is this the URL you expected?
Copy paste the URL you see and copy it on a new tab. This will give you a sufficient workspace to handle any problems on that page.
The above steps should give you sufficient clues as to what is the problem and how to resolve it.
In order to verify that your code is working properly - you should see your "got message" print and the content in the HTML from calculate.jsp.
I also recommend opening the network and verifying that the response you get from "calculate.jsp" is correct.
let me know if you experience any new problems.

Related

PHP/HTML, AJAX is not calling/executing PHP file

Before I opened this question, I searched the entire internet on a solution. Maybe it is me or my solution. Sorry for that.
The situation is, I have a web app which is build with PHP and interacting with the database through functions. Every page is a php in which html code is executed.
The problem is, when I want to implement Ajax to update data without refreshing a page, the PHP file is not being executed when the button is clicked.
The javascript has two functions:
Alert serialized data of the button (works)
Run php script with Ajax (doesn't work)
Html Header
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
Im using bootstrap-table, one of the column is a button which has the following content:
<form id="form" class="favourite-form" method="post"><input style="display:none" type="hidden" id=5 name="subject_id" value=5 ><input type="submit" name="submit" value="Button"></form><div id="response"></div>
When clicked on the button the following alert is popping up:
The script file is included in the php file:
include("favorite_ajax.html");
The script file has the following content:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var data = $(this).serialize(); //"this" represents the form element in this context
alert(data); // this alert works
$.ajax({
method: "POST",
url: "process.php", // calling this php file doens't work
data: data,
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown) //gracefully handle any errors in the UI
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
Finally the php file has one single simple function which inserts (dummy) data. The php file is tested and does not contain any errors.
<?php
insertDummyData(1, 123);
?>
In another topic I also read checking the logs. When I press the button, there is also no record being added in the logs.
Im cursious, what am I doing wrong? Spend like days to fix this, until now no results :(
put an error log in "process.php" to make sure that it's actually being called, if it's not being called, as others suggest, you may have path, permissions or script errors.
what does insertDummyData/process.php actually do? It must echo something as if it were writing to the page for the AJAX call to get a non-empty result. For example, in process.php
<?php
$new_data = my_function_which_does_stuff_to_posted_data($_POST['data']);
echo json_encode($new_data);
exit();

I am having issues with an external JS file

I am new to JavaScript. I have an external js file linked to a page, but its just not working. I don't know the line i went wrong in the js file. Help, please
function show_alert()
{
alert("Hello! I am an alert box!");
}
<input type="button" onclick="show_alert()" value="Show alert box" />
This is the code i used to link the file
<head>
<script type="text/javascript"
src="js\popup.js"></script>
</head>
First check the console in the Developer tools of your browser for any errors ( use F12 or Ctrl + Shift + I to open dev tools). If there's no error in the console, then check if the file path you stated is present in the directory you are.

Chrome extension form input text is blank on submit

I'm trying to build a chrome extension that downloads a bunch of items from links, the main logic is in my download.js file and I want to be able to specify in which downloads subfolder I'd like to bundle them all but the value of the input field seems to be empty. Here's my code so far
popup.html
<!doctype html>
<html>
<head>
<title>Download CVs</title>
<script src="popup.js"></script>
</head>
<body>
<form id="folderForm">
Subdir of downloads:
<input type="text" id="folder">
<input type="submit" id="download" value="Download CVs">
</form>
</body>
</html>
popup.js
function bundleItems() {
chrome.tabs.executeScript({
file: 'download.js'
});
}
document.addEventListener('DOMContentLoaded', function() {
var downloadButton = document.getElementById('download');
downloadButton.addEventListener('click', bundleItems);
});
chrome.extension.onRequest.addListener(function(logs) {
var folder = document.getElementById('folder').value;
logs.map(function(log) {
chrome.downloads.download({
url: log.attachment.link,
filename: folder + '/' + log.attachment.filename
});
});
});
I'm sending information from download.js to popup.js and everything works if I try to download it in downloads, so I feel posting my download.js file will be useless. However, if I try to display the folder variable, it's empty. I've searched for lots of other posts on the same issue and none of the solutions seem to work for me.
You cannot submit to a Chrome extension page. There is no web server to process your POST request in this case. Doing so simply reloads the document (clearing your value from the form).
You need to prevent submitting instead, by specifying type="button" for your button.
I would add preventDefault() on submit button.
https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Automate Log In on Website (Autofill and Submit)

I am trying to visit a website and log in automatically.
After this, I want to return whether or not this was a success or failure, but I can't get it to work. The page loads blank and nothing happens.
Note: I have deliberately greyed out the URL.
Below is my attempt,
<HTML>
<HEAD>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<TITLE>Login</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
<script type="text/javascript">
$(document).ready(function () {
runLogin();
});
function runLogin(){
alert("start");
if (window.location.indexOf("url") > -1) {
jQuery("#j_username").val("username");
jQuery("#j_password").val("password");
jQuery("#loginForm").submit();
}
}
</script>
If you want to test your login form, use Protractor or other e2e test framework, but this way does not seem very safe.
http://angular.github.io/protractor/
It's loading a blank page because your back-end script isn't redirecting back to the page you started on. One option is to send the current webpage URL as an extra field to the login form so that it can redirect back after it has logged in. This will require you to refactor your back-end code so that it can handle this extra information (not really possible if you're using j_security_check). Another option is to make an AJAX request to your login page so that it doesn't actually redirect the page, it just submits the form quietly and then JS handles the response.
If you want to add the URL of the current page to the login request, do this:
function runLogin() {
if (window.location.indexOf("url") > -1) {
jQuery("#j_username").val("username");
jQuery("#j_password").val("password");
jQuery("#loginForm").append(
'<input type="hidden" name="url" value="'+window.location.href+'"/>'
);
jQuery("#loginForm").submit();
}
}
If you want to use AJAX to send a login request:
function runLogin() {
var $form = $("#loginForm");
$.post($form.attr("action"), $form.serialize(), function(data) {
// login successful/unsuccessful message displays
// depending on what "data" contains
});
}

AJAX wait until file exist on another server

I'm developing a website based in to servers. One is a free host and another is a Raspberry Pi. When you access a webpage in the free host, you get a form where you enter a link. The link is send to the Raspberry Pi which is permanently running a script that downloads some content of the link recieved and saves a big txt file. The script takes a bit to load (30 secs aprox) so I want to create a Javascript script in the primary page (free host one, with the form) wich shows a load icon and checks in the raspberry downloads folder until the file exists.
I think AJAX will be the best for this. The workflow is:
user access form.php and enters a link
the form is send directly to the RPi
the RPi begins to download things and returns the user to the refferrer page with the get parameter id=
here the ajax code begins to work checks into an url if .txt exists if it exists, it shows the download link else, it waits checking until it gets a 200 status code (This is what i need)
I know the problem with javascript and different servers so i've created a php script named check.php in the same server and folder of form.php which gets id as parameter and return 200 or 404 so the ajax code just needs to get that answer and act in consecuence
How can I do it? I'm new to AJAX, I know just a bit of Javascript. Could you help me withe the AJAX code?
My form.php?id= page:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>downloader</title>
</head>
<body>
<div id="content">
<?
if (!$_GET){
?>
<form action="<<rpi server>>" method="post">
URL: <input type="text" name="link">
<input type="submit" value="Download">
</form>
<?
}else{
?>
<script>
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'<? echo $_GET['id']; ?>'},
//check if response is 200 or 404, if it's 404 keep checking every second, else show mesage
}
});
</script>
<?
}
?>
</div>
</body>
</html>
Use this
function checkFile()
{
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'999'},
error : function(){
setTimeout(function(){ checkFile(); }, 3000);
},
success : function(data) {
//do whatever you want
}
});
}
$(function() {
checkFile();
});

Categories

Resources