How to pass parameter from a link to jquery method - javascript

When the user clicks on the link i need the JQuery method to fire, and call a web service, which is located at /Project/Send/SendMethod. When i click on the send link the method gets fired, i know this because the alert is getting displayed. But the problem is how to call the webservice. It would be good if it's a POST method.
<a href='' id='2' class='send'> Send </a>
Jquery method
$(function () {
$('.send').click(function () {
alert(this.id);
});
});

Use jQuery $.post:
$(function () {
$('.send').click(function () {
alert(this.id);
$.post(url, {'id':this.id}, function (response) {
//do the result oriented activities
});
});
});

Use $.ajax() method and specify the url and options like this jQuery Ajax
$(function() {
$('.send').click(function (e) {
e.prevenDefault();
$.ajax({
url: "Project/Send/SendMethod",
type: "POST",
data: values,
success: function(){
alert("success");
$("#result").html('submitted successfully');
}
});
});
});

You can make use of the $.ajax() api in jQuery. Moreover, you have to preventDefault the default behavior in your link. Otherwise, you will change page instead of sending ajax requset.
$('.send').click(function (event) {
event.preventDefault();
$.ajax( {
url:"Project/Send/SendMethod",
type: "POST",
data: { "id": this.id },
success:function(data) {
alert(data);
}
});
});
If you are using jQuery 1.8+, since "success" callback is deprecated as of jQuery 1.8. You should use the "done" http://api.jquery.com/deferred.done/
$('.send').click(function (event) {
event.preventDefault();
$.ajax( {
url:"Project/Send/SendMethod",
type: "POST",
data: { "id": this.id }
}).done(function( data) {
alert(data);
});
});

I'd use jQuery's ajax() functionality (and regularly do).
The example below assumes you're going to get a JSON-formatted response. You can change this if you're going to get back a full HTML page... take a look at http://api.jquery.com/jQuery.ajax/ for more info.
$(function () {
$('.send').click(function (e) {
e.stopPropagation();
e.preventDefault();
var thisId = $(this).attr('id');
alert(thisId);
var hostAndPort = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port; // current page and protocol (http or https)
var requestUrl = hostAndPort + "/Project/Send/SendMethod/";
var str_address = requestUrl + 'id?=' + thisId;
$.ajax({
url: str_address,
contentType: 'application/json',
dataType: 'JSON',
type: 'POST',
success: function (response) {
console.log(response);
// do something...
},
error: function (e) {
// handle error
}
});
});
});

Related

jQuery AJAX function on success not working

Having an issue. I have two different buttons included with each image displayed. One is remove, the other is assign as "main".
Remove works. It hides the image, deletes the file, and the MySQL row.
Assign Main sort of works. It updates the row in the database changing "main" value to 1, as it should, however, it should also alert(), but it does not.
<script>
$(document).ready(function() {
$(".remove_image").click(function() {
var image_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { image_id:image_id,
image_remove:1},
success: function(response) {
$('#image_'+image_id).fadeOut(400);
showUploader();
}
})
})
});
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
}
})
})
});
</script>
The success method is only called when a HTTP 200 or HTTP 304 is returned, therefore you may need to double check to see if this is actually the case.
This can be done in the ‘Inspector’ panel in most modern web browsers, usually under the ‘Network’ tab.
You can also add a error: function() {} event handler to catch any HTTP 4xx / 5xx codes.
Try and alert the error which for sure is there:
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
})
})
});
This will show you if there is something wrong in your PHP code
Use done() instead of it :
$.ajax({
type: "post",
url: "imagecontrol.php",
data: {
image_id: image_id,
image_remove: 1
}
}).done(function(response) {
$('#image_' + image_id).fadeOut(400);
showUploader();
);

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

ajax response popup using fancybox

first I have send the http ajax request to the server and return the response. Then I need to popup response using fancy box. I have tried several ways in many times. Unfortunately I couldn't find a clear method,
here is my code,
<script type="text/javascript">
$(document).ready(function () {
$('#BtnInvoiceNo').click(function () {
$.ajax({
url: "#Url.Action("Return_Invoice", "QuickReports")",
type: "POST",
dataType: "",
success: function (data) {
alert(data);
$.fancybox({
'content': data
});
$('#popup_box').html(data);
$("#popup_box").fancybox();
},
error: function (e) {
alert("Error");
}
});
});
});
</script>

Checking dynamically generated element in jQuery?

Please consider the following code:
function autoRecursiveLoad(checkingElementId) {
if (checkingElementId.length) {
return;
}
else {
var targetId = $("#targetContent");
var requestUrl = $('#ajaxUrl').val();
$.ajax({
url: requestUrl,
cache: false,
type: "POST",
async:false,
beforeSend: function(){
},
complete: function(){
autoRecursiveLoad(checkingElementId);
},
success: function(data) {
targetId.append(data);
},
error: function(e) {
}
});
}
}
in the code: checkingElementId is the id of the dynamically generated element. I used checkingElementId.length to see if it already exists yet, if not, send ajax request to load the content, create div with the id of checkingElementId and then appends to targetId, then perform recursive call.
The problem is the div with id of checkingElementId is generated successfully but the code to check if it exists (checkingElementId.length) never worked. Hence, the above function will loop forever. Am I doing something wrong?
I dont know if it is the best solution or not, but this works for me, I trigger the DOMNodeInserted event on the fly, so the function is updated as follows:
function autoRecursiveLoad(checkingElementId) {
$(document).on('DOMNodeInserted', checkingElementId, function () {
// do something when the new dynamically generated item (checkingElementId) added to the page
});
if (checkingElementId.length) {
return;
}
else {
var targetId = $("#targetContent");
var requestUrl = $('#ajaxUrl').val();
$.ajax({
url: requestUrl,
cache: false,
type: "POST",
async:false,
beforeSend: function(){
},
complete: function(){
autoRecursiveLoad(checkingElementId);
},
success: function(data) {
targetId.append(data);
},
error: function(e) {
}
});
}
}

jquery ajax sucess data into facebox

UPDATE: The code if working I has some css issues.
I'm trying to put ajax data into facebox modal box, I have the following code but facebox modal box is not loading. Looking into firebug ajax is returning the correct data but i do not know how to pass that data to facebox.
$('a[rel*=facebox]').live("click", function() {
var ajaxpostID=$(this).parent().attr("id"); //Get entry ID
$.ajax({
url: 'http://www.someurl.com/ajax/facebox-ajax.php',
type: "POST",
data: ({
ajaxpostID: ajaxpostID
}),
success: function(data) {
$.facebox(data);
},
error: function() {
$.facebox('There was an error.');
}
});
});
Something like this worked for me:
//added some id to anchor tag and
$('a[id='some_anchor_id']').live("click", function() {
var ajaxpostID=$(this).parent().attr("id"); //Get entry ID
jQuery.facebox(function() {
var form_data = {
ajaxpostID: ajaxpostID
};
$.ajax({
url: "http://www.someurl.com/ajax/facebox-ajax.php",
type: 'POST',
data: form_data,
success: function(data) {
jQuery.facebox(data);
},
error: function() {
$.facebox('There was an error.');
}
)
});
})
})
Hope it works for you

Categories

Resources