AJAX calls only working once - javascript

Here's my code:
<script type="text/javascript">
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username() {
$("#check_username").html('<img src="images/site/ajax-loader.gif" />username avilable??').delay(5000);
var usernametotest = $('#username').val();
$.post("backend/username_available.php", { username: usernametotest})
.done(function(data) {
$("#check_username").replaceWith(data);
});
}
</script>
I use this code for checking with AJACX the availability of a username in my form.
It works perfect but just once. When an username is occupied and I change the username, no AJAX checks are done after the first one? The text "username already exists" (in the variable data), is not replaced by "username ok".
This JavaScript is added just before the </html> tag.

Your code looks fine - see this jsfiddle with an alert on the usernametotest value for more visibility
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username(){
$("#check_username").html('username avilable??').delay(5000);
var usernametotest = $('#username').val();
alert('posting username ' + usernametotest);
$.post("backend/username_available.php", { username: usernametotest} )
.done(function(data) {
$("#check_username").replaceWith( data );
});
}
The post requests are being made every time with the correct payload, so no problems there (check browser developer tools e.g. Network tab / XHR in Chrome)
Must be an issue with the response coming back from backend/username_available.php? Check the response of the first request vs the rest, and the difference and hence the problem will probably jump out at you.

Whenever you replace an element... and here you do just that...
$("#check_username").replaceWith( data );
all those element's handlers are lost. So change() no longer works. To be able to use it again, you just need to bind again the element after it has been rewritten:
$('#username').change(check_username);
Or bind the handler to a parent and delegate it:
$('#username').parent().on('click', '#username', check_username);
(I feel that a class selector would work better - call it superstition on my part)

You could try this:
$('#username').on('change', function() {
// write your code here
});

Related

how to send text value to server without the form submitting using ajax

basically i have a form and in that form i have a username textbox with a submit button.
now what i want is that before we submit the form i want to send the text value to server so the server could check if the username has not been taken by any other user and then submit the form, based on research i had, i found this tutorial useful https://scotch.io/tutorials/submitting-ajax-forms-with-jquery, altough this tutorial is using php for server coding and i am using java servlet but my ajax script never gets to execute.
here is my code:
<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script>
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'username' : $('input[name=UserName]').val(),
};
alert('hello');
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../postr', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
name="UserName" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" maxlength="30" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
<script>function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
if (field.value == '') {
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
document.getElementById(errordiv).style.visibility = "visible";
} else if(!field.value.match(/^[a-zA-Z0-9~`!##\(\.)]+$/)){
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "visible";
document.getElementById(errordiv).style.visibility = "hidden";
} else {
field.style.borderColor = "rgb(150,150,150)";
document.getElementById(errordiv).style.visibility = "hidden";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
}
}</script>
as you can see in my ajax script i have an alert() which it should pop up hello but it never does
Good Morning!
I think there are several things to say about your code. First of all your submit function:
$('form').submit(function(event) { ... }
Here you want to catch the submit-event when the user hits the button. Everything good, but since your button is of type=submit the browser will also react on the click and handle the submit-process by itself. Your function won't get called properly. To prevent this you have to escape the default behaviour of your form on submitting:
$('form').submit(function(event) {
event.preventDefault();
$.ajax({ ... });
}
This will do the trick to let the browser do what you want instead of handling the submit by itself.
So now your browser can run your ajax call.
Next thing: The ajax-call.
You did many things right, but some important things wrong. Look at the following structure:
$.ajax({
url: 'your_url_to_send_data_to',
type: 'post', //the method to use. GET or POST
dataType: 'json',
data: data, //your data: {key1:value1, key2:value2}
success: function(data) { //handle a successfull response (200 OK)
alert(data);
//here you can do with your data whatever you want
},
error: function(jqXHR, textStauts, errorThrown){ //handle every error. e.g. 500
alert(textStatus + ': '+errorThrown);
}
}});
This will handle the sending and the recieving of your request. The success function will get called if the server returns an 200 OK. Otherwise the error function gets called.
Now you just have to handle the request on server side properly.
Third thing: What's about the real submit after the name-check?
Since you preventDefault() the default browsers action, sou have to do it manually. You could think of triggering the submit again, but you would ran another time in your own function you've written so far.
Therefore you have to do it by your own. But wait! You can combine the two things in one call!
Think about this:
let the user fill your form
let him hit the submit button
preventDefault behaviour of your browser and build a FormData and put all your values in it
prepare your ajax call
send the FormData with your ajax call to your server
Handle name-check and all other things on server-side
answer the request
evalutate the answer in your success function
Note: On server side you have to print the application/json header to let the browser and finally your ajax call handle your answer properly.
Since you want a dynamic check of the user name availability, I suggest you react to the keyup event (note: I also added support for other possible change-incurring events in my demo below) and schedule a check run after a fixed delay. Once the delay transpires, if the user hasn't typed anything in the interim, you can run the AJAX check and update the page; if the user did type something in the interim, you can simply not run the check (yet). This means a check will automatically be run after every flurry of typing, as long as the user ceased typing for at least the hard-coded delay.
With regard to submitting, I would just allow the user to submit the form in the normal way without any last-second AJAX check of user name availability. You're still going to have to perform a server-side check for availability, in case the user disabled JavaScript or somehow constructed their own submit HTTP query, so you may as well depend on that server-side check upon form submission. The dynamic AJAX check is really only beneficial as a quick notification to the user, and so should only be provided if the user edits the user name, and then does not submit the form immediately. Most of the time the user will not submit the form immediately after editing a field, and most users can be relied upon to not submit the form if it is clearly indicated on the page that there is a validation failure.
var USERNAME_CHECK_DELAY = 800;
var userInputValCount = 0;
var userInputVal = '';
window.handlePossibleUserInputChange = function() {
let $userInput = $('#userInput');
let $checkDiv = $('#userCheckLine');
// if this event doesn't reflect a value change, ignore it
if ($userInput.val() === userInputVal) return;
userInputVal = $userInput.val();
// update the value count
let userInputValCountCapture = ++userInputValCount; // closure var
// schedule a potential check run
setTimeout(function() {
// only check the current name if the user hasn't typed since the provoking event
if (userInputValCountCapture !== userInputValCount) return;
checkUsername();
},USERNAME_CHECK_DELAY);
// update the status message
if ($userInput.val().trim() === '') {
$checkDiv.text('');
} else {
$checkDiv.attr({'class':'checking'});
$checkDiv.text('checking...');
} // end if
};
$('#userInput')
// listen to all events that could cause a change in the input value
.on('keyup change',handlePossibleUserInputChange)
// drop is special; the drop event unfortunately fires before the text is changed
// so we must defer the call until after the text is changed
// same with mouseup; occurs when clicking the input box X button in IE
// same with paste via context menu, rather than shortcut (which would trigger keyup)
.on('drop mouseup paste',function() { setTimeout(handlePossibleUserInputChange); })
;
var lastTaken = true;
window.checkUsername = function() {
let $checkDiv = $('#userCheckLine');
let $userInput = $('#userInput');
// just reset the check line if the input value is empty
if ($userInput.val().trim() === '') {
$checkDiv.text('');
return;
} // end if
// ... send ajax call, get result ...
// (for demo purposes, just invert the previous result)
let taken = lastTaken = !lastTaken;
if (taken) {
$checkDiv.attr({'class':'taken'});
$checkDiv.text('user name is taken.');
} else {
$checkDiv.attr({'class':'notTaken'});
$checkDiv.text('user name is available.');
} // end if
};
.taken { color:red; }
.notTaken { color:green; }
.checking { color:grey; font-style:italic; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<div>
<input id="userInput" type="text" placeholder="username"/>
<span id="userCheckLine"></span>
</div>
<input type="submit" value="Submit"/>
</form>
I think you should use the "remote" of jquery validation (https://jqueryvalidation.org/remote-method/) this check the validation of the field in the server. You need jquery.
$("#Registration_Form").validate({
rules: {
Registeration_Username_box: {
required: true,
remote: {
url: "check-email.php",
type: "post"
}
}
}
});

onclick() function is not working with Jquery?

So yesterday, I added some Jquery code and it worked perfectly. Today I was adding some more for a new part of my website and it did not work. When I tried the code I added yesterday, that stopped working as well. The first thing I do is create a function to get anything from the url that I need. The first 2 inputs are for following users. The first input should send the id variable to the url bar and is retrieved in the php file called follow.php. The second input should do the same thing. Finally the last function is for liking peoples posts. It sends the type of like(like or unlike) to the php file named like.php and is retrieved there. And should post the retrieved data into a div called likes. However, none of which is occurring when the buttons are pressed. Even when I just send an alert to make sure the on click is working, nothing happens either.
Here is my code:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$('input#sub').on('click', function(){
var id = getParameterByName('id');
$.get('follow.php' , {id: id}, function(data){
location.reload();
});
});
$('input#sub1').on('click', function(){
var id = getParameterByName('id');
$.get('unfollow.php' , {id: id}, function(data){
location.reload();
});
});
function doAction(postid , type){
alert("Works");
$.post('like.php' , {postid: postid type: type} , function(data){
$('div#likes').text(data);
});
}
Let's try to sum things up. I'm gonna change most of your code simply because you don't need all of that, otherwise jQuery wouldn't be helpful at all.
Assuming your caller is this anchor:
<img id="like" src="Social/down.png"/>
After this you can manipulate the clicked object getting its attributes easily through:
$('.idsfromdb').click(function(){
var id = $(this).prop('id');
var another_id_obj = $('newselector').prop('id');
// more logic, ajax,...
});
You can attach this kind of functions to every click event and then manipulate the object, call a php file, and so on... I hope I helped you somehow with this.
open google developer tools > network and see if request is made and if it has all data you want as request and if there is anything in response.
if there is request with all parameters, you have problem on server side,
if parameters not same that you are trying to send with ajax, than prevent buttons default action, you must prevent it every time when using ajax especially when button submits form.
$('input#sub').on('click', function(event){
event.preventDefault();
//your ajax
}

jquery: if statement does not work

The code below is very simple. Basically, if variable "ret" returns a value and if the value is "fail" it should post Alert:"Trigger 2". However, the problem is the IF statement. It triggers the Alert:"Trigger 1" and when the conditional statement comes up, it skips it.
I'd like to know if I'm doing something wrong. Thank you.
$(function() {
var body = $(document).find("body");
body.on("submit", "#form-user-profile", function (e) {
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url, data, function(ret) {
alert("Trigger 1"); // Triggers alert
if (ret == "fail") {
alert("Trigger 2"); // does not trigger alert
}
});
return false;
});
});
If the response actually is fail then most likely the problem is some whitespace surrounding the response, causing the if statement to evaluate to false. This can be solved by trimming the response:
if ($.trim(ret) == "fail") {
If the code is actually running, you should be able to view response headers from the Post URL using Chrome or Firefox dev tools. That should give you what the actual response is and help you debug the answer, I imagine its simply returning something close to what you have, but not exactly what you have.

Modifying the DOM based on an AJAX result with jQuery

I'm unsure of the best practice for modifying the DOM based on an ajax response. I'll try to let the code do the talking because it's hard to explain.
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
var cb = $(this); // for the sake of discussion i need this variable to be in scope
$("form").ajaxSubmit({ dataType: "script" });
}
The server sends a response back, and the js gets eval'd and that means "cb" is out of scope.
What I've done so far is create a couple of helper functions:
var target = undefined;
function setTarget(val) {
target = val;
}
function getTarget() {
return target;
}
And that turns the first snippet of code into this:
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
setTarget($(this));
$("form").ajaxSubmit({ dataType: "script" });
}
Then on the server's response I call getTarget where I need to. This seems hackish... Any suggestions?
It's unclear what you're actually trying to do, but I feel like you want to be looking at the success parameter for that AJAX call. The success callback function should execute in parent scope and do what you're looking for.
See 'success' on this page in the jQuery docs.
So what you are trying to do is get the form to submit the content via ajax whenever the user checks/unchecks a checkbox? And because there are several checkboxes, you need to find out which one triggered the submit, so you can change its value to whatever is stored on the server?
If you submit the entire form everytime, why don't you reply with all the checkboxes values, and then change each and every one of them? If not, get the server to reply with the id and the value of the checkbox, then use jquery to find the checkbox with that ID and then change it's value.
How about:
jQuery(function($) {
// give it scope here so that the callback can modify it
var cb,
cbs = $('input[type="checkbox"]');
cbs.live('click', function {
// taking away var uses the most recent scope
cb = $(this);
// disable checkboxes until response comes back so other ones can't be made
cbs.attr('disabled', 'true'); // 'true' (html5) or 'disabled' (xhtml)
// unless you are using 'script' for something else, it's best to use
// a callback instead
$('form').ajaxSubmit({
success : function(response) {
// now you can modify cb here
cb.remove(); // or whatever you want
// and re-enable the checkboxes
cbs.removeAttr('disabled');
}
});
}
});

Issue with jQuery $.get in IE

I have a login form which appears at the top of all of my pages when the user is logged out. My current jQuery/javascript code works in Firefox 3 but not IE 7. The code queries a page which simply returns the string "true" or "false" depending on whether the login was successful or not. Inside my $.ready() function call I have the following...
$('#login_form').submit(function() {
var email = $('input#login_email').val();
var pw = $('input#login_password').val()
$.get('/user/login.php', { login_email: email, login_password: pw }, function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
});
alert('called');
return false;
});
In FF, I am successfully transferred to the intended page. In IE, however, the below alerts "called" and nothing else. When I refresh the page, I can see that I am logged in so the $.get call is clearly going through, but the callback function doesn't seem like its being called (ie. "get succeeded" is not popping up). I also don't appear to be getting any javascript error messages either.
Why isn't this working in IE?
Thanks
EDIT: Since a couple people asked, whenever I enter a correct email/password or an incorrect one, nothing in the callback function happens. If I manually refresh the page after entering a correct one, I am logged in. Otherwise, I am not.
EDIT 2: If I alert out data in the callback function nothing happens in IE (I do not get an alert popup). In FF, it alerts true for valid email/pw combos and false for invalid ones. I am using jQuery 1.3.2.
EDIT 3: Ok, guys, I tried R. Bemrose's thing down there and I'm getting a "parseerror" on the returned data. I'm simply echoing 'true' or 'false' from the other PHP script. I also tried 'yes' and 'no', but that still gave me a parse error. Also, this works in Chrome in addition to FF.
In your response type use:
header("content-type:application/xml;charset=utf-8");
As stupid as this sounds... perhaps IE7 is being anal retentive about the missing semicolon on the var pw line?
Probably not, but the only way I can think of getting more information is to convert it to an $.ajax call in order to add an error hook and see which error type it think is happening. Oh, and to check out the exception object.
$.ajax({
type: 'GET',
url: '/user/login.php',
data: { login_email: email, login_password: pw },
success: function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
},
error: function(xhr, type, exception) {
alert("Error: " + type);
}
});
If the error type is parse, IE may be complaining because the data coming back has extra commas at the end of comma separated arrays/lists.
IE uses cached data for get requests. Maybe that's your problem? What happens if you try different user id, password?
In any case, isn't it a better idea to send password in POST? :)
I'm am having a similar problem with the following code:
var listOrder = $(this).sortable('toArray').toString();
var otherVariable = whatever
$.get('process_todo.cfm?method=sortToDos', {listOrder:listOrder,otherVariable :otherVariable });
The variable displays through an alert as 'test_123,test_456'. I can hard code the same values and it does not fail. It must have something to do with the 'toArray'? I have been trying to debug this one thing for hours. Works perfectly in Firefox, Safari and Chrome... of course!
Instead of:
if(data == 'true')
try:
if(data)
then in your server just return either a 1 (or true) and a empty value.
What you've posted (at least after Edit 2) looks good. I think the problem is in what you haven't posted.
First, have you checked your server logs to ensure that it's sending back what you presume?
If so, I'd recommend dropping the submit mechanism and using a 'button' type with an 'onclick' handler, and not 'submit' button w/a 'onsubmit' handler...
<input type="button" id="login_submit" value="Login" />
Then switch the submit handler:
$('#login_form').submit(function() { ... });
from the form to the button with:
$('#login_button').click(function() { ... });
If that doesn't help, can you post the HTML for the form, too?
[Edit 3] - try adding the 4th 'type' parameter of "text" to the $.post() call.
Have you used Fiddler to have a good look at what's actually being transferred? (http://www.fiddler2.com)
if you are testing/checking your script in local machine then you will not see any thing in any version of internet explorer because IE on localmachine send datatype as text and not xml and in your case again its matter of datatype not compatible with your document datatype so it worth checking if your datatypes are matching
as far as xml goes solution is here
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
you may check this and find some inspiration :)
salman

Categories

Resources