this is my code:
$("#MainContent_btnSave").click(function () {
if (($("#MainContent_txtFunc").val() == "") || ($("#MainContent_cmbLoc").val() == "")) {
alert("Please fill options.");
return false;
}
else {
$("#msgbox-loading").show();
$.ajax({
type: "POST",
url: "Ajax.aspx",
data: { func: "getexist", catfunc: $("#MainContent_txtFunc").val(), catdes: $("#MainContent_txtDesc").val() },
success: function (data) {
var parsed = $(data);
var exist = parsed.filter("[id=exist]").text();
if (exist == "NO") {
return true;
}
if (exist == "Yes") {
alert("already defined.");
$("#msgbox-loading").hide();
return false;
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#msgbox-loading").hide();
HidePopup('popup');
alert(xhr.status + " " + thrownError);
}
});
};
});
My code is check mandatory and If empty mandatory, an error message display and or if not empty mandatory, first display the loading and then Ajax run.
After running Ajax i want if page send "NO" run button postback and if page send "Yes" stop button postback.
but Unfortunately, after run ajax and page send "Yes" run button post back.
please help.
you can use .ajaxComplete() for commands that you want to fire after ajax completed
Related
I have a login form and a captcha field. I need a javascript source to check this captcha input then send post data to action but my code seems to be wrong, the e.preventDefault function doesn't work because captcha field true or false post data's still sent. please help.
This my javascript Function:
$(document).ready(function () {
$("#signupform").submit(function (event) {
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
event.preventDefault();
//Form post data still sent?
}
}
});
}
else alert("Captcha not null");
});
});
You need to move event.preventDefault(); up so it comes before the ajax call.
Use $("#signupform").submit(); in an else block to programmatically submit the form.
$(document).ready(function () {
$("#signupform").submit(function (event) {
event.preventDefault();
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
//Form post data still sent?
} else {
$("#signupform").submit();
}
}
});
}
else alert("Captcha not null");
});
});
You would need have the form event.preventDefault(); before making the ajax request.
$("#signupform").submit(function (event) {
event.preventDefault();
When the ajax request is returned, you can submit the form using:
if (data != 0) {
$("#signupform").submit();
}
I have the following script for AJAX to do login, but with some passwords that contain characters like "!##" it will return 403 error and will not submit to the PHP.
$(document).ready(function () { // When the document is ready
$('#login').click(function (e) { // We attach the event onchange to the select element
e.preventDefault();
var form_info = "";
$('#login_form *').filter(':input').each(function(){
if(this.value !== ""){
form_info += this.name;
form_info += "=";
form_info += encodeURIComponent(this.value);
form_info += "&";
}
});
form_info += "function_name=login";
var form = $('#login_form').serialize() + "&function_name=login";
$.ajax({
url: "function_ajax.php", // path to you php file
type: "post", // We want a POST request
dataType: 'html',
data: form_info,
statusCode:
{
404: function () {
alert('Could not contact server.');
},
500: function () {
alert('A server-side error has occurred.');
}
},
error: function ()
{
alert('A problem has occurred.');
},
beforeSend: function ()
{
alert(form_info);
alert(form);
},
complete: function ()
{
},
success: function (data) { // The function to execute if the request is a -success-,
if(data === "1"){
if (document.referrer !== "") {
window.location.href = document.referrer;
}
else{
window.location.href = "some_domain"
}
}
else if (data === "2")
{
alert("invalid");
}
else {
alert("empty");
}
}
});
});
});
You will find that I'm trying both ways to encode each element and the serialize just to check if I'm getting the same result, and I'm getting the same result, but still, it's getting this error.
If I try to encode the whole serialize, then I will not get the error but in PHP, the $_POST array will have the first key as the data I'm sending with no value.
encodeURIComponent($('#login_form').serialize()) + "function_name=login"
then the $_POST will be like
array(
[email=email#gmail.com&password=pass123!##&function_name=login]=>
)
which will not be useful for me.
function update(){
var name= document.getElementById("TextBox").value;
$.ajax({
url: '....',
type: 'post',
data: {....//many data include// 'name' : name, ....},
success: function(data) {
var replacevalue=data.replace(/[\[\]']/g,'' );
alert(replacevalue);
var stringstatus=replacevalue.replace(/['"]+/g, '');
alert(stringstatus);
if(stringstatus == "success"){
alert ("Successfully Update ")
}
else{
alert("Failed!");
return ;
}
returnToDisplayPage();
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
function returnToDisplayPage(){
var id = document.getElementById("TextBox").text;
window.location = './DisplayPage.php?Name='+id;
}
Please suggest me. How should I do to get the updated data when click update button and refresh or reload page ? In function returnToDisplayPage() methods. I got only the name of update data and other related fields data didn't get back.
Try something like this:
$.post('url', {params}, function(response){
//Here you check if you got response from url
// And then you can do whatever you like to do with received data
if(response == 'ok'){
//do your stuff
//then
window.location.reload();
}
}
When we will get result in response then After 5 seconds page will be refresh..
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
I am trying to make an instant search drop down for my site. All work fine, except for this.
var timeOut;
$('#search input[name=\'search\']').on('keyup', function(e) {
// If enter - submit the search field
if (e.keyCode == 13) {
$('header input[name=\'search\']').parent().find('button').trigger('click');
}
// Call only when length is at least 2 and the key pressed is alphanumeric
else if ($('#search input[name=\'search\']').val().length>2 && ((e.keyCode>=65 && e.keyCode<=90) || (e.keyCode>=97 && e.keyCode<=122))) {
timeOut = null;
//alert(timeOut);
if (!timeOut) {
timeOut = setTimeout(function() {
$.ajax({
url: 'ajax.php',
type: 'post',
async: false,
data: 'ACTION=SEARCH&search='+$('#search input[name=\'search\']').val(),
dataType: 'json',
beforeSend: function() {
$('#loader-icon').show();
},
complete: function() {
$('#loader-icon').hide();
},
success: function(json) {
//$('.product-list-row').html(json);
$('#search-listing').html(json['html']);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
timeOut = null;
}, 500);
}
}
});
Problem 1: My script ends up making too many calls to the server, for some reason setTimeOut isn't working as I expected it to. Ajax call should only be made when the user has done typing or something like that and not at every key press.
Problem 2: For some reason when I type fast the input bar doesn't get edited. The ajax however works, but with the last textual input.
Instead of trying to tackle this with setTimeout, you can abort the previous call using the jqXHR object returned by the AJAX. It is more clean and simple to use this. Remove async: false, too.
var timeOut;
var xhr;
$('#search input[name=\'search\']').on('keyup', function(e) {
// If enter - submit the search field
if (e.keyCode == 13) {
$('header input[name=\'search\']').parent().find('button').trigger('click');
}
// Call only when length is at least 2 and the key pressed is alphanumeric
else if ($('#search input[name=\'search\']').val().length>2 && ((e.keyCode>=65 && e.keyCode<=90) || (e.keyCode>=97 && e.keyCode<=122))) {
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax.php',
type: 'post',
data: 'ACTION=SEARCH&search='+$('#search input[name=\'search\']').val(),
dataType: 'json',
beforeSend: function() {
$('#loader-icon').show();
},
complete: function() {
$('#loader-icon').hide();
},
success: function(json) {
//$('.product-list-row').html(json);
$('#search-listing').html(json['html']);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
});
The right solution is combination of both, abort running request, if new one should be made, and also, tackle firing of the new request. You can use underscore library, which has nice function for that, called debounce (see http://underscorejs.org/#debounce) and your code should looks like this:
// This is your xhr, each request save into this
// variable, in order to be able to abort it if needed
var xhr;
// Wrap your event handler using the debounce function
$("#search").on("keyup", _.debounce(function(e) {
// Abort running request
if(xhr) {
xhr.abort();
xhr = null;
}
// Store the new request
xhr = $.ajax({
// Search for the term $(this).val()
});
},500));
There is no need to fire the search for each keyup, but only when user stopped typing - debounce will do it for you. And there is no need to handle previous results if the request should be made.
I have a radio button that displays a list of records in a telerik grid. When the radio button is checked, it displays complete and incomplete records. However, the user wants a way of displaying only complete or incomplete records. I added two mutually exclusive checkboxes. The user can either check the complete or incomplete checkbox to display the data. It works fine on my local, but it does not work well on the server. The first time, the user has to click the checkbox two or three times before it can keeps the state. In addition, if complete is checked and the user checked incomplete next, the checkmark will go back to complete. The user has to do it a second times. What I am doing wrong here?
Here is the html for the checkbox
#Html.CheckBox("complete", SessionWrapper.currentEncounter.complete, new { id = "chkComplete", onclick = "chkInCompleteOption(1);this.form.submit();" }) <strong>Complete</strong>
#Html.CheckBox("Incomplete", SessionWrapper.currentEncounter.incomple, new { id = "chkInComplete", onclick = "chkInCompleteOption(2);this.form.submit();" }) <strong>Incomplete</strong>
//Here is the javascript
var completeCheck = '#SessionWrapper.currentEncounter.complete';
var inCompleteCheck = '#SessionWrapper.currentEncounter.incomplete';
function chkInCompleteOption(e) {
if (e == 1) {
var cc = $('#chkComplete').is(':checked');
var data = { "complete": cc, "inComplete": false };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testComplete();
return true;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
else if (e == 2) {
var inc = $('#chkInComplete').is(':checked')
var data = { "complete": false, "inComplete": inc };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testInComplete();
return true;
// $('#chkComplete').removeAttr("checked", "checked");
// $('#chkInComplete').attr("checked", "checked");
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
}
function testInComplete() {
if (inCompleteCheck == true) {
inCompleteCheck = $('#chkInComplete').attr("checked", "checked");
document.getElementById('chkInComplete').checked = true;
} else {
$('#chkInComplete').removeAttr("checked");
}
}
function testComplete() {
if (inCompleteCheck == true) {
completed = $('#chkComplete').attr("checked", "checked");
document.getElementById('chkComplete').checked == true;
} else {
$('#chkComplete').removeAttr("checked");
}
}
//Setting the mutually exclusive value on the server side
public bool CompletedOption(bool complete, bool inComplete)
if (inComplete == true && complete == true)
{
return false;
}
if (complete == true)
{
SessionWrapper.currentEncounter.complete = true;
}
else if (SessionWrapper.currentEncounter.complete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.complete = true;
}
else
{
SessionWrapper.currentEncounter.complete = false;
}
if (inComplete == true)
{
SessionWrapper.currentEncounter.incomplete = true;
}
else if (SessionWrapper.currentEncounter.incomplete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.incomplete = true;
}
else
{
SessionWrapper.currentEncounter.incomplete = false;
}
return true;
}
I found the issue. The server side was being updated properly; however, the ajax was returning an error message every time it executed. The method on the server side was returning a Boolean when a string was expected. I've also set async and cache to false. I ran the application again, and it works.
//Change Method Signature from boolean to string
public string CompletedOption(bool complete, bool inComplete)
{
return "true";
}
ajax post
$.ajax({
url: url,
type: 'post',
dataType: 'text',
async: false, //Added
cache: false, //Added
data: data,
success: function (data) {
return data;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});