Good day,
I have a button
<button id="4" onclick="UpdateStatus(this.id)" class="btn btn-default" type="button">update</button>
that is calling an ajax function
<script>
$(document).ready(function () {
function UpdateStatus(Id) {
$.ajax({
type: "Post",//or POST
url: '/myController/UpdateSomething?Id=' + Id,
// (or whatever your url is)
data: { data1: var1 },
success: function (responsedata) {
// process on data
alert("got response as " + "'" + responsedata + "'");
}
});
}
}
</script>
My problem is that I receive an error in my view:
UpdateStatus is not defined at HTMLButtonElement.onclick
what am I doing wrong? thanks
Update
When I try to run this code
#section scripts
{
<script>
$(document).ready(function () {
//Carga datos del curso
console.log("asdf");
});</script>}
I do not get the message in my console.
The problem is, You are defining your method definition inside the document.ready event of jQuery. When the button markup was parsed and rendered, the JavaScript method was not defined, hence you are getting the error.
The jquery ready method gets executed a little later when the document is ready (parsing and rendering of the HTML is already done, DOM is safe to be accessed). By this point, the HTML has been already rendered.
Define it outside it.
<script>
function UpdateStatus(Id) {
alert('UpdateStatus called');
}
$(function () {
});
</script>
Another option is to use unobutrusive JavaScript. So instead of wiring up a click event handler to the button markup, you will wire up later, when document ready is fired.
<button id="4" class="btn btn-default" type="button">update</button>
and wire up the click event
$(function () {
$("#4").click(function (e) {
e.preventDefault();
alert('User clicked');
});
});
<script>
function F(user_id) {
var user_id = user_id;
$.ajax({
type:"GET",
url:"http://127.0.0.1:8000/preference",
data: {'user_id':user_id},
async: false,
success: function (result) {
console.log(result)
}
});
}
</script>
the first line is automatically not to display. It is the script's type and src attributes. I used the "text/javascript" and "http://code.jquery.com/jquery-latest.js".
This question I found 2 solutions. One is as the above. To divide the script into two parts. Second is to move the function to under the button tag.
It is really a scope question. But I didn't find the solution's logic. But I solve it.
This is definitely a scoping issue, because UpdateStatus defined within the scope of document.ready() function. You can declare UpdateStatus as variable outside document.ready() block and declare a function inside it:
var UpdateStatus;
$(document).ready(function () {
UpdateStatus = function () {
var buttonId = $('#4').attr('id');
$.ajax({
type: "POST",
url: '/myController/UpdateSomething',
data: { Id: buttonId, ... }, // setting parameters
success: function (responsedata) {
// process on data
alert("got response as '" + responsedata + "'");
}
});
}
});
Additionally, based from standard event registration model and separation of concerns, I suggest you to use unobtrusive JavaScript by retrieving button ID like this:
$(document).ready(function () {
$('#4').click(function() {
var buttonId = $(this).attr('id');
$.ajax({
type: "POST",
url: '/myController/UpdateSomething',
data: { Id: buttonId, ... }, // setting parameters
success: function (responsedata) {
// process on data
alert("got response as '" + responsedata + "'");
}
});
});
});
Because you're using AJAX POST, no need to use query string parameters in URL like url: '/myController/UpdateSomething?Id=' + Id.
Related issues:
Uncaught ReferenceError: (function) is not defined at HTMLButtonElement.onclick
Why is inline event handler attributes a bad idea in modern semantic HTML?
Related
In an MVC page, I have the following jQuery/javascript:
$("form").submit(function (event) {
var inp = $("input"); inp.attr('value', inp.val());
var html = replaceAll(replaceAll($('html')[0].outerHTML, "<", "<"), ">", "<");
// event.preventDefault();
$.ajax({
url: "/Ajax/SetSession",
asynch: false,
dataType: "json",
cache: false,
type: "get",
data: { name: 'html', data: html.substring(0, 1024) },
error: function (xhr, status, error) {
alert("Ouch! " + xhr.responseText);
// $(this).unbind('submit').submit();
},
success: function (data) {
alert("Awesome: " + data);
// $(this).unbind('submit').submit();
},
complete: function (xhr, status) {
alert('Phew!');
$(this).unbind('submit').submit();
}
});
});
It is meant to intercept the normal submit process, capture the html of the page before it's submitted, and then continue on its way as if nothing happened.
But the problem is, with both commented out, the form re-submits, as expected, put the controller never executes the /Ajax/SetSession url. Whereas, if I uncomment them, the /Ajax/SetSession does execute but the unbind does not appear to work as the form does not seem to get resubmitted.
Not sure what's going on here. What am I missing?
Any and all clues appreciated.
event.preventDefault(); should stay uncommented since this prevents form to submit instantly. Apparently you want to control the moment at which form is submitted.
$(this).unbind does not work because inside success and error handles context is no longer form - it is an jQuery ajax context object. You can do two things here to have the behavior you want:
Set context explicitly to be the form object. This can be done via context property:
$.ajax({
...
context: this, //form here!
...
success: function (data) {
alert("Awesome: " + data);
$(this).unbind('submit').submit(); //now this refers to form
},
Refer to form using a different variable:
$("form").submit(function (event) {
var form = this;
...
$.ajax({
...
success: function (data) {
alert("Awesome: " + data);
$(form).unbind('submit').submit(); //using form variable instead of this
},
I am a very beginner to mvc and ajax both.
I have tried many examples on net but I don't understand how ajax is used practically?
I have a controller named members which has GetAllMembers Method.
GetAllMembers returns a List<Members>
Now I want to use JQuery and ajax something like :
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function () {
},
error: function () {
alert("Failed to get the members");
}
});
});
Is my URL right?
Upon success I want to display that List in a ListBox.
How can I get it? Can anyone give me a start?
$.ajax({
type: "POST",
url: "Members/GetAllMembers", //Your required php page
data: "id="+ data, //pass your required data here
success: function(response){ //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
},
error: function () {
alert("Failed to get the members");
}
});
Hope this will help you.. :)
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function (result) {
// do your code here
},
error: function () {
alert("Failed to get the members");
}
});
});
So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.
Follow this example:
suppose you have this html:
<p>List Box - Single Select<br>
<select id="listBox" name="listbox">
</select>
</p>
So we have this js:
var template = '<option value="$value">$name</option>';
var getAllMembers = function() {
$.ajax({
url: 'Members/GetAllMembers',
dataType: 'json', //Assuming Members/GetAllMembers returns a json
success: function(response) {
$.each(response, function(index){
var option = template.replace(/\$value/g, this.value)
.replace(/\$name/g, this.name);
$('#listBox').append(option);
});
}
});
};
EDIT: Now you only need to call getAllMembers(); function.
Hope this help.
Pablo.
EDIT: To be more clear, I am looking to have onBegin call a function that returns a true or false value from an Ajax call. That false value needs to be able to trigger onBegin to abort the form submission, just as if I had returned a false value from a non ajax function.
I need to return a value of false to Ajax.BeginForm's onBegin, if certain conditions exist. This way I can prevent the form from submitting if certain database conditions exist.
However, in order to use the results of an Ajax Get, I would need to craft the function to use callbacks, which means that I cannot have the function used by onBegin return the ajax value. So how can I pass the result into onBegin?
Basically I have:
`Ajax.BeginForm(onBegin="checkIfMyConditionExists();"`}...
function checkIfMyConditionExists(){
$.get(checkConditionURL, function(data){
doSomething(data);
});
How can I get that data (which would be my true or false value) into onBegin?
What you are trying to accomplish without it being synchronous just is not going to happen. You WILL have to perform a synchronous check. Otherwise the check will be called but the form and other things will be submitted before the ajax call has time to say "Wait for me."
In your ajax call to the server you have to set async: false on a $.ajax call. This will make it to where it will expect some sort of result before running the next bit of code. Keep in mind that you wouldn't want to do $.get because there is no option to turn it off.
If you "don't want the UI to hang".... Put some sort of loading icon or text. It's a good practice for "ajax" stuff anyways...
Here is the code you could use :)
function checkIfMyConditionExists () {
$.ajax({
url: checkConditionURL,
async: false,
success: function (data) {
if (!data.success) {
return false;
}
// put your code to run something here!
}
});
}
It really doesn't need to be more complicated than that. Also something to keep in mind when implementing this...
Per the jQuery.ajax documentation:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
Another way to accomplish this would be to do the following.
Use a standard button on the form. (not a submit)
<button id="TriggerButton">Submit</button>
Handle the click of that button. Do your check. Submit the form if it's success!
$(function () {
$("#TriggerButton").click(function (e) {
e.preventDefault();
$.ajax({
url: checkConditionURL,
success: function (data) {
if (!data.success) {
// ruh roh!
return false;
}
// submit le form!
$("#MyForm").trigger("submit");
}
});
});
});
With this method, you could remove the onBegin and it should do what you need it to do. :)
I modified your code with a solution that works:
Ajax.BeginForm(onBegin="return checkIfMyConditionExists();"}...
function checkIfMyConditionExists(){
$.ajax({
url: checkConditionURL,
data: data,
async: false,
success: function (data) {
return data.condition;
}
});
note the async: false option that allows you to wait until the call ends and get the results after that.
My Working code
JavaScript/JQuery
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function StartValidation() {
var result = AjaxCall();
return result;
}
function AjaxCall() {
var Istrue = false;
$.ajax({
url : "#Url.Action("Json", "FileUpload")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({FirstName:'test', LastName:'test1'})
}).done(function() {
Istrue = true;
alert('ok')
})
.fail(function() {
Istrue = false;
alert('not ok');
});
return Istrue;
}
</script>
HTML
#using (Ajax.BeginForm("UploadRequestFile", "FileUpload", new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "return StartValidation();"
}, new { id = "frmUp" }))
{
<input type="submit" name="Submit" value="Submit" />
}
Runtime MarkUp
<form method="post" id="frmUp" data-ajax-method="POST"
data-ajax-begin="return StartValidation();" data-ajax="true"
action="/fileupload/UploadRequestFile?Length=10">
<input type="submit" value="Submit" name="Submit">
</form>
Check the data-ajax-method, data-ajax-begin and data-ajax attributes. Ajax.BeginForm helper emits those attributes. Those attributes mean absolutely nothing to the browser. It's the jquery.unobtrsuive-ajax.js script that understands and interprets them. Without it. So, no need to perform the Submit explicitly.
Action Methods
[HttpPost]
public JsonResult Json(string FirstName, String LastName)
{
//Do the Validation Part here.
return Json(new { Success = true });
}
[HttpPost]
public ActionResult UploadRequestFile()
{
return View();
}
I have this Ajax function inside my application.js file:
$("#project_person_id").change(function() {
$.ajax({
url: '/projects/get_invoice_types',
data: 'person_id=' + this.value,
dataType: 'script'
})
});
Is it possible to use a locale inside that function?
When I change line 3 to this:
url: '/de/projects/get_invoice_types',
I get the desired outcome (i. e. the output in German).
But of course I would like to set this dynamically. How can this be done?
Thanks for any help.
you can set it dynamically wherever you like, i.e
var locale = "de"; // set it dynamically
and the use it as a global, like this
$("#project_person_id").change(function() {
$.ajax({
url: "/"+locale+'/projects/get_invoice_types', // use it
data: 'person_id=' + this.value,
dataType: 'script'
})
});
a more elegant why would be to set it as a data attribute to the body tag <body data-locale="de"> or to the HTML head <html lang="de">, and pull it using a function
function locale() { return $("body").data("locale") } or
function locale() { return $("html").attr("lang") } and then retrieve it like this:
$("#project_person_id").change(function() {
$.ajax({
url: "/"+locale()+'/projects/get_invoice_types', // use it
data: 'person_id=' + this.value,
dataType: 'script'
})
});
there are other options of course, these seem straightforward.
I solved this issue modifying $.get and $.post jQuery's functions.
I my case the locale is a parameter in the url, but it can be injected as Sagish did too
(function ($) {
var oPost = jQuery.post;
var oGet = jQuery.get;
jQuery.post=function(url , data , success , dataType ){
if (typeof data === "undefined") {
data={};
}
data=add_locale_to_url(data);
return oPost.apply(this,[url , data , success , dataType]);
}
jQuery.get=function(url , data , success , dataType ){
if (typeof data === "undefined") {
data={};
}
data=add_locale_to_url(data);
return oGet.apply(this,[url , data , success , dataType]);
}
})(jQuery);
And when I call $.get or $.post the locale is automatically added to the URL:
...
var remote_search=$.get("/expenses/search_users/"+$(this).val());
remote_search(function( data ) {
$("#processing").hide();
alert( "Usuari inexistent");
obj_error.val("");
});
...
I solved this issue by adding data attributes to my erb template.
<button type="button" class="btn btn-success" id="save-job-position-btn" data-locale="<%= params[:locale] %>"><%= t("save") %></button>
$( "#save-job-position-btn" ).click(function() {
var locale = $(this).data("locale");
}
I have a page that will make an external call on a button click, and then update the button to reflect success. The ajax calls work properly, however I am having difficulty trying to manipulate the text of the button when there are many on the page.
It is easy enough to match using $(".sabPauRes.ui-btn-text").text("Updated"); when it's the only item on the page, but I am not sure how to point to it using $(this) when I am using the each function. I read a bit about 'closest', but it doesn't seem to accomplish what I want (or I'm just doing it wrong).
Code sample below!
$(document).ready(function(){
$('.sabPauRes').each(function() {
$(this).click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: this.href,
cache: false,
dataType: "text",
success: onSuccess
})
})
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
})
function onSuccess(data)
{
// validate the result of the ajax call, update text, change button methods as needed
if (data == "Success") {
// PROBLEM -- how do I use $this to match a class that is nested within it?
$(this).closest(".ui-btn-text").text("Updated");
} else {
alert("Failed: " + data);
}
$("#resultLog").html("Result: " + data);
}
})
})
html
<body>
<div data-role="page">
<div data-role="content">
<div data-role="collapsible">
<h3>This is an item</h3>
<p>
Resume Download
<div id="resultLog"></div>
</p>
</div>
</div>
</body>
Found the answer within Change button text jquery mobile
If you assign $(this) to a variable, then you can reference it in the .text() function as shown below:
$(document).ready(function(){
$('.sabPauRes').each(function() {
$this = $(this);
$(this).click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: this.href,
cache: false,
dataType: "text",
success: onSuccess
})
})
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
})
function onSuccess(data)
{
// validate the result of the ajax call, update text, change button methods as needed
if (data == "Success") {
alert(data);
$(".ui-btn-text",$this).text("Updated");
} else {
alert("Failed: " + data);
}
$("#resultLog").html("Result: " + data);
}
})
})
First things first. Please stop using jquery ready handler when working with jQuery Mobile. Give your page an id and use pageinit() event instead.
pageinit = DOM ready
One of the first things people learn in jQuery is to use the
$(document).ready() function for executing DOM-specific code as soon
as the DOM is ready (which often occurs long before the onload event).
However, in jQuery Mobile site and apps, pages are requested and
injected into the same DOM as the user navigates, so the DOM ready
event is not as useful, as it only executes for the first page. To
execute code whenever a new page is loaded and created in jQuery
Mobile, you can bind to the pageinit event.
You can save a ref to the clicked button and use it in success and error handlers like this:
$(document).on("pageinit", "#page1", function(){
$(document).on("click", "a.sabPauRes", function(event){
event.preventDefault();
//Save a ref to the clicked button
$this = $(this);
$.ajax({
type: "GET",
url: this.href,
cache: false,
dataType: "text",
success: function (data){
// validate the result of the ajax call, update text, change button methods as needed
if (data == "Success") {
$this.find(".ui-btn-text").text("Updated");
} else {
$this.find(".ui-btn-text").text("Failed");
}
$("#resultLog").html("Result: " + data);
},
error: function(jqXHR, textStatus, errorThrown) {
$this.find(".ui-btn-text").text("Error");
$("#resultLog").html("Error Calling: " + $this.attr("href") + "<br />HTTP Code: " + jqXHR.status + " " + jqXHR.statusText);
}
})
});
});
Here is jsFiddle