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
},
Related
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?
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 + "¬e=" + 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');
});
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.
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
I have following code.I show user a fancybox and they click Submit on Form I close fancybox and show them processing on page and do an AJAX post using JQuery. But some how fancybox gets stays open until AJAX form post is completed.Which creates confusion for user .
function BeginProcess(){
$.fancybox.close();
$("#imgProcess").attr("src", "/admin/images/loading_animation.gif");
$('#imgProcess').show();
PostAJAXForm();
}
function PostForm(FormData){
$.ajax({
type: "POST",
url: "process_image.jsp",
data: FormData,
contentType: "application/x-www-form-urlencoded",
async: false,
success: function(response) {
response = $.trim(response);
$('#imgProcess').delay(10000).hide();
return response;
},
error: function(xhr, ajaxOptions, thrownError) {
alert("There was an error. Please undo image and perform action again. " );
$('#lblProcess').delay(5000).hide();
return;
}
});
}
Here's a snippet:
var params = $(this).serialize();
var self = this;
$.ajax({
type: 'POST',
url: self.action,
data: params,
beforeSend: function(){
alert('Closing');
$.fancybox.close();
},
success: function(data){
alert('Finished processing form');
return false;
},
dataType: 'json'
});
Sorry if something is messed up or left out from that snippet - but you should get the idea.
You need to add $.fancybox.close() in Jquery' Ajax's beforeSend function.
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/ajaxSend/
This should help you out too
http://snipplr.com/view/47979/close-a-fancybox-when-you-submit-a-form-with-ajax