jQueryMobile - looping each button to change text of nested tag on click with ajax - jquery-mobile

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

Related

<function> is not defined at HTMLButtonElement.onclick

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?

Kendo Date Picker failing in MS Edge Browser

I have created this partial view as a pop-up to enable the user to edit the date and save. Kendo date picker fails on Edge browser. All the date fields turn blank when opened in this particular browser(when date picker already has a date assigned to it).Works fine in all the other browsers like Chrome, Mozilla and IE. Kendo UI version is v2013.3.1119.
Can you please suggest any fix?
<script type="text/javascript">
// This method opens the popup window.
function EditMiscDates() {
$('#edit-dca-misc-dates-div').kendoWindow({
width: "1100px",
title: "Milestone Dates",
actions: ["Close"],
draggable: false,
modal: true,
resizable: false,
activate: function () {
// set focus to the first control
$("#mcd-code-check-scheduled").focus();
}
});
// Center the window and open it
$('#edit-dca-misc-dates-div').data("kendoWindow").center();
$('#edit-dca-misc-dates-div').data("kendoWindow").open();
}
function OnMiscDatesSuccess(data) {
//console.log('OnMiscDatesSuccess called.');
// If the service returned with an error message, show the message to the user
if (!data.IsValid) {
console.log("Error (" + data.Messages + ")");
// Allow the user to retry
EnableMiscDatesClose(true); // let them close the window
$("#error-text-misc-dates").html("An error occurred: " + data.Messages);
$("#error-text-misc-dates").show();
return;
}
// The method successfully executed so we can close the popup window and reload the main page.
CloseMiscDatesPopup();
// Redirect back to the Index page to reload the data
window.location = '#Url.Action("Index", "Dca", new { id = Model.OrderId })';
}
// This method allows us to enable or disable the close button on the main window
function EnableMiscDatesClose(enable) {
$('#edit-dca-misc-dates-div').parent().find(".k-window-action").css("visibility", (enable ? "" : "hidden"));
}
// Handle the user clicking the cancel button
function CloseMiscDatesPopup() {
EnableMiscDatesClose(true);
$("#error-text-misc-dates").hide(); // Hide error message (if exists)
$('#edit-dca-misc-dates-div').data('kendoWindow').close();
}
function GetMiscDatesJson() {
// Note: Something prepends "step_" to the front of every id (with the odd exception of the Kendo controls). So I have to
// manually make the ajax call to submit the form (or it can't match the field names with the model parameters)
var orderId = $("#step_mcd-order-id").val();
var mcdCodeCheckScheduled = $("#mcd-code-check-scheduled").data("kendoDatePicker").value();
mcdCodeCheckScheduled = kendo.toString(mcdCodeCheckScheduled, "MM/dd/yyyy");
var o = {
OrderId: orderId,
CodeCheckScheduled: mcdCodeCheckScheduled
};
return o;
}
// This method validates the data entered by the user.
// If it is invalid, it shows a detailed error message; otherwise it submits the form via ajax
function ValidateAndSubmitMiscDates() {
var d = GetMiscDatesJson();
var s = JSON.stringify(d);
console.log(s);
// Submit the form via ajax
$.ajax({
type: 'POST',
url: '#Url.Action("SaveConversionMiscDates", "Dca")',
dataType: 'json',
data: s,
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log('success!');
OnMiscDatesSuccess(data);
},
error: function (xhr, status, error) {
console.log('error!');
EnableMiscDatesClose(true); // let them close the window
$("#error-text-misc-dates").html("An error occurred: " + error);
$("#error-text-misc-dates").show();
}
});
}
</script>
<div id='edit-dca-misc-dates-div' style='display:none'>
<div class="k-block k-error-colored" id="error-text-misc-dates" style="display: none"></div>
<div class="mcd-label">Scheduled</div>
#Html.Kendo().DatePicker().Name("mcd-code-check-scheduled").Value(Model.CodeCheckScheduled)
</div>
<div style="padding-top:6px;text-align:right">
<button class="k-button" onclick="ValidateAndSubmitMiscDates()">Save</button>
Cancel
</div>
Fixed in the latest build: 2015.2.902.545

How do you run trigger("create") on content loaded with ajax?

I have a function that refreshes the content on a page after a form is filled out. It works but the jquery mobile elements are not formatted. Calling trigger() is not working because apparently it is getting called before the elements appear on the page. Here's the code:
function add_note() {
var vid = $("#basic_note_vid_hidden").val();
note = $("#basic_note_textarea").val().replace(/(\r\n|\n|\r)/gm,"<br />");
$.ajax({
async: true,
type: "POST",
url: "ajax.pl",
data: "action=add_note&vid=" + vid + "&note=" + note,
error: function(res) {
$.growl({title:"Update failed!", style: "error",message:"Are you connected to the Internet?", static:true, size: 'medium' })
},
success: function(res) {
$.growl({title:"Update successful", message:"Note added", duration:500, size: 'small' });
$("#basic_note_close_button").click();
$("#basic_note_textarea").val('');
$("#notes .ui-content").load('ajax.pl?action=print_note_ajax&vid=' + vid).parent().trigger('create');
},
});
}
The meat of the matter is the very last line of code. Is there a way to detect when the new content gets loaded into the page so I know when I can call the trigger() function?
I'm obviously still learning basic jquery. Answer was in the docs for load():
$("#notes .ui-content").load('ajax.pl?action=print_note_ajax&vid=' + vid, function() {
$('#notes .ui-content').trigger('create');
});

Ajax call will not work without preventDefault

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
},

asp.net mvc4 jquery ui autocomplete not working

I want to use autocomplete widget in asp.net mvc4 app. I was able to call the action to get list of autcompletition values from controller. Unfortunetely I am not able to add it to list of suggestions. I think that .map(data, function(item) in success part of autocomplete ajax call is not working. But I really do not know why. I am sure that all the scripts and css are load corectly. I am stating controller action returining suggestions list, also script in view and response from firebug. I was also trying the demo example from jqueryui page and it was working, but somehow it does not work over my returned data. Can someone help me and tell me why? Thank you in advance.
Action in Controller:
public ActionResult GetCities(int RegionId, string Name)
{
var ret = db.Cities.Where(c => c.RegionId == RegionId &&
c.Name.Contains(Name)).Select(a => new{ CityId = a.CityId, Name = a.Name});
return Json(ret);
}
Script in view:
<script type="text/javascript">
$(function() {
$("#City").autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("GetCities")",
dataType: "json",
contentType: "application/json; charset=utf-8",
method: "POST",
data: "{'RegionId': " + $("#Region").val() + ", 'Name': '" + request.term + "'}",
success: function (data) {
response( $.map( data, function( item ) {
return {
label: item.Name,
value: item.Name
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
Response (from firebug)
[{"CityId":16,"Name":"Kordíky"},{"CityId":94,"Name":"Korytárky"}]
So I find out it was working, the only problem was, that I had breakpoint in visual studio and this breakpoint was supressing autocomplete suggestion list.
for Mvc Artitecture you must delete already imbended #Scripts.Render("~/bundles/Jquery") and #Scripts.Render("~/bundles/Jqueryval")
on all .cshtml files at the end and for also views/Shared/_layout.cshtml at the
end and put our jaquery suitable files on his suitables .cshtmls files in head...and lets enjoy.

Resources