I'm creating HTML with a loop that has a column for Action. That column
is a Hyperlink that when the user clicks calls a JavaScript
function and passes the parameters...
example:
<a href="#" OnClick="DoAction(1,'Jose');" > Click </a>
<a href="#" OnClick="DoAction(2,'Juan');" > Click </a>
<a href="#" OnClick="DoAction(3,'Pedro');" > Click </a>
...
<a href="#" OnClick="DoAction(n,'xxx');" > Click </a>
I want that function to call an Ajax jQuery function with the correct
parameters.
Any help?
Using POST
function DoAction( id, name )
{
$.ajax({
type: "POST",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Using GET
function DoAction( id, name )
{
$.ajax({
type: "GET",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
EDIT:
A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.
Click
Click
Click
...
Click
<script type="text/javascript">
$(function() {
$('.ajax-link').click( function() {
$.get( $(this).attr('href'), function(msg) {
alert( "Data Saved: " + msg );
});
return false; // don't follow the link!
});
});
</script>
If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false
like this:
function DoAction(id, name)
{
// your code
return false;
}
Do you want to pass parameters to another page or to the function only?
If only the function, you don't need to add the $.ajax() tvanfosson added. Just add your function content instead.
Like:
function DoAction (id, name ) {
// ...
// do anything you want here
alert ("id: "+id+" - name: "+name);
//...
}
This will return an alert box with the id and name values.
try something like this
#vote_links a will catch all ids inside vote links div id ...
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(\'#vote_links a\').click(function() {// alert(\'vote clicked\');
var det = jQuery(this).get(0).id.split("-");// alert(jQuery(this).get(0).id);
var votes_id = det[0];
$("#about-button").css({
opacity: 0.3
});
$("#contact-button").css({
opacity: 0.3
});
$("#page-wrap div.button").click(function(){
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
function omtCallFromAjax(urlVariable)
{
alert("omt:"+urlVariable);
$("#omtDiv").load("omtt.php?"+urlVariable);
}
</script>
try this it work for me
Related
My page has a button that calls a Razor Page page handler to delete the associated item.
<a class="delete-item" data-id="#item.Id" asp-page-handler="delete" asp-route-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
I've defined a Javascript click handler. I need that handler to return false if the item should not be deleted.
$('.delete-item').on('click', function (e) {
var id = $(this).data('id');
var tr = $(this).closest('tr');
var td = tr.find('.item-description');
// Get number of lease details for this lease
$.ajax({
type: 'GET',
url: '?handler=LeaseDetailCount',
contentType: 'application/json',
dataType: 'json',
data: { 'leaseId': id },
})
.done(function (response) {
var description = 'Delete "' + description + '"? Are you sure? This cannot be undone.\r\n\r\n';
if (response.count == 0)
description += 'This lease has no lease details.'
else
description += 'WARNING: This lease has ' + response.count + ' lease detail(s).';
if (!confirm(description))
return false;
})
.fail(function (response) {
alert(response.responseText);
})
//.always(function (response) {
//});
}
The problem, of course, is that the AJAX call is asynchronous. And so it returns before my confirmation is displayed.
How can I get the code above to work as I want?
If you not wish to set asp-page-handler for the anchor tag, it is possible. As you mentioned
AJAX call is asynchronous
we can't predict which result come first, href navigation or onclick AJAX response
<a class="delete-item" data-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
In AJAX .done event, If the confirmation is OK page redirect to delete handler
window.location.href = "/?id=" + id + "&handler=delete";
.done(function (response) {
......
.......
if (!confirm(description))
return false;
else
window.location.href = "/?id=" + id + "&handler=delete";
})
I have a page that locates a link inside it and when that link is clicked it should save some data in database.
Besides, I have a file named "add.php" that communicates with the DB and operates well.
In my wordpress page I have added below codes for accessing the add.php file and send some parameters to it.
<a href="javascript:add(true);" >Click Me</a>
<script type="text/javascript">
function add(b){
$(document).ready(function(){
var result = $.ajax({
type: "POST",
url: "add.php",
data: { add: b }
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert( "No such data exists: " + textStatus );
});
});
}
</script>
I had this exact code in an html file and it worked smoothly. but it doesn't work on wordpress page like that.
Plus, the problem is that when I click the link -Click Me- it doesn't do anything.
please tell me where the problem is and how to solve it ?
I would recommend you to use this:
<a href="#" data-add="true" class='hitClick'>Click Me</a>
<!--use data* attributes to pass specific data -->
now in your function:
function add() {
event.preventDefault(); //<------make sure to add it.
var result = jQuery.ajax({
type: "POST",
url: "add.php",
data: {
add: jQuery(this).data('add')
}
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert("No such data exists: " + textStatus);
});
}
jQuery(document).ready(function(){
jQuery('.hitClick').on('click', add); // bind the click and use as callback
});
I want to pass the link on textbox blur function.
Jquery code
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a> */* this is the link for get the profile details*/*
<script type ="text/javascript">
$('#getCandidate').text('Get Profile') // Sets text for email.
.attr('href', '#');
$("#Email").blur(function () {
$('#checkEmail').trigger('click');
//$('#checkEmail').trigger('GetCandidateDetail?validateEmail=' + $('#Email').val());
$('#getCandidate').text('Get Profile')
.attr('href', 'GetCandidateDetail?validateEmail=' + $('#Email').val());
});
$(document).ready(function () {
$('#checkEmail').click(function () {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
Html code
<%: Html.TextBox("Email",Model.Email, new {#title="Enter the Candidate Email Id"})%>
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a>
In the above code when I type the email id in textbox it triggers email id is registered or not. Then I give one more link getdetails. If I click that link then the profile will come by using the link GetCandidateDetail?validateEmail=' + $('#Email').val()).
But Now I want when I type the email id in textbox, if exists means it will load the link GetCandidateDetail?validateEmail=' + $('#Email').val())automatically otherwise false. How to do this? Help me to come out this issue?
You can do just like this:
$(document).ready(function() {
$("#Email").on('blur', function() {
// Check mail on blur
var email = $(this).val();
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: {validateEmail:email},
success: function(data) {
// handle your response
}
});
});
});
function verify() {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
return false;
});
}
$("#Email").blur(function(){verify();)
$("#checkEmail").click(function(){verify()})
thats it !!
I have a page that displays a dynamic amount of "orders" and I have a button to "view" and another button to "print". To display the specific OrderNumber I'm using a javascript function triggered by onmouseover and a jQuery ajax function to change the button text, make a database entry, and then view or print another page. The problem is the order is viewed or printed MULTIPLE times from onmouseover. How can use only jQuery and call the specfic OrderNumber? Here is the code I'm using now:
This code is repeated for each order:
<div class="console_orders_details">
<input type="button" value="View"
id="vieworder'.$row[orderid].'" onmouseover="vieworder('.$row[orderid].');">
</div>
Here is the function to view the order:
function vieworder(id){
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result)
{
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
I'm assuming I need to eliminate the "vieworder" function and use a pure jQuery function. However, I don't know how to send over the order "id", which is why I used javascript.
You can target all elements with an ID that starts with vieworder, and then store the row ID as a data attribute :
<div class="console_orders_details">
<input type="button" value="View" id="vieworder'.$row[orderid].'" data-id="'.$row[orderid].'">
</div>
JS
$(function(){
$('[id^="vieworder"]').on('click', function(){
var orderid = $(this).data('id'),
btn = $('input[type="button"]', this);
$.ajax({
url: "includes/ajax/console-view.php",
dataType: 'html',
data: {orderid : orderid}
}).done(function(result) {
window.open("print.php?view=1&orderid="+orderid+"");
btn.val("Viewed!").fadeIn(400);
});
});
});
Your onmouseover event is probably being fired many times, resulting in your problem. This might help to stop unwanted extra calls, by ignoring them unless the previous one has completed.
var activeRequests = {}; // global
function vieworder(id){
if (activeRequests[id]) { return; }
activeRequests[id] = true;
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
delete activeRequests[id];
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
First, don't have a dynamic id that you have to parse, and don't have an event handler in your html:
<div class="console_orders_details">
<input type="button" value="View" class="vieworder" data-id="$row[orderid]">
</div>
Next, create an event handler for just what you want to do. .one() will set an event handler to fire only once:
$(document).ready(function (){
$(".console_orders_details").one("mouseover", ".vieworder" function(){
var dataString = "orderid=" + $(this).data("id");
$.ajax({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
window.open("print.php?view=1&" + dataString);
$(this).val("Viewed!");
}
});
});
});
If you want this to work onclick, then just change the mouseover to click. Also, fadeIn doesn't work on values. Here is a fiddle that has the basics: http://jsfiddle.net/iGanja/EnK2M/1/
i have a page where i'm using a with id="emailfrnd", from the following script i successfully implemented the colorbox:
<script type="text/javascript">
$(document).ready(function(){
$("#emailfrnd").colorbox({
inline: true,
href:"#ef",
close:"",
opacity:0.95,
onClosed:function(){
//window.parent.location.reload(true);
}
});
});
</script>
now the new colorbox contains a form with a send button in it of id "emailfrnd_submit" now i had written some validations using the jquery & ajax and if there are no errorMessages i'll get another colorbox and the code is as follows:
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
$("#emailfrnd_submit").colorbox({
inline: false,
close: "",
html: "<div style='height:230px;width:400px;display:block;'><p style='color:black;font:16px verdana;'>Your email was successfully sent.</p><br/><p style='color:gray; font:16px verdana;'>Thank you for telling your friend</p><div id='emailfrnd_sub' style='width: 50px;margin-top:30px;float: right;'><input type='submit' value='OK' name='emailfrnd_submit' id='emailfrnd_sub' class='redbut' style='float:right;position:absolute;right: 198px;margin-top: 0px;color:white;'></div></div>",
opacity: 0.95,
onClosed: function () {
//window.parent.location.reload(true);
}
});
//window.location.assign("../index.php");
} else {
alert('mail not send');
}
}
});
} else {
alert(errorMessage);
}
});
upto now i succeed in getting the things as i want, here after doing the validations and onclick the send button according to this code a new colorbox with the html content as above is coming, here i have a Ok button here, i want to make that button as the closing button of this colorbox. how can i get that functionality for the ok button here??
anyone help is much appreciated....thanks in advance.....
You don't need 2 colorboxes to do it.
Why don't you simple create a div which class is message_content and you update it's text according to the ajax status ?
It's much better.
Example:
html:
<div id="colorbox_content"> //#todo: change to colorbox id
<form id="your_form"> //#todo: change according to your form id
</form>
<div class="message_content">
<p class="message"></p>
<span class="close">Close</span>
</div>
</div>
js:
/**
* Close message
*/
jQuery('#colorbox_content').on('click', '.close', function() {
jQuery(this).closest('#message_content').slideUp();
});
/**
* On form submit
*/
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
var message = "Your email was successfully sent.";
//window.location.assign("../index.php");
} else {
var message = "Your email was successfully sent.";
}
jQuery('#colorbox_content').slideDown().find('.message').text(message);
}
});
} else {
alert(errorMessage);
}
Update based on this comment:
If you want the same funcionality for different buttons you have to use the same class for them.
here's what do you need.
demo
I changed some ids to classes so you don't need 2 events with the same code.
And here's the las version.
You can see that you can store your options for each kind of colorbox and then pass them thrue parameter.
i got the answer and the fiddile shows how to do it.....::::)))))
http://jsfiddle.net/srinivaswaterdrop01/4vuDC/189/