Trying to display a loading image - javascript

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
}
});

Related

jquery ajax search results output

I am having problem when I search for something and pressed search button it not showing the output.How should I get the results when jquery ajax search results. I am using inteilj
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mainpage</title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<input id="mysearch"text="text" placeholder="Search...">
<button id="search" >Search </button>
</form>
<ul id="movies">
<li id="result"></li>
</ul>
<script type="application/javascript" >
$(document).ready(function(){
$('#search').onkeypress(function(){
$.ajax({
url: 'http://localhost:8080/api/movies',
method: 'GET',
dataType: 'json',
success: function(data){
$.each(data, function(index, val){
$('#movies').append($('<li>').text('title: ' + val.title + ', year: ' + val.year ));
});
}
});
});
});
</script>
</body>
</html>
use onClick event listener so that you script becomes
<script type="application/javascript" >
$(document).ready(function(){
$('#search').on('click',function(){
$.ajax({
url: 'http://localhost:8080/api/movies',
method: 'GET',
dataType: 'json',
success: function(data){
$.each(data, function(index, val){
$('#movies').append($('<li>').text('title: ' + val.title + ', year: ' + val.year ));
});
}
});
});
});
</script>
your event should be .keypress not .onkeypress

getting data from a form using ajax?

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.

Multiple Submit Actions

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>

ASP.net PageMethods return undefined

Hi everyone i trying to get data from cs to js using ToolkitScriptManager.
this is my aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../assets/lib/jquery/jquery-2.0.3.js" type="text/javascript"></script>
<script>
$(window).load(function () {
alert(PageMethods.isConnected());
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager runat="Server"
EnablePageMethods="true"
EnablePartialRendering="true" />
<div>
</div>
</form>
</body>
</html>
and this is my code behind
[ScriptMethod, WebMethod]
public static bool isConnected()
{
return true;
}
i dont know, but this keep result undefined, sorry if this is really simple problem for you, but for me so hard, because i am new in asp.net
please help me to fix this problem.
You need to supply a success and a failure callback to the webmethod call as below.
$(window).load(function () {
PageMethods.isConnected(fnsuccesscallback,fnerrorcallback);
});
function fnsuccesscallback(data) {
alert(data);
}
function fnerrorcallback(result) {
alert(result.statusText);
}
Also, there is another way of accessing the page methods using $.ajax.
<head id="Head1" runat="server">
<title></title>
<script src="../assets/lib/jquery/jquery-2.0.3.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(window).load(function () {
$.ajax({
type: "POST",
url: "PageMethodTest.aspx/isConnected",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnsuccesscallback,
error:fnerrorcallback
});
}); function fnsuccesscallback(data) {
alert(data.d);
}
function fnerrorcallback(result) {
alert(result.statusText);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<div>
</div>
</form>
</body>
Will do 100% work
<script type="text/javascript">
function Generate()
{
var result = PageMethods.GenerateOTP(your parameter, function (response)
{
alert(response);
});
}
</script>

Updating the Div with added text, comment feature

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 });
}

Categories