Javascript and ASP MVC - refreshing an image - javascript

I have a page that contains a captcha. whenever the user enters the captcha incorrectly the form will submit and they will move on. If not, i want to refresh the captcha image so that the user has to enter the new number. this code currently works in Chrome, but the image wont refresh in firefox. does not work in IE either.
javascript method:
function CheckCaptcha() {
var UserInput = $("#Captcha").val();
$.ajax({
type: "POST",
url: "/Messaging/CheckUserCaptcha",
data: { userCaptcha: UserInput },
success: function (data) {
//alert("SUCCESS: " + data.success);
//alert("SUCCESS2: " + data.message);
var correct = data.success;
if (correct == true) {
document.forms[0].submit();
} else { THIS IS WHERE I NEED TO REFRESH THE CLASS
alert(data.message);
$(".captchaImage").attr("src", "<%= Url.Action("CaptchaImage", "Messaging", new {prefix = "CaptchaImage"}) %>");
}
}
});
return false;
}
this is what the HTML looks like
<img src="/Messaging/CaptchaImage?prefix=CaptchaImage" class="captchaImage"></img>

i used the answer from this question to answer mine:
How to reload/refresh an element(image) in jQuery
so essentially my question may have been a copy of his question. it just took me a while to find the answer.
i added a var d, which was instantiated as a new instance of the Date object. then i concatenated onto my image the getDate() method.

Related

Previous data being added rather than replaced with current editing data

Trying to create a simple crud operation using edit and delete. Currently on edit functionality.
Functionality works like this:
1) user clicks on edit icon, bootstrap modal opens up with form information that is fetched from ajax request containing users id. Forms value fields are auto populated based on fetched ajax request.
2) User can edit the auto populating form fields editing the users information and a separate ajax request goes out that edits the users record.
Problem:
This all works how I wanted to but I noticed a small bug that I'm stuck on to where when I go edit a users information, hit send and then close out of the modal to open and edit another users information and hit send again, the previous forms data is added onto the data I'm currently editing and I don't want that. I just want to open up the modal and edit and send the current users data that I'm on.
In addition, I also noticed If I keep trying to edit multiple users information, multiple ajax requests are sent each time I try and edit another record. I tried looking up my problem and I think it's because of my events bubbling up in which I tried e.stopPropagation; and return false; and it did nothing to solve my problem. I feel like I'm close but there is something that I'm missing.
If you need my HTML code as well I'll be happy to show that.
Here is my code:
$(document).on('click', 'i.fas.fa-edit', function(userId){
emailField.value = 'Please wait...!';
fullnameField.value = 'Please wait...!';
areaField.value = 'Please wait...!';
personField.value = 'Please wait...!';
// By Default
adminAccess.checked = false;
personField.style.display = 'block';
adminAccess.addEventListener('click', function(){
if(adminAccess.checked == true) {
areaField.style.display = "none";
} else {
personField.style.display = "block";
}
});
var usersId = {
usersId: userId.target.id
}
// Select user data
$.ajax({
method: 'POST',
url: 'select-user-action.php',
data: usersId,
success: function(data){
var parseData = JSON.parse(data);
parseData.forEach(function(element){
emailField.value = element.email;
fullnameField.value = element.name;
areaField.value = element.areaField;
personField.value = element.personField;
});
}
});
});
$('#editModal').on('show.bs.modal', function () {
submitForm.addEventListener('submit', function(e){
// prevent form from submitting
e.preventDefault();
var editData = {
"email": emailField.value,
"fullName": fullnameField.value,
"areaField": areaField.value,
"personField": personField.value
};
// Previous data is being added onto current edited data.. This is what I'm stuck on.
console.log(editData);
// $.ajax({
// method: 'POST',
// url: 'edit-user-action.php',
// data: editData,
// success: function(data){
// console.log(data);
// }
// });
// this didnt work
return false;
});
});

jQuery Ajax placing random "jQuery111201xxx" into string

I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.
Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});

Troubles Submitting Form programmatically

I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.

$.ajax error getting back data from php file

I'm developing a website, and right now the registration form of it! But I have something like a problem! I want to create a Username input field, and when the user is typing, check if the username already exists in the database and give some output.
The error is this one: suppose that in the database there is only the username "Manuel". If I type "Manuel" in the input field no message is shown. Now if I type any other character it gives me the message 'The user already exists'. If i delete the last typed character the message goes away. If I type again and have something like "Manuela", the message shows up, if I type again and have "Manuelae" the message goes away
Thanks for your help!!
Here the code
Here the input field: (register.php)
<input type="text" id="username" name="username" maxlength="40" required="required">
<span id="username-info">What's your username?</span>
Here the javascript and jquery code (registration.js)
$(document).ready(function () {
var userExists = new Boolean();
var username = $("#username");
var usernameInfo = $("#username-info");
username.keyup(validateUsername);
}
Here the function validateUsername():
function validateUsername(){
checkUsername();
var minlenght = 5;
var usernameVal = username.val();
if(usernameVal.length < 1){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.FIELD_REQUIRED);
} else if(usernameVal.length < minlenght){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.USERNAME_MIN_WORDS+minlenght+' '+messages.USERNAME_CHARACTERS);
} else if(userExists){
//here i tell the user that the user already exists
usernameInfo.addClass("input-error");
usernameInfo.text('The user already exists');
} else {
usernameInfo.removeClass("input-error");
usernameInfo.text("");
}
}
And here the function checkUsername():
function checkUsername() {
var url = 'processregistration.inc.php';
$.ajax({
type: "POST",
dataType:"json",
url: url,
data: {username: username.val()},
success: function(data){
userExists = data.CHECK; //true if the user exists, false if not
}
});
}
Ajax means Asynchronous JavaScript and XML.
You are doing a check on a value which is actually not received.
You should do something like this :
function validateUsername() {
// remove input-error, text
if (...localcheck...) {
// add input-error, text
}
else if (...otherlocalcheck...) {
// add input-error, text
}
else {
$.ajax({
...
success : function(data) {
if (data.CHECK) {
// add input-error, text
}
}
});
}
}
I think you are on the right track, but I don't think your implementation is correct.
Note: I'm not a javascript hero
$("#filter").keyup( function(e) {
var filter = $("#filter").val(),
timer = $('#filter').data('timeout'),
if(timer) {
clearTimeout(timer);
$('#username').removeData('timeout');
}
$('#username').data('timeout', setTimeout(function() {
var url = 'processregistration.inc.php';
$.POST(url, {username: $('#username').val()}, function(data) {
// you get the picture ;)
updateComponentThatShowsIfUserNameIsTakenFunction(data.CHECK);
});
}, 100));
function updateComponentThatShowsIfUserNameIsTakenFunction(taken) {
$('#username').addClass('input_error');
}
What I did: Removed global variables, they are annoying and error prone. Instead, I'm using a callback named updateComponentThatShowsIfUserNameIsTakenFunction. You can also change it to directly call that function with the "data" of course. I have also added a timeout for you so that you won't call the server EVERY key-up. Every key-up cancels the previous timeout, causing the check to only trigger 100ms after the user is done typing (you don't want to spam your server).
I hope this works and helps you further!

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Categories