Very new to JQuery AJAX here. I have been looking around for a answer for awhile on this and can't find an answer.
I have a form that users would fill out. Once filled click on submit. This starts an ajax call to an asp page and basically just displays the information that was entered and fades out the user form. A confirm button below that takes the user to another .asp page that puts it into a database and gives them a ticket number.
My issue is that on the second call ( page that does the input ) , I notice in firebug that the get is happening twice. If I try the asp page alone it is only doing the input once so it's not my sql code. If I switch the second .asp page with the first it works fine.
Here is my jquery. I appreciate any comments. Thanks
$('#submit').click(function (event){
event.preventDefault(); // DECLARE EVENT IN THE CLICK FUNCTION
//Get the data from all the fields
var posting = 'no';
var firstname = $('input[name="firstname"]');
var lastname = $('input[name="lastname"]');
var phone = $('input[name="phone"]');
var email = $('input[name="email"]');
var family_size = $('select[name="family_size"]');
var date_3 = $("#date3");
var date_4 = $("#date4");
var book_option = $('input[name=book_option]:radio:checked');
var payment_type = $('input[name=payment_type]:radio:checked');
var comments = $('textarea[name="comments"]');
if (firstname.val()=='') {
firstname.addClass('fn_error');
firstname.focus();
return false;
} else
firstname.removeClass('fn_error');
if (lastname.val()=='') {
lastname.addClass('ln_error');
lastname.focus();
return false;
} else
lastname.removeClass('ln_error');
if (phone.val()=='') {
phone.addClass('fn_error');
phone.focus();
return false;
} else
phone.removeClass('fn_error');
if (email.val()=='') {
email.addClass('ln_error');
email.focus();
return false;
} else
email.removeClass('ln_error');
// TEST FOR VALID EMAIL
var email_pattern=new RegExp("^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
var email_result = email_pattern.test(email.val());
if( email_result == true ) {
email.removeClass('fn_error');
}else{
email.addClass('fn_error');
email.focus();
return false;
}
// TEST FOR VALID PHONE NUMBER
var phone_pattern=
new RegExp("^(\\(?\\d\\d\\d\\)?)?( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$");
var phone_result = phone_pattern.test(phone.val());
if( phone_result == true ) {
phone.removeClass('fn_error');
}else{
phone.addClass('fn_error');
phone.focus();
return false;
}
var dataString= 'firstname=' + firstname.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&email=' + email.val() + '&family_size=' + family_size.val() + '&date3=' + date_3.val() + '&date4=' + date_4.val() + '&book_option=' + book_option.val() + '&payment_type=' + payment_type.val() + '&comments=' + comments.val() + '&posting=' + posting;
//alert(dataString);
$('#ticketform').fadeOut('slow', function() {
$('#testdiv').load('../resources/confirm_ticket.asp', dataString, function() {
$('#generateform').fadeIn('slow');
$('#submit').unbind('click');
});
}); // LOAD CLOSE
}); // SUBMIT CLICK FUNCTION CLOSE
$('#gen').click(function (event){
event.preventDefault(); // DECLARE EVENT IN THE CLICK FUNCTION
var firstname = $('input[name="firstname"]');
var lastname = $('input[name="lastname"]');
var phone = $('input[name="phone"]');
var email = $('input[name="email"]');
var family_size = $('select[name="family_size"]');
var date_3 = $("#date3");
var date_4 = $("#date4");
var book_option = $('input[name=book_option]:radio:checked');
var payment_type = $('input[name=payment_type]:radio:checked');
var comments = $('textarea[name="comments"]');
var dataString= 'firstname=' + firstname.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&email=' + email.val() + '&family_size=' + family_size.val() + '&date3=' + date_3.val() + '&date4=' + date_4.val() + '&book_option=' + book_option.val() + '&payment_type=' + payment_type.val() + '&comments=' + comments.val();
alert(dataString);
$('#testdiv, #generateform').fadeOut('slow', function() {
$('#message').load('../resources/generate_ticket.asp', function() {
$('#message').fadeIn('slow');
});
}); // LOAD CLOSE
}); // SUBMIT2 CLICK FUNCTION CLOSE
First off, a better way to verify if a field is filled in is to use jQuery $.trim(), it will trim all white space in the beginning and end so if someone enters a bunch of spaces, it will return false still. This is how you would do it:
if ($.trim(firstname.val())) {
firstname.addClass('fn_error');
firstname.focus();
return false;
}
This is a much better way to verify if it is empty, but an even better idea is to use the jQuery Validation plugin, in which you can simple put class="required", class="required email", etc. for each rule (they can also be defined in the javascript if you prefer).
Also, I see that you keep using .load. Did you know a thing called $.get exists? It is a little more powerful way to send a get request and you don't have to load it into an element to make it work (there's also $.post). I used to use .load myself all the time a while back until I discovered $.get and $.post. This is an example with your code:
$.get('../resources/confirm_ticket.asp', dataString, function(data) { // data is what is returned from the request (html, etc.)
$('#generateform').fadeIn('slow');
$('#submit').unbind('click');
});
Anyway, now to your question.
I don't see any problems of why it would be doing that, but it could be a bug with the browser or something (usually not but this happened to me before too and I never found out how to fix it). Have you tried it in other browsers like Google Chrome or Safari?
I got the answer from a forum today. Can't remember where but the answer is....
$('#testdiv, #generateform').fadeOut('slow', function() {
$('#message').load('../resources/generate_ticket.asp', function() {
$('#message').fadeIn('slow');
});
I have 2 selectors in the fadeOut. It was calling the load function twice for each selector. Changed it and now I'm only getting the one GET request. Thanks for the help though all! :) Happy Coding!
Related
I have a button that executes a function:
$("#btnRemove").click(function () {
var name= $("#editAccountName").val();
if (confirm("Are you sure you want to mark " + "''" + name + "''" + " as innactive?")) {
saveAccount(false);
window.location.href = "/RxCard/Search";
}
alert (name + "was marked innactive.")
});
I need the alert to show after the user is redirected to "/Rxcard/Search"
what do i need to change in my code to get it working like that?
on a side note, how would do the same but with a CSS customized alert?
Thanks.
Instead of putting your alert in this code, you need to put it into the script behind Search page. Now you can add a url parameter and then in there check it and show the alert if that parameter is set:
if (confirm("Are you sure you want to mark " + "''" + name + "''" + " as innactive?")) {
saveAccount(false);
window.location.href = "/RxCard/Search?name=" + name;
}
And then add this somewhere (doesn't matter that much):
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
And at last this code goes into your search page code:
function() {
if($.urlParam('name') == true){
alert (name + "was marked innactive.");
}
}();
You cannot run an alert after the location.href has changed because it causes the browser to refresh. Once refreshed, your script is no longer running.
You would need to move your alert script into your search page and perhaps pass the name as a querystring arguement.
You could store the name value using localstorage. The value can be evaluated after the redirection so you can display the dialog with the stored value (if any)
You can't style your alert dialog but you can always create a modal dialog from scratch or by using a web framework / library.
this is the same question i asked before. sorry but i check all the link provided it doesnt help. and sorry this is the first time i asked question here so was not very clear about how to ask
I am explaining here again with full details:
i have an input text field.
I Use jquery to validate the input date entered by user in this input box.
I pass the data enter as parameter in javascript GET method and pass it to PHP and validate it there with simple REG Ex. It does validate in all account. But if i add # with any test case this validation fails.
my code:
Input field:
<div id="clntFstName" >
<label for="clnt_fst_name">First Name</label>
<input type="text" id="clnt_fst_name" name="clnt_fst_name" onBlur="checkFieldValid(this.value, this);" value=""/>
<div class="msgError"></div>
</div>
If you the function CheckFieldValid is called as the user leaves a field input box.
java script:
function checkFieldValid(value, obj) {
var elem = obj.name;
$('#' + elem).parent().children('.msgError').html('');
var $label = $("label[for='" + obj.id + "']").text();
var $id = obj.id;
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" + value + "&lab=" + $label + "&id=" + $id, function(json) {
if (json.status.length > 0) {
$.each(json.status, function() {
if (this['fail'] == 'fail') {
var info = '<div class="warningMsg"> ' + this['message'] + '</div>';
$('#' + elem).parent().children('.msgError').html(info);
$('#' + elem).focus();
$('#' + elem).val("");
}
if (this['success'] == 'success') {
$('#' + elem).parent().children('.msgError').html('this is success');
}
});
if (json.status == 'empty') {
$('#' + elem).parent().children('.msgError').html('this is empty');
}
}
});
}
PHP code:
if($_GET['action'] == 'checkInputFieldValid'){
if(!empty($_GET['varField'])){
// this creates dynamic session variables and add values to it.
$_SESSION[$_GET['id']] = $_GET['varField'];
if(preg_match('/^[a-zA-Z]+$/',$_GET['varField'])){
$txtVar = 'It is a valid '.$_GET['lab'];
array_push($validFieldArray, array('success' => 'success', 'message' => $txtVar));
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 0;
}else{
$txtVar = 'Enter a valid '.$_GET['lab'];
array_push($validFieldArray, array('fail' => 'fail', 'message' => $txtVar));
unset($_SESSION[$_GET['id']]);// unset the session variable to clear when page refresh
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 1;
}
}
}
I dont know where I am wrong? I did all as told by other members May be I am doing something wrong with Java script when I pass the GET request variables? as far as
I think I did exactly what other member told me about PHP part. but may be the data is wrong when i take it from Java script part? As i checked it with other values return from PHP. but when I put # in my input box IT does not make the AJAX call and doesnt return the JSON nor set the session variable. So probably when I pass the varible as GET parameter It doesnt run the AJAX and just doesnt validate so plz tell me how can i pass # as GET parameter so that i correctly validate the fields in my PHP .
Plz help I will loos my job :(
Your $.getJSON call should use encodeURIComponent() to make sure you're not creating the wrong URL:
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" +
encodeURIComponent(value) +
"&lab=" +
encodeURIComponent($label) +
"&id=" +
encodeURIComponent($id), function(json) {
If you don't do that, then a # character will be interpreted as signalling the start of the hash field of the URL, and the rest of the URL will be ignored.
I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>
I have a JavaScript function that goes through a list of checked checkboxes and uploads a video file for each checked box. I'm trying to make sure that the videos have been transcoded into a smaller format before I begin the upload process. I use to track the index in the array videos, that have completed the transcode process. I check to be sure that counter is >= id before starting the upload process for a given video. If counter is too low (the file is not yet transcoded) I use setTimout() to call the uploadVideos function again. It never seems to call the uploadVideos function again, because I never see the alert popup a second time.
How can I get this to work?
function uploadVideos(id, videos, selected, boxes) {
var status = document.getElementById('currentUploadStatus');
// need to deal with element an array
var fields = videos[id].split(":", 2);
var playlist = document.getElementById('playlist');
var dataString = 'videoId='+ fields[0] + '&playlist=' + escape(playlist.value);
// need to determine the maxTranscodedId
var counter = document.getElementById('counter');
alert('counter: ' + counter.innerHTML + " id: " + id);
if (counter.innerHTML >= id) {
id++;
status.innerHTML = "<b class='status'>Uploading Bout #" + fields[1] + " (" + id + " of " + videos.length + ")</b>";
$.ajax({
type: "GET",
url: "floUpload.php",
data: dataString,
success: function(txt) {
if (txt != 'Success') {
alert(':' + txt + ':');
}
if (id < videos.length) {
uploadVideos(id, videos, selected, boxes);
} else {
//re-enable the start button
var startButton = document.getElementById('start');
startButton.disabled = false;
status.innerHTML = "<b class='status'>Upload Complete</b>";
alert('Upload Completed');
}
//deselect the checkbox
if (boxes == 1 ) {
document.videos.video.checked = false;
document.videos.video.style.display = 'none';
} else {
document.videos.video[selected[id-1]].checked = false;
document.videos.video[selected[id-1]].style.display = 'none';
}
},
async: true
});
} else {
// timer call myself the same way I was called
status.innerHTML = "<b class='status'>Upload waiting for trancode.</b>";
var t=setTimeout("uploadVideos(id, videos, selected, boxes)",3000);
//var t=setTimeout("alert('waking')",3000);
}
}
This is a common error in JS beginners. setTimeout admits either one of two kinds of first parameter:
a) Text, in which you can put JS code to be evaluated out of scope (so referenced variables may be undefined), not quite helpful.
b) Function, such as the fix I propose for this, is to replace the line:
setTimeout("uploadVideos(id, videos, selected, boxes)",3000);
with:
setTimeout(function(){
uploadVideos(id, videos, selected, boxes);
},3000);
As you can see I'm wrapping the function call inside another anonymous function. Why? simply because I need to pass arguments, and otherwise I'd be just calling it, instead of passing as argument.
I have the following function:
function checkEmails(newEmail){
$('table td:nth-child(3)').each(function(){
if ($(this).html() == newEmail)
{
alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.');
toggleSpinner();
return false;
}
});
return true;
}
I'm calling it this way in my form submit handler:
if (!checkEmails($('input#email', $('#newForm')).val())) {
return false;
}//I submit the form via ajax next....
I'm just checking to make sure that the email address the user's trying to submit isn't already in a table. It seems to work good, except in Firefox, it doesn't actually stop the ajax request from occurring. The alert box appears, telling me the user's already in the list, but after clicking ok, the form is submitted anyway. It works as I want it to in IE.
What am I doing wrong here?
it should probably be done like this:
function checkEmails(newEmail){
var ret = true;
$('table td:nth-child(3)').each(function(){
if ($(this).html() == newEmail)
{
alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.');
toggleSpinner();
ret = false;
}
});
return ret;
}
What it is doing is setting the return value to true before doing the each on the elements to, then if it finds any invalid email addresses it will set it to false. That is the value that will be returned from the function.
the return false is inside the closure so it doesn't break out of the outer function
i.e. it returns false for the nested function and not for checkEmails
I think you want this (use a bigFatGlobal to store the return value):
function checkEmails(newEmail){
var bigFatGlobal = true;
$('table td:nth-child(3)').each(function(){
if ($(this).html() == newEmail)
{
alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.');
toggleSpinner();
bigFatGlobal = false;
}
});
return bigFatGlobal;
}