So I am loading my page using ajax, and everything is working fine using below
$( document ).ready(function() {
menuLoad('auction');
});
function menuLoad(page){
$.ajax({
type: 'post',
url: '/content/'+page+'/'+page+'.php',
async : false,
success: function (response) {
location.hash = page;
$("#contentLoad").html(response);
}
})
};
however if i try loading the same page multiple times, all buttons click events will fire multiple times.. I understand that every time I am loading the content, I am re-assigning a new event to the button while it already have one which cause each event to fire when a user click on it.. but how to fix this?
inside page content, the button will be something like below
<input type="button" value='New Sold' id='soldaddbtn' >
$( document ).on("click", "#soldaddbtn", function(){
$.ajax({
type: "POST",
url: "/content/sold/loadSoldAdd.php",
dataType: 'html',
success: function(response){
bootbox.dialog({message: response});
}
});
})
define a global variable and check for its existence.
if(!soldaddbtnClickEventisAdded) { // check if the variable is defined file is already loaded
$( document ).on("click", "#soldaddbtn", function(){
$.ajax({
type: "POST",
url: "/content/sold/loadSoldAdd.php",
dataType: 'html',
success: function(response){
bootbox.dialog({message: response});
}
});
});
}
var soldaddbtnClickEventisAdded = true; // add a global variable
I didn't understand your problem completely but try using following code:
As on() will bind the click event, so there might be the case that event is bounded multiple times. So unbind the click event then bind it again.
$("#soldaddbtn").off("click").on("click", function(){});
its javascript not java, you need event to fire once, the replace
$( document ).on("click", "#soldaddbtn", function(){
with
$("#soldaddbtn").on("click", function(){
Related
Trying to display a value from database without refreshing the webpage using JQuery and Ajax was successful in displaying this however “Served at: /Project name” is getting appended to the value displayed
Script:
$(document).ready(function() {
$('#AESASJOBRUNOPTION').change(function() {
var AESASJOBRUNOPTION = $('#AESASJOBRUNOPTION').val();
$.ajax({
type:'POST',
url: "AESASJobCurrentOpenPeriod",
data: {AESASJOBRUNOPTION: AESASJOBRUNOPTION},
cache: false,
success: function(result) {
$("#result1").html(result);
$("#result1").html(result).slideDown('slow');
}
});
});
});
Servlet:
try{
if(ASCOGSRS.next()){
//System.out.println("Open Peiod is :"+ASCOGSRS.getString(1));
HttpSession OpenPeriodsession=request.getSession();
OpenPeriodsession.setAttribute("ASCOGSCurrentOpenPeriod", ASCOGSRS.getString(1));
PrintWriter out =response.getWriter();
String ASCOGSOpenPeriod=ASCOGSRS.getString(1);
out.print(" The Current Open Period is: "+ASCOGSOpenPeriod);
}
}
If your project is using JET Template from Eclipse, looks like the doPost method appends the extra Served at: <PATH>.
If JET Template is used, following are possible solutions:
Skip using JET Template in Eclipse Window -> Preferences -> Java EE
If Skipping JET Template is not possible and your AJAX request only retrieves the data, change the request type to GET instead of POST
If JET Template is not used, following is a solution at the Javascript level:
$(document).ready(function() {
$('#AESASJOBRUNOPTION').change(function() {
var AESASJOBRUNOPTION = $('#AESASJOBRUNOPTION').val();
$.ajax({
type:'POST',
url: "AESASJobCurrentOpenPeriod",
data: {AESASJOBRUNOPTION: AESASJOBRUNOPTION},
cache: false,
success: function(result) {
result_without_path = result.replace(/Served at:[\/a-zA-Z0-9]*/i,'');
$("#result1").html(result_without_path);
$("#result1").html(result_without_path).slideDown('slow');
}
});
});
});
You may also look for response writer in your servlets which may write the response it should be something like:
response.getWriter().append("Served at: ").append(request.getContextPath());
And then you can comment this line from your servlet.
I have a java function that gets a JSON string of data from a Servlet in Java. I am trying to use that data to populate a datatable (http://www.datatables.net/examples/data_sources/ajax.html)
This is the way that the DataTables website instructs users to populate datatables:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
And this is the javascript method that calls the doPost method in my servlet to generate and return the JSON:
<script>
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
//$('#somebutton').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}
}).responseText;
console.log(bodyContent);
});
</script>
How can I get the JSON string in var bodyContent to populate the datatable?
First off, you're not really doing AJAX; when you do:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}).responseText;
You set async: false ... but AJAX stands for Asynchonous Javascript and XML. With an AJAX approach the following happens:
You start the request by doing $.ajax
The server takes however long to respond; the user's browser is not locked up during this time
When the server responds the success callback you defined gets called
With your approach
You start the request by doing $.ajax
The user's browser is locked up while waiting for a response
When the server responds your code (after the $.ajax call) is invoked.
To make your code actual AJAX do this instead:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(responseText) {
bodyContent = responseText
}
});
Of course, once the response comes back you also need to build your Data Table, so what you really want is:
success : function(responseText) {
$('#example').dataTable( {
"data": responseText
});
}
(Or something to that effect; I forget DataTable's exact syntax.)
Refer to jQuery.ajax docs. The data returned from server in first argument of success callback. Also note that all manipulations with this data whould be inside this callback. I guess you should additionally check status argument:
$(document).ready(function() {
var bodyContent = null;
$.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(data, status) {
console.log(data);
$('#example').dataTable( {
"data": $.parseJSON(data),
"columns": [
{ "title": "Engine" },
{ "title": "Browser" },
{ "title": "Platform" },
]
});
});
});
});
UPDATE To populate data server should respond with JSON encoded array of data and you should parse it and pass to dataTable as it noted here.
I have created a REST service at "/post/search/{id}" and when I call this URL from my jquery code sometimes it gets called sometimes not. What is the exact problem in it. Is it regarding jquery or my code. My jquery code is as follows:
function functionname(clicked_id) {
$('#idForm').submit(
function(e) {
$.ajax({
type : 'POST',
url : "${pageContext.request.contextPath}/post/search/"+ clicked_id,success : function(data) {
}
});
});
}
My button code is :
<input type="submit" value="Express Intrest" id="abc" onclick=functionname(this.id) />
try like this.
function yourFunc() {
$.ajax({
type : 'POST',
url : 'yourcontroller/action',
contentType : "application/json; charset=utf-8",
dataType : 'json',
data : param,
async : false,
cache: false,
success : function(dataList) {
//alert("dataList ---> "+dataList);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest + " - " + errorThrown);
}
});
}
pass parameter values in param like this :-
var param;
param={param1:"val",param2:"val", param3:"val"};
change your button type from submit to button.
Because when you click on button your page start submitting.so the ajax function is sometime completed not completed before page.
<input type="button" value="Express Intrest" id="abc" onclick=functionname(this.id) />
i have a problem with passing values to the controller(jave) from javascript file after serialising the entries. when i run in debug mode its passing values to the controller but if its run straight away then its not passed. i first serilzed the values entered in the form and then post to the controller. any ideas please... the code is as follows function
submitSearch() {
var searchParams = $("#search-filters, #keyword-desktop-filters, #keyword-mobile-filters").serialize();
alert(searchParams);
$.ajax({
url: 'search?' + searchParams,
type: 'POST',
success: function (msg) {
alert("hai");
},
error: function (xhr) {
alert("kooyi");
}
});
}
Try to pass your search parameters like data parameter in your .ajax function settings object. Here the example:
$.ajax({
url: 'search' ,
type: 'POST',
data: $("#search-filters, #keyword-desktop-filters, #keyword-mobile-filters").serialize(),
success: function (msg) {
alert("hai");
},
error: function (xhr) {
alert("kooyi");
}
});
And here is .ajax method' API: http://api.jquery.com/jQuery.ajax/
I have a button in blank.jsp (lets say).
<input class="submit_button" type="submit" id="btnPay" name="btnPay" value="Payment"
style="position: absolute; left: 350px; top: 130px;" onclick="javascript:payment();">
when button is clicked I need to call the java method callprocedure() using ajax.
function payment()
{
alert('Payment done successfully...');
........
// ajax method to call java method "callprocedure()"
........
}
I am new to ajax. how can we call the java method using ajax. Please help me soon.
Thanks in advance.
try to use this method..
$.ajax({
url: '/servlet/yourservlet',
success: function(result){
// when successfully return from your java
}, error: function(){
// when got error
}
});
I suppose your payment is in a servlet.
All you need is this
function payment(){
$.ajax({
type: "POST",
url: "yourServletURL",
success: function(data){
alert("Payment successful");
},
error: function (data){
alert("sorry payment failed");
}
});
}
remove the inline onclick from the submit
add an onsubmit handler to the form
cancel the submission
I strongly recommend jQuery to do this especially when you have Ajax involved
I assume here the servlet function is in the form tag. If not, exchange this.action with your servlet name
$(function() {
$("#formID").on("submit",function(e) { // pass the event
e.preventDefault(); // cancel submission
$.post(this.action,$(this).serialize(),function(data) {
$("#resultID").html(data); // show result in something with id="resultID"
// if the servlet does not produce any response, then you can show message
// $("#resultID").html("Payment succeeded");
});
});
});