Submit a link using javascript or jquery without refreshing a page - javascript

I have a link which invokes an API which saves a session. Suppose my API be present on http://www.example.net and my link is as below :
<a href="http://www.example.net" >Click here </a>
Now i don't want to refresh the page. Just use JQuery or Javascript to simply execute the link and give an alert like "Action Succesfull". I don't see the point of using AJAX as I don't require any database actions from my side. Thanks

The point of AJAX is not to do database actions, its to comunicate with the server without needing to reload the page. I think your description qualifies for the use of AJAX, since you do expect a answer from the server, and you do not want to reload the page.
You could also open a iframe, or a new window, but ajax might be the solution here.
Keep in mind you need to cancel that event when you click on the anchor.
So, with ajax you could so something like:
$('a').on('click', function(e) {
e.preventDefault;
var href = this.getAttribute('href');
$.ajax({
url: href,
success: function(text) {
alert(text);
}
});
});

You will need an ajax call. Something like this:
$.ajax({
cache: false,
type: "Post",
url: "http://www.example.net",
success: function () {
alert("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
finaly: function () {
alert("Finish");
}
});

You can simply use onclick event if you don't want to use AJAX
Click here

Try to use an ajax call when click on button submit or the link. Here is the code :
$("a").click(function(e){
$.ajax({
url: "http://www.example.net",
type: "POST",
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data,textstatus,jqXHR)
{
alert("Success");
}
});
e.preventDefault();
});

you need to do something like this:
$('a').click( function(e) {
e.preventDefault();
var url = "your link";
$.ajax({
url: url,
success: function(data)
{
alert(data); // show response.
}
});
return false;
});

Related

Reset application STATE after JQUERY AJAX Function

Is there any way to reset an application STATE after every invoking of JQuery Ajax function?
I am developing a small app: users click on a button to invoke a function. But afterwards, when users want to click other buttons to invoke the same function, the dynamic ID of the first clicked button still persisting, so other buttons cannot be addressed anymore.
Code:
$('#submitComment').on('click', function(){
var id = $(this).data('id');
var thiselement = $(this);
$.ajax({
url: 'includes/updateicon.php',
type: 'POST',
data: {id:id},
dataType: 'html',
success: function(data){
if (data) {
$('#submitComment').attr("disabled", true);
$('#customComment').val("");
$('#updatedicon-'+id).html("DONE").removeClass('badge-danger').addClass('badge badge-success');
# CODE HERE TO RESET THE STATE OF THE APP
}
else {
$('#customContent').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#customContent').html("There was an Error about getting the Content:" + errorThrown);
}
});
});
You are searching for elements based on ID and IDs need to be unique (this is most likely causing your bug).
A simple fix of this would be:
$('.submitComment').on('click', function(){
var id=$(this).attr('id');
$.ajax({data:{id:id}});
})

Can't access object made by ajax call

I have this ajax request:
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
});
as you can see it makes new row in #table. But this new objects made by ajax are not accessible from next functions. Result from ajax is not a regullar part of DOM, or what is the reason for this strange behavior?
$('#uid').on('click', function () {
alert('ok');
});
Use event delegation:
$(document).on('click','#uid', function () {
alert('ok');
});
Note that ajax calls are asynchronous. So whatever you do with the data you need to do it in a callback within the success function (that is the callback which is called when the ajax call returns successfully).
Jquery on doesn't work like that. Use have to give a parent which not loaded by ajax, and the specify ajax load element like this
$('#table').on('click','#uid' ,function () {
// what ever code you like
});
Is simple and complex at the same time. Simple to solve but complex if you are getting started with javascript...
Your event handler - onclick is being fired and bound to an object that doesnt yet exist.
So when you append the object to the #table, you need to set up your click handler as the object now exists.
So in your success part of the ajax return add the click handler event there.
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
Or how about you make it dynamic and create a function to do it for you.
function bindClick(id) {
$('#' + id).click(function() {
//Do stuff here
console.log('I made it here' + id);
});
}
Then:
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
bindClick(uid);
});
}
This is a super contrived example but you get the idea you just need to make the rest of it dynamic as well. for example some name and counter generated id number: id1, id2, id3...
Try it like this, add this $('#uid').on('click', function () { into the success
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
});

Tracking Clicks using jQuery and Ajax. I dont have access to any html/other files

I have a list of thumbnails of recipe names and i want to track which recipes people are clicking on. I problem is that i can strictly do this using jQuery and nothing else. I dont have access to any other pages of the website.
What i did so far is i checked on the names of recipe and images and added a common class using .addClass() in jquery and just after that i declared an onclick function on that name.
Then i a taking the tile of the tag(Which is the recipe name) and sending this information of my other website where it stores this info in database.
The problem is my clicks are not getting all of the time. The behavior looks random to me till now and i don't know how some of the clicks are getting stored and how some are not!! I researched on net and only related thing i found was to keep cache to false. I also tried that but the behavior remained the same. Clicks got stored sometime only.
I am doing this on local host right now and i need to store this info on other website of mine.
jQuery(window).load(function(){
jQuery('.del-space .thumbnail a').addClass("recipeLinks");
$(".recipeLinks" ).on("click",function(event) {
var user=jQuery('loggedinuser').attr('title');
//alert(user);
if(typeof(user)==="undefined"){
user='Guest';
}
var recipeName=$(this).attr('title');
var data='recipeName='+recipeName+'&user='+user;
$.ajax({
url: "http://myotherwebsite.com/tracking/storeClick.php",
cache: false,
type: 'POST',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//alert('done');
//window.location = location.href;
},
error: function(xhr, textStatus, errorThrown) {
//alert("error");
}
});
});
Apart from this i am also wondering, that when i will put this code on live, where there would be a hell lot of clicks at a time, will i be able to log all the clicks?
use event.preventDefault() to stop the click from changing the page right away so that your ajax request has time to complete, and use window.location to change the page once ajax is complete
jQuery(window).load(function(){
jQuery('.del-space .thumbnail a').addClass("recipeLinks");
$(".recipeLinks" ).on("click",function(event) {
event.preventDefault(); //stop the default action
//the action will take place after
//ajax is complete
var href = jQuery(this).attr("href"); //get the location to goto
var user=jQuery('loggedinuser').attr('title');
//alert(user);
if(typeof(user)==="undefined"){
user='Guest';
}
var recipeName=$(this).attr('title');
var data='recipeName='+recipeName+'&user='+user;
$.ajax({
url: "http://myotherwebsite.com/tracking/storeClick.php",
cache: false,
type: 'POST',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//alert('done');
window.location = href; //now goto the links href
},
error: function(xhr, textStatus, errorThrown) {
//alert("error");
}
});
});

JQuery attempt to change window.location incorrectly truncating query parameters

I'm experimenting with JQuery for fun and I've run into a bit of a brick wall. I'm attempting to write a login page and my thought was to have a form on a jsp where a user would enter a login id and password and click a submit button. This then gets caught by a JQuery method that then makes an AJAX call to the back-end. The "success" method should then set the window object's location to a new URL indicated by the value returned from the Ajax call. FYI: I'm a back-end guy and I have that portion covered. My problem is that although I call the back-end and get the data I require. I then attempt to set a new window location with a URL that contains a single query parameter (to allow the app to know who the user is), which almost works as I get to the base URL but with no query parameters (though there is a '?' on the end of the base URL)
Here's my JQuery code:
</script>
$(document).ready(function(){
submit( function() {
var id = $("#login_id").val();
var pwd = $("#password").val();
var uri = "`http://localhost:8080/SW_Server/rest/admin/login`";
$.ajax({
async: false,
url: uri,
type: 'GET',
dataType: "json",
success: function(data) {
var session = data.session;
newLoc = data.redirect+"?"+data.session
// Prevent the form's default submission.
preventDefault();
// Prevent event from bubbling up DOM tree, prohibiting delegation
event.stopPropagation();
window.location.replace(encodeURIComponent(newLoc));
},
error: function(jqHHR, textStatus, errorThrown) {
alert("textStatus: "+textStatus+"\nerror: "+errorThrown);
// Prevent the form's default submission.
event.preventDefault();
// Prevent event from bubbling up DOM tree, prohibiting delegation
event.stopPropagation();
}
});
});
</script>
When I execute this, my back end currently returns data.redirect=http://localhost:8080/test.jsp and data.session=session_id=3, which I see in an alert (hooray for me), but then when window.location.replace(newLoc) is called it goes to http://localhost:8080/test.jsp? with no query parameter. I've been banging my head all day. What can I do to get the query param correctly picked up by the new page?
Regards,
Tim
Try to assign the value to location instead
window.location = data.redirect;
did you try some of this:
$(document).ready(function(){
$("#loginForm").submit( function(event) {
var id = $("#login_id").val();
var pwd = $("#password").val();
var uri = "http://localhost:8080/SW_Server/rest/admin/login";
alert("uri: "+uri);
$.ajax({
async: false,
url: uri,
type: 'POST',
dataType: "json",
data: { "id":id, "pwd":pwd },
success: function(data) {
$('#loginForm').attr('action',data.redirect);
$('#loginForm').submit();
},
error: function(jqHHR, textStatus, errorThrown) {
alert("textStatus: "+textStatus+"\nerror: "+errorThrown);
}
});
// Prevent the form's default submission.
event.preventDefault();
// Prevent event from bubbling up DOM tree, prohibiting delegation
event.stopPropagation();
//and also
return false;
});
});

JQuery $(this) not accessible after ajax POST?

Let's say I have a bunch of links that share a click event:
Click me
Click me
Click me
Click me
and in the $('.do-stuff').click function I execute a JQuery ajax POST request that updates the database with stuff and I get a successful response. After the ajax is completed, I simply want to change the value of the link text to be whatever I send back from the server...
$('.do-stuff').click(function () {
$.ajax({
type: "POST",
url: "MyWebService.asmx/DoSomething",
data: '{CurrentLinkText: "'+ $(this).text() +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$(this).text(result.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
This invoked just fine and I verified that "result.d" is indeed the text from the server but the text is not changing. I think that the $(this) element is no longer accessible after the AJAX post? What can I do to work around this?
In general when you lose context like that, you can save a reference to the object. Like this:
function clickHandler() {
var that = this;
$.ajax( { url: '#',
success: function (result) {
$(that).text(result.d);
}
);
}
See here:
$(this) inside of AJAX success not working
You can set the context option:
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). (...)
Example:
$.ajax({
//...
context: this,
success: function(json) {
//...
}
});
or use $.proxy:
$.ajax({
//...
success: $.proxy(function(json) {
//...
}, this)
});
Try:
success: $.proxy(function(result) {
//...
}, this)
There are lots of ways to do this, as you can see from the answers here. Personally, I prefer to construct a function bound to the current value of this:
success: (function(target) {
return function(result) {
$(target).text(result.d);
}
})(this)
It's neat, clean, and $(this) will remain the same as it is in the outer context; i.e. it will be the element that raised the event.
jQuery('#youridvalue').html(result.d);
jQuery('.yourclassvalue').html(result.d);
Use it

Categories