I have a custom function that I have defined and then I subsequently call when the the page loads. I need the function to run when the page loads because it is populating a group selectlists:
<!---Populate Custom Service Description select lists --->
<script type="text/javascript">
function PopulateSelectLists(){
// Important: Must append the parameter "&returnformat=json"
$.ajax({
url: 'cfcs/get_descriptions.cfc?method=getDescriptions&returnformat=json'
, dataType: 'json'
, success: function(response){
$.each(response.DATA, function(I, row){
// get value in first column ie "description"
var description = row[0];
// append new option to list
$("#descriptionDD1").append($('<option/>', {
value: description,
text : description
}));
$("#descriptionDD2").append($('<option/>', {
value: description,
text : description
}));
$("#descriptionDD3").append($('<option/>', {
value: description,
text : description
}));
$("#descriptionDD4").append($('<option/>', {
value: description,
text : description
}));
});
},
error: function(msg){
console.log(msg);
}
})
}
$(document).ready(PopulateSelectLists);
</script>
I am trying to call my custom function PopulateSelectLists() when another AJAX call successfully completes so I can refresh my selectlists but it never seems to call my function:
<!---Script to add new description to DB --->
<script>
$(function(){
//Add a new note to a link
$("#addDescriptionForm").submit(function(){
// prevent native form submission here
$.ajax({
type: "POST",
data: $('#addDescriptionForm').serialize(),
url: "actionpages/add_descriptions_modal.cfm",
success: function() {
PopulateSelectLists(); //Call Function to refresh selectlist
$("#addDescriptionResponse").append( "Successfully added description." );
}
});
return false;
});
});
</script>
Where am I going wrong here?
In the problematic case, does the request actually return successfully? Inspect the response with Firebug or Fiddler or whatever dev toolbar you are using. It may be that there is a server error, a connection error, or any other reason that can drop the request, so it is not successful.
You can also look into using the complete handler: http://api.jquery.com/jquery.ajax/.
Related
I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
$.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
$.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});
That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.
Why won't my function work after ajax has succeed?
I have a custom function named filter(), defined in the header as javascript file.
Then i have a series of jquery code to dynamically retrieve data from the server to populate the select box. I would like to call the filter() after the AJAX request has completed since the filter() will manage populated the select box's option.
$.ajax({
url: "checkersc2.php", //This is the page where you will handle your SQL insert
type: "GET",
data: values, //The data your sending to some-page.php
success: function (response) {
$('#loading-image').css('display', 'none');
$dropdownCondition.html(response);
filter();
},
error: function () {
console.log("AJAX request was a failure");
}
});
EDIT: my filter() code is a little long, # http://jsfiddle.net/tongky20/re5unf7p/11/
It looks like you have an invalid selector for dropdownCondition. It probably fails on that line and never calls filter. Unless you defined that variable else where try updating it to a valid element selector and see if it calls filter. Something like:
$('#dropdownCondition').html(response);
Assuming the element id is dropdownCondition.
Full function:
$.ajax({
url: "checkersc2.php", //This is the page where you will handle your SQL insert
type: "GET",
data: values, //The data your sending to some-page.php
success: function (response) {
$('#loading-image').css('display', 'none');
$('#dropdownCondition').html(response);
filter();
},
error: function () {
console.log("AJAX request was a failure");
}
});
i added custom.js to my product edit page
i have added attribute with id "getdata" now there is another file where value show based on what user select in dropdown
i need to do ajax call to other page with value of dropddown , calling ajax is simple i want to use magento built in way of calling ajax url and loader also how can i do it ??
i wrote below code but its now working
function myajaxcall(id){
new Ajax.Request('/a.php?id='+id, {
onSuccess: function(response) {
alert(response);
}
});
}
what am i missing pls help
Try to use the below code :
function myajaxcall(id){
new Ajax.Request('a.php?id='+id, {
method:'get',
onSuccess: function(data) {
var response = data.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function() { alert('Something went wrong...'); }
});
}
I have the following code:
$(document)
.ready(
function() {
$.ajax({
type : "GET",
url : "http://localhost:8080/RememberMeServer/rest/LifeEventService/events",
dataType : "xml",
success : function(xml) {
$(xml).find('Event').each(function() {
var name = $(this).find('Text').text();
$('#droplistevents').append($('<option/>', {
value: name,
text : name
}));
});
},
error : function(xhr) {
alert(xhr.responseText);
}
});
});
What it does is a get request to a webservice running on that address and gets the data inside the <Event> <Text> </Text> </Event>
but unfortunately i am not being able to add that information to the select box i have in my html file with id = "droplistevents".
What am i doing wrong?
This actually works. i was calling the wrong js inside the html page that calls this.
I dont delete because this might help someone