I have a simple form validation with ajax and jquery. I've done this before but now it seems to be failing over and over.
The title is the error I see in the firebug console. After some google research, seems to be a problem with managing windows but... I'm not trying to do that and I also tried in other browsers with identical results. The form submits...
This is the function:
$("#login-da").submit(function(){
$('#error').hide();
var username = $('#username').val();
var password = $('#password').val();
var query = 'username=' + username + '&pass=' + password;
$.ajax({
type: "POST",
url: "functions/check-user.php",
async: false,
data: query,
cache: false,
success: function(response){
if(response == 0) {
$('#error').slideDown();
var error = 1;
}
else {
var error = 0;
}
}
});
if (error == 1){
return false;
}
});
I've tried to return false directly in the success function with identical results. The error begins to show but the form submits anyways and nothing appear.
I've also noticed through debugging that anything outside the ajax call isn't executed.
Any help would be really appreciated
Try using Number() on the response data, also, check the scope of the error variable on the response funcion:
success: function (response) {
var result = Number(response);
if (result == 0) {
$('#error').slideDown();
error = 1;
} else {
error = 0;
}
}
Related
I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});
I have a strange error within my $.ajax call here:
//CHECK USERNAME
$('#username').focusout(function() {
var id = $(this).attr('id');
var username = ($(this).val());
$(this).removeClass('hint').removeClass('hint_validated');
if (!$(this).val() || !regexUser($(this).val())){
//INVALID
$('#'+id+'_hint').hide().addClass('hint').show().html(usernameInvalid);
}else{
//VALID -> CHECK USERNAME FROM DB IF CONFIG = TRUE
if (checkUsername == true){
//LOADING FROM DB
$('#'+id+'_hint').hide().addClass('hint_check').show().html(usernameCheck);
$.ajax({
cache: false,
type: 'POST',
url: 'classes/ajax_check.php', //all that does currently is echo "USERNAMEVALID"
data: {username: username},
success: function(response){
if (response == "USERNAMEVALID") {
$('#'+id+'_hint').hide().removeClass('hint_check').addClass('hint_validated').show().html(usernameValid);
}else{
alert("ERROR");
};
},
error: function(){
$('#'+id+'_hint').hide().removeClass('hint_check').addClass('hint').show().html(usernameError);
}
});
}else{
$('#'+id+'_hint').hide().addClass('hint_validated').show().html(usernameValid);
}
}
});
The success function is called but the IF clause throws always FALSE. Why?
If the success function is only alert (response); it actually alerts USERNAMEVALID
I've worked with these functions before but I can't find the error here... Thanks for reading, any help is apreciated.
cheer
PrimuS
Check for empty lines. There is a difference between seeing:
alert("Hi\n");
alert("Hi");
You see the same, but it is not. Try this:
alert(encodeURI("Hi\n"));
alert(encodeURI("Hi"));
Where, it alerts this way:
Hi%0A
Hi
PS: If you are using a good browser other than IE, please use console.log() instead of alert(). So that you can check what is printing and what not!
Fiddle: http://jsfiddle.net/XaT6S/
I'm struggling around for a while now with a jQuery Ajax-Request. I'm building a Step-by-Step rating form. There is actually only one form which will be submitted on each step (the current step will is transmitted to PHP, only data that is important for that step will be validated).
The Problem:
The Ajax call is being submitted a lot of times without reloading the page. Although the ajax call (logged into Firebug console) is returning the right value (e.g. error if PHP validation fails) jQuery still picks up the old return values first (e.g. an old error or a success) and goes through the code again..
Code
Here is my jQuery function..
$(ajax_cont).find(':submit').live('mouseup keyup',function(){
submitButton = $(this);
});
$(ajax_cont).live("submit", function(d) {
var index = submitButton.attr("id").substring(9);
d.preventDefault();
var str = $(this).serialize() + "&step=" + index;
var uri = ajax_default;
$.ajax({
type: "POST",
cache: false,
asynch: false,
url: uri,
data: str,
success: function(data) {
$(".step_slider_container").ajaxComplete(function(event, request, settings) {
if(data.success) {
alert("jaa");
var next_step = "";
$(ajax_cont).parent().find(".error").html("").hide();
$(ajax_cont).find(".error_input").removeClass("error_input");
next_step = data.next;
console.log(data.next);
step_check = $(ajax_cont).find(".step_check").val();
if(step_check.indexOf(next_step) == -1) {
step_check = step_check + "," + next_step;
}
$(ajax_cont).find(".step_check").val(step_check);
var enabled_array = step_check.split(',');
$.each(enabled_array, function(enabled_index, enabled_value) {
if(enabled_array[enabled_index].length > 0) {
tmp_div = enabled_array[enabled_index];
$("body").find(".step_" + tmp_div).removeClass("disabled");
}
});
// Show - Hide Container
var id = "#step_" + next_step;
fadeDiv(id);
if(next_step == 3) {
preview_rating();
setHeight(ajax_cont.height());
}
// Navigation
$("body").find(".step").removeClass("step_active");
$("body").find(".step_" + next_step).addClass("step_active");
}
if(data.error) {
next_step = "";
$(ajax_cont).find(".error_input").removeClass("error_input");
error = data.error;
error_ids = data.error_id;
$.each(error_ids, function(index, value) {
id = "#" + error_ids[index];
$(id).addClass("error_input");
});
$(ajax_cont).parent().find(".error").html("<p>" + error + "</p>").show();
setHeight(ajax_cont.height());
}
});
},
dataType: "json"
});
return false;
});
I hope someone can find an answer to the problem.. Seems to make me crazy :(
I can see a few problems with your code:
a) You are setting the ajaxSuccess event within the success event of an ajax call...
b) You are using data.success to determine whether it is successful, which won't change because of an PHP error.
Instead, you should do:
$(ajax_cont).find(':submit').live('mouseup keyup',function(){
submitButton = $(this);
});
$(ajax_cont).live("submit", function(d) {
var index = submitButton.attr("id").substring(9);
d.preventDefault();
var str = $(this).serialize() + "&step=" + index;
var uri = ajax_default;
$.ajax({
type: "POST",
cache: false,
asynch: false,
url: uri,
data: str,
success: function(data) {
if(data.success) {
alert("jaa");
var next_step = "";
$(ajax_cont).parent().find(".error").html("").hide();
$(ajax_cont).find(".error_input").removeClass("error_input");
next_step = data.next;
console.log(data.next);
step_check = $(ajax_cont).find(".step_check").val();
if(step_check.indexOf(next_step) == -1) {
step_check = step_check + "," + next_step;
}
$(ajax_cont).find(".step_check").val(step_check);
var enabled_array = step_check.split(',');
$.each(enabled_array, function(enabled_index, enabled_value) {
if(enabled_array[enabled_index].length > 0) {
tmp_div = enabled_array[enabled_index];
$("body").find(".step_" + tmp_div).removeClass("disabled");
}
});
// Show - Hide Container
var id = "#step_" + next_step;
fadeDiv(id);
if(next_step == 3) {
preview_rating();
setHeight(ajax_cont.height());
}
// Navigation
$("body").find(".step").removeClass("step_active");
$("body").find(".step_" + next_step).addClass("step_active");
}
if(data.error) {
next_step = "";
$(ajax_cont).find(".error_input").removeClass("error_input");
error = data.error;
error_ids = data.error_id;
$.each(error_ids, function(index, value) {
id = "#" + error_ids[index];
$(id).addClass("error_input");
});
$(ajax_cont).parent().find(".error").html("<p>" + error + "</p>").show();
setHeight(ajax_cont.height());
}
},
error : function()
{
alert('there was an error parsing the json, or processing your request');
},
dataType: "json"
});
return false;
});
Note, I have removed the ajaxSuccess event and implemented an error event to your ajax request.
I agree with #thecodeparadox - wall of code. Too much code is just as bad as too little code :-)
Going purely by what you have said it sounds like you have multiple AJAX submits and you are using the response from an older request. Try using something like Ajax Manager http://www.protofunc.com/scripts/jquery/ajaxManager/ which lets you queue and cancel requests.
i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)
You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)
I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}
Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.
I have some PHP AJAX code that is supposed to validate some parameters sent by jQuery and return some values. Currently, it consistently returns invokes the jQuery error case, and I am not sure why.
Here is my jQuery code:
$('.vote_up').click(function()
{
alert ( "test: " + $(this).attr("data-problem_id") );
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
alert (json);
},
error : function(json)
{
alert("ajax error, json: " + json);
//for (var i = 0, l = json.length; i < l; ++i)
//{
// alert (json[i]);
//}
}
});
//Return false to prevent page navigation
return false;
});
and here is the PHP code. The validation errors in PHP do occur, but I see no sign that the error that is happening on the php side, is the one that is invoking the jQuery error case.
This is the snippet that gets invoked:
if ( empty ( $member_id ) || !isset ( $member_id ) )
{
error_log ( ".......error validating the problem - no member id");
$error = "not_logged_in";
echo json_encode ($error);
}
But how do I get the "not_logged_in" to show up in my JavaScript of the jQuery so that I know it is the bit that got returned? And if it isn't, how do I make it that that error is what comes back to the jQuery?
Thanks!
Don't echo $error in the json_encode() method just simply echo $error like so. Also, don't use the variable json, use the variable data. Edited code below:
PHP
if ( empty ( $member_id ) || !isset ( $member_id ) )
{
error_log ( ".......error validating the problem - no member id");
$error = "not_logged_in";
echo $error;
}
jQuery
$('.vote_up').click(function()
{
alert ( "test: " + $(this).attr("data-problem_id") );
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
// ? :)
alert (data);
},
error : function(data)
{
alert("ajax error, json: " + data);
//for (var i = 0, l = json.length; i < l; ++i)
//{
// alert (json[i]);
//}
}
});
//Return false to prevent page navigation
return false;
});
jQuery uses the .success(...) method when the response status is 200 (OK) any other status like 404 or 500 is considered an error so jQuery would use .error(...).
You must handle all output returned from the php script in the success handler in javascript. So a not-logged in user in php can still (should normally...) result in a successful ajax call.
If you are consistently getting the error handler in your javascript call, your php script was not run or is returning a real error instead of a json object.
According to the manual, you have 3 variables available in the error handler, so just checking these will tell you exactly what the problem is:
// success
success: function(data)
{
if (data == 'not_logged_in') {
// not logged in
} else {
// data contains some json object
}
},
// ajax error
error: function(jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
//
Easiest way to debug PHP in this case, is to modify .htaccess to create an error log.
php_flag log_errors on