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
Related
I am having an issue with saving a form. The form itself has about 40 rows with around 12 inputs for each row in this style:
On save, it should POST and then close the window. However, it never truly saves it. This makes me think that it is closing the window before it saves. Here's the code in question:
$('#save-btn').click(function() {
document.form.submit();
window.close();
};
If I remove the window.close() and use the inspector than I see in the parameters field that all the values save correctly. This is again what lead me to think that the window is closing to early.
I have tried using the following in the above #save-btn function:
setTimeout('window.close()',5000)
Yet this never seemed to execute the window.close() after the 5 seconds and all around seems like bad programming to force it to wait 5 seconds and then close when it could take any amount of time.
I then attempted to use an AJAX request like:
var _url = 'submit?nameParam="+nameParam+"&com=editlist&'+$('form').serialize();
console.log(_url); //just to see what its pushing out
$.ajax({
url: _url,
error: function(){
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
This resulted in 414 Request-URI Too Long. I know the case for this is it should be a POST to begin with, but I was just trying to make it work.
Just because, this is how our form is set up:
<form name="form" action="submit" method="post">
Our solution was to close the page from our action page
Remove the serialized data from your _url and instead pass it through the .ajax() request with the data setting:
var _url = 'submit?nameParam="+nameParam+"&com=editlist';
$.ajax({
url: _url,
method: "POST",
data: $('form').serialize(),
error: function() {
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
Your ajax approach is correct because you can understand that form submit done correctly with code, on success post it is easy to close the window.
For sending a POST request, you have to make some small changes in your code...
Don't serialize your form and add URL, it is not safe (not working for your situation).
Post your values as "post data".
Here is documentation about it.
https://api.jquery.com/jquery.post/
Please try and update your question if you cannot understand how.
If I have a validation tag in my asp.net mvc application for a text field called search, can I plug into it using jquery/javascript to get it to trigger if certain logic is performed? How would I do that?
It looks something like this
#Html.TextBox("SearchQuery", other stuff here, other)
#Html.ValidationMessageFor("SearchQuery")
Say I want to trigger the validation message to show if this occurs
$('form').submit( function (e) {
e.preventDefault(e);
var results = GetLocation();
if (results) {
this.submit();
} else {
// trigger validation message and display "can't find results"
}
});
Please note that I don't think I need to validate here, I just want to show a message where the validation message would be if I did validate
As far as i understand your question, for custom messages coming from server you need to send the object to server and then get the response from it.
You can perform it with an ajax call for example:
$.ajax({
url : 'example.com',
type: 'POST',
data : results,
success:function(datafromserver)
{
$('.resultState').html(datafromserver);
}
});
Another thing if do validation first in the client and then send (and check again in server), in this case remember var result can always be true if the getLocation functions returns anything (such as string , object etc...) so in this case print it with console.log and take a look if is it an object (f example: data.x === none or 'no coordinates' just evaluate it correctly and you can avoid ajax.
Hope helped!
Regards
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.
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
});
For some reason, AJAX requests seem to be failing in both Opera 11.51 and IE8 but work in Firefox and Chrome. I am not doing anything fancy other than the standard post request call:
$.post('/dashboard/valid_email/', { email:email }, function(data) {
I've added an alert before and after the AJAX call and I only get one alert which means the callback function isn't called.
I am using jquery.1.6.2 hosted on Google.
Any ideas?
Add an error handler to see what error is being thrown. If you are returning something other than text/html, you need to set the dataType parameter to the proper dataType.
Parse error means that there is something wrong with the data you are returning; if you are returning html, then the html is not valid, and if you are returning json, the json is not well-formed.
$.post(url,data,callback,datatype).fail(function(x,y,z){
alert(x + "\n" + y + "\n" + z);
})
I finally found out what the problem was. I was making use of mouseflow and it was causing problems for some reason on those two browsers! I just removed it and won't be using mouseflow again. I've let the developers know - maybe they can apply a fix.
One error I see: You need to change email to 'email':
$.post('/dashboard/valid_email/', { 'email' : email }, function(data) {
It's not likely your whole problem, but it needs correction.