<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate="+$("#epdate").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
i have this code and i want to add another variable
inside ajax script adding another
data: "empname="+$("#empname").val(),
dopesnt work i hope someone would help me. thank you
and how can i call a postname or make a postname into session an call it into another php page?
Actually, there are multiple ways, either separate them using a & character.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate=" + $("#epdate").val() + "&empname="+$("#empname").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
Or alternatively, you can use an object which holds the name-value pair.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: { epdate : $("#epdate").val(), empname : $("#empname").val() },
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
UPDATE 1: You can also pass it as an array in the following format,
data : [{
name : 'epdate',
value : $("#epdate").val()
}, {
name : 'empname',
value : $("#empname").val()
}],
UPDATE 2: There is build in functions in jQuery to do the same, use [serialize()][] or serializeArray() method for that. You can apply it on a form element or input elements and which generates based on the input elements name attribute.
data : $('#epdate,#empname').serialize(),
// or
data : $('#epdate,#empname').serializeArray()
,
Related
My problem is lack of action after pressing the button. Under the button hook AJAX function.
Please a hint where I have a bug // errors.
My code:
Controller:
[HttpPost]
public ActionResult InsertCodesToDB(string name)
{
cl.InsertCodesToDB(name);
fl.MoveCodeFileToAccept(name);
string response = "Test";
return Content(response, "application/json");
}
View / Button:
<input type="button" class="btn btn-success sendCodesToDB" value="Umieść kody w bazie" data-value="#item.Name"/>
View / Script:
<script>
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
onBegin;
}
});
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
Thank you in advance for your help.
You seem to not be adding the on ready function for jQuery. Try adding it before your click action and closing it before your onBegin() function, like so:
<script>
// open here
$( document ).ready(function() {
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
// function call missing "()"
onBegin();
}
});
});
// and close here
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
The code in Ajax must be JavaScript. You cannot use C# code there (except to print some values). What is #(ViewBag.MessageOK) doing here:
success: function (response) {
#(ViewBag.MessageOK) = response;
},
If you want to display the response in a message box, try something like:
success: function (response) {
$("#your_message_id").html(response);
},
Notes: aside from that, you have several errors in your code as others pointed out in the comments.
1- Remove the quotes from the data like this:
data: JSON.stringify({ name: name }),
2- Change the error to this:
error: function () {
onBegin(); // You need "()" here
}
Or better this:
error: onBegin // You don't need "()" here
I guess you are sending data inside the AJAX call in the wrong way.
Try it like this
data: JSON.stringify({ name: name })
Hope this will help you.
I have tried to ajax using post to jsp script my html table rows for weeks now with no success.Can anyone please guide me on this?Below is what I have done so far.
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
$('#notSoCoolGrid > tr').each(function(event) {
event.preventDefault();
var postData = {
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
};
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData.$('input, select').serialize() ,
success: function(msg){
alert("submitted");
}
});
});
});
If I correctly understand your need, you want to transmit the content of your rows, each in the form showed in your current postData.
So this can be made at once for all rows (instead of ajaxing successively each of them).
It might be something like this:
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
event.preventDefault();
var postData = [];
$('#notSoCoolGrid > tr').each(function(event) {
postData.push(
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
);
});
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData,
success: function(msg){
alert("submitted");
}
});
});
});
Note that I choosed (the simplest way, IMO) to make a simple array of rows, where each one is an object like you already structured them.
Last point: I notice you specified async: false.
I don't know why you did that, and so I kept it unchanged.
But note that it's not recommended, and is being on the road to become deprecated.
I finally was able to solve this issue,for that I want to post my answer it might be helpful for someone out there.My previous code was submitting a form before even ajax call being triggered and I have to use Classes instead of IDs to identify my rows.I had to change the code completely to be able to submit the form
$('#btn').click(function(e) {
e.preventDefault();
$('#notSoCoolGrid tr').each(function(i, tr) {
var postData = {
paymentId : $('.paymentId', tr).val(),
id : $('.deald', tr).val(),
pType:$('.pType', tr).val(),
pAmt:$('.pAmt',tr).val(),
currency:$('.currency',tr).val(),
pInvDate:$('.pInvDate',tr).val(),
pRecDate:$('.pRecDate',tr).val(),
comments:$('.comments',tr).val()
}
$.ajax({
async: false,
type: "post",
url: "/update_deal_pmt_script.jsp",
data: postData
})
.done(function(response) {
console.log(response);
})
.fail(function(x, status, error) {
alert("Error: " + error);
});
});
});
This question is related to this one.
I'm using Tooltipster JQuery plugin to show tooltips on my website like:
HTML
<div class="tooltip" data-id="'.$comment['id'].'">Hover me!</div>
JS
<script type="text/javascript">
$(document).ready(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250
});
});
</script>
Anyway this doesn't work on Ajax dynamic content, basically I load via Ajax new content with a function:
function exploreTracks(start, filter) {
$('#load-more').html('<div class="load_more" style="height: 232px;"><div class="preloader-loadmore preloader-center"></div></div>');
if(filter == '') {
q = '';
} else {
q = '&filter='+filter;
}
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_explore.php",
data: "start="+start+q+"&token_id="+token_id,
cache: false,
success: function(html) {
$('#load-more').remove();
// Append the new comment to the div id
$('#main-content').append(html);
// Reload the timeago plugin
jQuery("div.timeago").timeago();
// Update the Track Information
updateTrackInfo(nowPlaying);
}
});
}
New contents on mouse hover don't show any tooltip, from console I can't see any error or warning and on network load_profilecard.php is not called.
I have placed the script (same JS as above) directly on my content page, so why the tooltip is not shown on mouse hover?
My solution
As suggested in comments by Evan I used delegation option for this purpose.
$(function() {
$('body').on('mouseenter', '.tooltip:not(.tooltipstered)', function(){
$(this)
.tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250 })
.tooltipster('open');
});
});
I am trying to make a stepy-form for my project. What I want to do is I want to submit all my data step by step in stepy-form so I used an AJAX request for this purpose, but When I am trying to save it it's not working. So I used noConflict Method to avoid jQuery conflicts but I still have the same problem. I am using adminEX template And Not getting any error message. So can anyone help me?
<script src="ajax/jquery.min.js"></script>
<script>
$.noConflict();
Jquery(document).ready(function(){
$('#stepy_form').click(function(){
$.ajax({
type: 'POST',
url: 'ajax/insert_all.php',
data: {
txtVehicleNo: txtVehicleNo,
SltType: SltType,
txtPANNumber: txtPANNumber,
txtManufacture: txtManufacture,
txtModel: txtModel,
txtEngineNumber: txtEngineNumber,
txtChassisNumber: txtChassisNumber,
txtOwnerName: txtOwnerName,
txtUnlaidenWt: txtUnlaidenWt,
txtGVW: txtGVW
// qid: 'form1'
},
//alert('hello');
//async: true,
//cache: false,
success: function(result) {
alert('SUCCESS');
//$('#target').html(result);
}
});
});
});
</script>
And this one is the URL ,insert_all.php
$qid = $_POST['qid'];
echo $qid;
You are not using 'no conflict' with jquery and accessing it using $. Change $ with jQuery like this
$.noConflict();
jQuery(document).ready(function(){
jQuery('#stepy_form').click(function(){
jQuery.ajax({
type: 'POST',
url: 'ajax/insert_all.php',
data: {
txtVehicleNo: txtVehicleNo,
SltType: SltType,
txtPANNumber: txtPANNumber,
txtManufacture: txtManufacture,
txtModel: txtModel,
txtEngineNumber: txtEngineNumber,
txtChassisNumber: txtChassisNumber,
txtOwnerName: txtOwnerName,
txtUnlaidenWt: txtUnlaidenWt,
txtGVW: txtGVW
},
success: function(result) {
alert('SUCCESS');
//$('#target').html(result);
}
});
});
});
I'm using the jQuery UI Autocomplete plug-in to make an ajax call and retrieve data. As well as passing the text of the input element I'm trying to pass in the 'id' attribute of the input element as an additional parameter. An extract of my code looks like this -
$("#autocomplete input").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(this).attr('id')
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label,
value: item.name
}
}))
}
})
},
});
The extra parameter is added to the 'data' property in the ajax call. It works okay if I specifically pass in a value e.g. '3' but I want to pass the 'id' attribute of the input element the function is being called on e.g. $(this).attr('id').
I assume it's a problem with 'this' not being evaluated in this part of the code, but I'm at a loss to see how else I can reference the element that is being targeted. Any help appreciated!
$('#autocomplete input').each(e, function() {
$(e).autocomplete('/path?param=' + $(e).attr('id'), function() { ... });
});
$('#autocomplete input').each(e, function() {
$(e).autocomplete({ source:function ... extra_param: $(e).attr('id') ... });
});
There maybe a more elegant way, but, I know autocomplete is somewhat sophisticated. I personally generate the request w/get parameters and use formatItem/formatResult instead of assigning the source to an ajax call.
I've got it working by breaking the autocomplete call out into an each. This allows me to capture the target element before I execute the autocomplete -
$("#autocomplete input").each(function() {
var that = this;
$(that).autocomplete({
source: function(request, response, this_element) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(that).attr('id')
}
....
"Source" is the ID of your input, you receive this item and save it in the variable, "that". When the input "Source" calls the autocomplete function, you can send the value of your id stored in the variable "that" for AJAX.
Example:
<script type="text/javascript">
$(document).ready(function() {
$("#Source").each(function() {
var that = this;
var url = "<?php echo constant('URL'); ?>";
$(that).autocomplete({
source: function(request, response){
$.ajax({
url: url+"models/queries/C_getOptions.php",
dataType:"json",
data:{
word:request.term,
id : $(that).attr('id')
},
success: function(data){
response(data);
}
});
},
minLength: 1,
select: function(event,ui){
//alert("Selecciono: "+ ui.item.label);
}
});
})
});