I am trying to get data from an html form using jquery. I have tried the following but for some reason when I tried to log the data in the console, I keep getting null. What could I be doing wrong ? I want to send the data captured from my form in json format to my servlet. Thanks
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.vertical-menu {
width: 200px;
}
.vertical-menu a {
background-color: #eee;
color: black;
display: block;
padding: 12px;
text-decoration: none;
}
.vertical-menu a:hover {
background-color: #ccc;
}
.vertical-menu a.active {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<form id="register">
<div class="vertical-menu">
</div>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<br>
<input type="submit" id="check" name="check" value="Insert">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var d = $('register').serialize();
console.log("d",d);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType: "text",
contentType: "application/json",
data:d,
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
</script>
</body>
</html>
You forgot to give proper selector:
register is the ID of the form so;
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var d = $('#register').serialize(); // You had missed # here.
console.log("d",d);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType: "text",
contentType: "application/json",
data:d,
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
// Handle submit action on the forms.
$('#register').on('submit', function(e) {
// Prevent the browser to submit the form (we want to do it manually)
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
console.log(data);
// POST request to server
$.ajax({
url : "URL/TO/SERVER",
type : "POST",
data : data,
// other fields you need
});
});
I think that this is a proper way to achieve what you need. Don't forget to add the event argument to your callback function.
Related
I need to store data in server-side.I tried to make an Ajax call to PHP:
upload.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<style>
#test{
padding:20px 50px;
background:#ccc;
color:#000;
}
</style>
<script>
$(function(){
$('#test').click(function(){
$.ajax({
url: "http://localhost:8012/myFolder/upload.php",
type : 'POST',
data: {"foo": "bar"},
processData: false,
contentType: 'application/json'
});
});
});
</script>
</head>
<body>
<button id="test">KLICK</button>
</body>
</html>
upload.php:
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fwrite($fh,$_POST['data']);
fwrite($fh,$_POST['foo']);
fwrite($fh,$_POST["foo"]);
fwrite($fh,$_POST[foo]);
fclose($fh);
?>
but It doesn't work.The data is not wrriten to testFile.txt.
I will appreciate your help.
Thanks in advance.
No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least.
If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone.
If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want cookies.
Updated:
Below is a simple code that you are looking for. There is a simple form with four fields. On clicking of submit, it calls the server file and that PHP file will have the code to write the data to a file.
$("#submit").click(function(){
var paramsToSend = {};
var i = 1;
$("input[name='myanswer[]']").each(function(){
paramsToSend[i] = $(this).val();
i++;
});
$("#dataToSend").html(JSON.stringify(paramsToSend));
$.ajax({
type: "POST",
url: 'URL_HERE/post.php',
data: {params:JSON.stringify(paramsToSend)},
success: function(data) {
console.log("SUCCESS!!!");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputsl">
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
</div>
<button id="submit">
Submit
</button>
<div id="dataToSend"></div>
PHP code can be:
file_put_contents('filename.txt', $_POST['params']);
I have a script given to me by another developer to send push messages to my Apps.
I want to be able to send them from one page to both App types but cannot figure how.
Problem is I do not have any control over the pages on the server they are sent to.
If you look at the code the only differences in the two critical pieces of code are the Form action to send them to each Server page and the name of the App Id's...the other info remains the same.
I also found a piece of javascript to submit to two places from one button but could not get it working with both...
I know from reading that I probably need an array...Could someone please show me some code with these in an array with a submit button to send them to their respective pages.
Thanks in advance...
EDITED
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../../ScriptLibrary/jquery-latest.pack.js"></script>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<form name="push" method="post" >
<input name="pushmessage" type="hidden" value="HAIR EXTENSIONS ">
<p align="center">Notification Message:<br />
<textarea style="width: 280px; height: 150px; margin-bottom: 30px; font-family: Verdana, Geneva, sans-serif; border-color: #000; border- width: 1px; resize: none;" name="pushmessage" id="push-message"> </textarea><br />
<input type='button' class="inputbtn" name='Submit' value='Push' onclick='sendFormData()' />
<form/>
<script type="text/javascript">
function sendFormData() {
var formURL1 = 'http://apple/iPhone-message';
var formURL2 = 'http://google/android-message';
var postData1 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','appid':' CommunityApp-i','topics':'test'};
var postData2 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','ap pid':'CommunityApp','topics':'test'};
submitForm(formURL1, postData1);
submitForm(formURL2, postData2);
};
function submitForm(formURL, postData) {
$('#push-message').append('sending data to url : '+formURL+'\n');
$.ajax(
{
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$('#push-message').text('success');
},
error: function (jqXHR, textStatus, errorThrown) {
$('#push-message').append('oops:error occured'+errorThrown+'\n');
}
});
}
</script>
</body>
</html>
You should not use native submit button (that triggers a page change) but use a ajax submit method using XHR object.
You can take a look to this jquery plugin: http://jquery.malsup.com/form/
you dont need to html form tag, you can do that with this piece of this code:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<form name="push" method="post" >
<input name="pushmessage" type="hidden" value="HAIR EXTENSIONS ">
<p align="center">Notification Message:<br />
<textarea style="width: 280px; height: 150px; margin-bottom: 30px; font-family: Verdana, Geneva, sans-serif; border-color: #000; border- width: 1px; resize: none;" name="pushmessage" id="push-message"> </textarea><br />
<input type='button' class="inputbtn" name='Submit' value='Push' onclick='sendFormData()' />
<script type="text/javascript">
function sendFormData() {
var formURL1 = 'http://apple/iPhone-message';
var formURL2 = 'http://google/android-message';
var postData1 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','appid':' CommunityApp-i','topics':'test'};
var postData2 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','ap pid':'CommunityApp','topics':'test'};
submitForm(formURL1, postData1);
submitForm(formURL2, postData2);
};
function submitForm(formURL, postData) {
$('#push-message').append('sending data to url : '+formURL+'\n');
$.ajax(
{
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$('#push-message').text('success');
},
error: function (jqXHR, textStatus, errorThrown) {
$('#push-message').append('oops:error occured'+errorThrown+'\n');
}
});
}
</script>
I am using the following code and I need to access the input value of the form textbox from php. The form is not submitted to server directly through the form tag. The button is calling a JS function. I need to access the input textbox called stName from the php code. How can I pass this info to php and access it from there? Thank you.
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.4.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script charset="utf-8" type="text/javascript">
function connect()
{
$.ajax({
url:'hostname/reply.php',
headers:{"Content-Type": "application/json"},
type:'POST',
data:$(this),
dataType:'JSON',
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
</script>
</head>
<body>
<center><b>My Students</b></center>
<center>
<form method="POST">
<input type="text" value="John" name ="stName" />
<input onclick="connect()" type="button" value="showStudents" />
</form>
</center>
<center><b>Results</b></center>
<ul data-role="listview" id="result"></ul>
</body>
</html>
serialize the form data ..
change your connect function to this
function connect()
{
$.ajax({
url:'hostname/reply.php',
headers:{"Content-Type": "application/json"},
type:'POST',
data:$('form').serializeArray(),
dataType:'JSON',
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
or simply you can compress your code like this ..
function connect()
{
$.post('hostname/reply.php', $('form').serialize(), function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
You need to use the Sterilize Function. data:$( "form" ).serialize()
For Reverence to the function: http://api.jquery.com/serialize/
I also just found this StackOverflow that talks about how to structure the ajax request if you are having problems. Submit form using AJAX and jQuery
I am developing an MVC application with razor syntax.
I am developing the partial class for commenting feature.
I have code in which disply output of comments in following pattern.
John Smith 15-Aug-2012
-------------------------------
Called Customer today, hold me to call later.
Will Parkar 15-Aug-2012
-------------------------------
Keep track with him.
*Add New Comment in below text box.*
___________________________________________
|Called Again... |
| |
|___________________________________________|
Add Comment Clear
Now, whenever user put the comment in text box , that text should added in above list...
out put should be
John Smith 15-Aug-2012
-------------------------------
Called Customer today, hold me to call later.
Will Parkar 15-Aug-2012
-------------------------------
Keep track with him.
John Smith 16-Aug-2012
-------------------------------
Called Again... <---------------------New Comment get added here.
*Add New Comment in below text box.*
___________________________________________
| |
| |
|___________________________________________|
Add Comment Clear
I have below code...
#model IEnumerable<CRMEntities.Comment>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!DOCTYPE html>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function clearText()
{
document.getElementById('Comment').value = "";
}
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$('#AddCommentButton').click(function () {
$.ajax({
type:'post',
url: '/Comment/SaveComments', //url to your action method
dataType: 'json',
data: { 'comments': $('#Comment').val() },
success: function(data)
{
$('#ParentBlock').appendChild("<div>" + data.msg + "</div>");
}
});
});
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".ShowComments").click(function () {
$(".ParentBlock").slideToggle("slow");
$("CommentP").append(document.getElementById('Comment').value);
});
});
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".ShowComments2").click(function () {
$(".1").append("<strong>Hello</strong>");
});
});
</script>
<style type="text/css">
div.ParentBlock
{
position:relative;
display:none;
}
#ClassPara
{
position:relative;
background-color:#ECF5FC;
cursor:pointer;
border:2px;
width: 115px;
border-style:solid;
border-width:thin;
border-color: #DCEDF8;
}
<style type="text/css">
#OwnerName
{
background-color : #F0F6FF;
font-style:normal;
font-family:Calibri;
}
#CommentTextBlock
{
background-color : #F9F9FF;
}
#EmpName
{
font-style:normal;
font-size:medium;
}
#Clear
{
text-decoration:underline;
cursor:pointer;
color:Blue;
}
#AddComment
{
text-decoration:underline;
cursor:pointer;
color:Blue;
}
</style>
</head>
<body>
#{
<p id="ClassPara" class="ShowComments" >Show Comments</p>
<div class="ParentBlock">
#foreach (var item in Model)
{
<div id="OwnerName">
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
</div>
#* <div id="CommentTextBlock">
#Html.DisplayFor(ModelItem => item.CommentText)
</div>*#
<p class="CommentP">
#Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
}
</div>
#Html.TextArea("Comment", "", 5, 80, "asdsd")
<input type="button" value="Add Comment" id="AddCommentButton"/>
<input type="button" value="Clear" onclick="clearText()"/>
<br />
#* <label id="AddComment">Add Comment</label>
<label id="Clear" onclick="clearText()">Clear</label>*#
}
</body>
</html>
How to do this ?
On click of ADD Comment button post that comment to your action to save it to Database or wherever you want to save, and then return that comment in call back function of ajax to show it on page.
$('#addCommentButtonID').click( function() {
$.ajax({
type:'post',
url: 'SaveComments' //url to your action method
dataType: 'json',
data: {'comments':$('#textboxId').val()},
success: function(data)
{
$('#yourMainDiv').appendChild("<div>"+data.msg+"</div>");
}
});
});
Second way :
$('#addCommentButtonID').click( function() {
$.post('SaveComments',comments:$('#commentTextbox').val(),
function (data) {
$('#yourMainDiv').appendChild("<div>"+data.msg+"</div>");
},'json');
});
Your Action
public JsonResult SaveComments(string comments)
{
// save it wherever you want
// after saving success return this string as jsonresult
return Json(new { sc = true, msg = comment });
}
I have commended out the problem lines so show the working code:
<%# Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnGet').click(function() {
get_conflicts( $("#txtValue").val() );
});
$("#txtValue").live('keyup', function()
{
if ($("#txtValue").val().length > 3) {
get_conflicts( $("#txtValue").val() );
} else {
$("#divResults").empty();
}
});
function get_conflicts( phrase ) {
$.ajax({
type: 'POST',
url: 'conflict.asmx/GetConflicts',
data: '{phrase: "' + phrase + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
beforeSend: function() {
$('#spanLoading').empty().append("<img src='/img/loading.gif' />");
},
success: function( conflicts ) {
$("#divResults").empty();
if( conflicts.d[0] ) {
$.each( conflicts.d, function( index, conflict ) {
$("#divResults").append( conflict.Group + ':' + conflict.Count + '<br />' );
});
} else {
alert( "null" );
}
},
complete: function() {
$('#spanLoading').empty();
},
error: function(xhr, status, error) {
$('#spanLoading').empty();
var err = eval("(" + xhr.responseText + ")");
alert(err.Message) ;
}
});
}
});
</script>
</head>
<body>
<form id="form1" runat="server"></form>
<input type="button" id="btnGet" value="Get" /><br />
<input type="text" id="txtValue" /> <span id="spanLoading" /><br />
<div id="divResults" />
</body>
</html>
Why does this code stop printing results to the screen if I uncomment the first commended out line?
these are for global settings. all ajax call show an loading image.
$(".loading").ajaxStart(function () {
$(this).delay(500).slideDown(200);
});
$(".loading").ajaxComplete(function () {
$(this).delay(500).fadeOut(200);
}
<div class="loading" style="display: none">
<div>
<img src="/img/loading.gif" title="Loading" alt="Loading" />
Please Wait. Loading....
</div>
</div>
You can use beforeSend and complete events of ajax request.
$.ajax({
beforeSend:function(data){
//Show Image
},
complete: function(data){
//Hide Image
},
//rest of your code
});
use ajaxSetup
$.ajaxSetup({
beforeSend:function(){
//show loading div
},
complete:function(){
//remove the loading div
}
});