Ajax validator function doesn't work - javascript

I have to validate my form which does a scheduling. I used ajax and php to do a query and search that time - that was choosen in a select - in the database. If there's one row saved, it returns 1 (or false), if doesn't, returns 0 (or true). Anyway, in the function callback, even it's true, the validate error appears, as if it had a real error. Printing the value, we see the value, but i dont know why it shows the error. I've tried everything, and nowhere i found the answer for this.
The js file: alteraDiv.js
jQuery.validator.addMethod('confereDia', function(value){
alert("entrou no método");
if (conf(value) == '0'){
alert("entrou no if");
return true;
}else{
alert("entrou no else");
return false;
}
});
var verifica;
function setVerifica(x){
verifica = x;
}
function conf(value){
$.ajax({
async: false,
url: 'confereDia.php?horarioInicial='+value,
dataType: 'text',
success: function(data) {
alert("entrou no success");
setVerifica(data);
alert("value:"+value);
return verifica;
},
error: function(data){
alert("ERROR. Dados: " + data);
}
});
}
The php file: confereDia.php
$horarioInicial = $_GET["horarioInicial"];
$query = "SELECT idAgendamento FROM agendamento WHERE horarioInicial = '$horarioInicial'";
$results = mysql_query($query);
if (mysql_num_rows($results) == 0) {
echo '0'; //good to register
} else {
echo '1'; //already registered
}
There are more codes in the files, but i think these are necessary for you understand and help me.. THANK YOU!!!

Related

Ajax PHP Follow Script - Nothing stored in the database

I recently discovered a treehouse blog on ajax for beginners http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php I've been looking for a follow script for a while and I've hit a dead end. Currently the follow button fades as it should do, yet no values are stored in the database as of yet.
Profile.php (follow button):
<div id="followbtncontainer" class="btncontainer">Follow</div>
Ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
$('#followbtncontainer').html('<p><em>Following!</em></p>');
var numfollowers = parseInt($('#followercnt').html()) + 1;
$('#followercnt').html(numfollowers);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
$('body').on('click', '#morefllwrs', function(e){
e.preventDefault();
var container = $('#loadmorefollowers');
$(container).html('<img src="images/loader.gif">');
var newhtml = '';
$.ajax({
url: 'ajax-followers.php',
type: 'post',
data: {'page': $(this).attr('href')},
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div class="user"> <img src="'+item.profile_pic+'" class="avi"> <h4>'+item.username+'</h4></div>';
}
else {
return false;
}
}) // end $.each() loop
if(json.nextpage != 'end') {
// if the nextpage is any other value other than end, we add the next page link
$(container).html('Load more followers');
} else {
$(container).html('<p></p>');
}
$('#followers').append(newhtml);
},
error: function(xhr, desc, err) {
console.log(xhr + "\n" + err);
}
}); // end ajax call
});
});
ajax.php
<?php require 'database.php' //<?php include 'session-check-index.php' ?>
<?php include 'authentication.php' ?>
<?php
session_start();
$follower=$_SESSION['id'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($database,$sql);
$rws = mysqli_fetch_array($result);
$following=$rws['id'];
/**
* this script will auto-follow the user and update their followers count
* check out your POST data with var_dump($_POST)
**/
if($_POST['action'] == "follow") {
$sql=" INSERT INTO `user_follow` (`follower`, `following`, `subscribed`) VALUES ('$follower', '$following', CURRENT_TIMESTAMP);"
/**
* we can pass any action like block, follow, unfollow, send PM....
* if we get a 'follow' action then we could take the user ID and create a SQL command
* but with no database, we can simply assume the follow action has been completed and return 'ok'
**/
mysqli_query($database,$sql) or die(mysqli_error($database));
}
?>
I'm not sure if the actual $following and $follower values are causing the problem, and just not passing any data. Any help would be much appreciated, thanks!
try to change in ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
...
the url parameter to :
url: 'ajax-follow.php',
See if it will work that way

AJAX request - How can I see the request? [duplicate]

This question already has an answer here:
Viewing data returned by ajax in IE9
(1 answer)
Closed 9 years ago.
I have tried to send an AJAX request and wanted to see what I've send.
But unfortunately I'm not able to do it.
There exists a select option element that I will fill later with the response if everything works.
<script type="text/javascript">
$(document).ready(function(){
$('select[name="domains"]').change(function(){
var requestStr = $(this).val();
// send Ajax request
$.ajax({
cache: 'false',
type: 'POST',
data: {select:requestStr},
url: 'myHandler.php',
dataType: 'json',
success: function(data){
var json = JSON.parse(data);
alert(json.response); // Here you get the value
if(data.status == 'success')
alert("Thank you for subscribing!");
else if(data.status == 'error')
alert("Error on query!");
var str = "<option value=''>Please Select</option>";
//$.each(data, function(i, items){
// str += "<option value='"+items.id+"'>"+items.name+"</options";
//});
$('select[name="countries"]').html( str );
},
// When an error occurs, the error function is called.
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
});
});
The PHP handler Looks like this:
<?php
require_once 'myClass.php';
if (isset($_POST['select']))
{
// log event
$filename = "log.txt";
$fd = fopen($filename, "a");
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $_POST['select'];
fwrite($fd, $str . "\n");
fclose($fd);
$handler = new myClass();
$dataAjax = $handler->getName($_POST['select']);
echo json_encode($dataAjax);
}
<?php
class myClass {
function getName($data)
{
return $data;
}
}
I thought I can use the request parameter and return it but there is nothing I can see.
Oh, I use Internet Explorer so I can't use Firebug.
EDIT
I added a few rows to log my request.
But the log file is empty.
UPDATE
Now there is some progress:
I can see this in the request-text "select=QD".
But when I echo it with echo json_encode($dataAjax);
I get a error window with Error.Parsing JSON Request failed.
I don't get it why the 'success' function won't work!
The response is json encoded.
Oh btw. is it right that I can't use "return" in PHP to send my response back to AJAX?
You can print out request at server side and log it into file/syslog/etc.
if (isset($_POST['countries']))
{
$handler = new myClass();
$dataAjax = $handler->getName($_POST['countries']);
echo json_encode($dataAjax);
}
------------------------------------------------------
dataType: 'json'
if you just want to see the headers,post,response,html then try firebug
function IsJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
this will check whether the response is json or not

Button needs to be clicked twice before working, I want it to be clicked just once

I have a enable and disable button. Each buttons returns a "success" message in the console when clicked. The enable button works in a single click, however, the disable button needs to be clicked twice before it prints the "success" message in the console in my developer tools. What is the problem with this? Can somebody helps me fixing this one? Thanks a lot. Here is my code:
<button class="btn_mode" value="1">Enable</button>
<button class="btn_mode" value="0">Disable</button>
<script type="text/javascript">
$(".btn_mode").click(function(){
var mode_val = $(this).val();
var postdata={'mode':mode_val};
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
}
});
});
</script>
my controller function
function change_mode(){
$mode = $this->input->post('mode');
$query = $this->course_booking_model->change_mode($mode);
if($query){
$notification = "Success";
}
else{
$notification = "Failed";
}
echo json_encode(array('notify'=>$notification));
}
model
function change_mode($mode){
$id = 1;
$data = array('mode' => $mode);
$this->db->where('id',$id);
$this->db->update('maintenance_mode',$data);
return true;
}
Output when adding the console.log('Posting mode_val: ' + mode_val); in the javascript
Clicking the enable button output in the console
Output in the console when clicking the disable button
As your event hook-up looks fine, i suspect that something is going wrong on the server side, which means that your success handler isn't firing. Try logging prior to your ajax call, to see if the click event fires at all:
$(".btn_mode").click(function(){
var mode_val = $(this).val();
var postdata={'mode':mode_val};
console.log('Posting mode_val: ' + mode_val);
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
}
});
});
If the above logs the expected values when you click the buttons, that means that your php script is failing the first time you call it with mode_val = 0.
You could try catching whatever exception might be thrown like so:
function change_mode(){
try{
$mode = $this->input->post('mode');
$query = $this->course_booking_model->change_mode($mode);
if($query){
$notification = "Success";
}
else{
$notification = "Failed";
}
}
catch(Exception $e){
$notification = $e->getMessage();
}
echo json_encode(array('notify'=>$notification));
}
Edit:
The images you have uploaded indicate that there is a problem with the server-side code, and your button click is firing just fine. If you update your php to catch the error and return it, you should be able to get a hint as to what is going wrong. To see the call completing, you could implement the 'complete' and/or 'error' callbacks:
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
},
error: function(jqXhr, txtStatus, errThrown){
console.log('Call failed with status:' + txtStatus);
if(errThrown)
console.log('and error:' + errThrown);
},
complete: function(jqXhr, txtStatus){
console.log('Call completed with status:' + txtStatus);
}
});
});
hmmm maybe something like this
$(".btn_mode[value='1']").on("click", function(){ do something });
$(".btn_mode[value='0']").on("dblclick", function(){ do something });
Try to change your model to return the real outcome of the update.
Like:
return $this->db->update('maintenance_mode',$data);
depending on what the db wrapper return after an update.

Function called by jQuery Form Plugin's beforeSubmit not returning value

The beforeSubmit function in my jQuery Form plugin needs to check whether the selected file already exists on the server. Here's that relevant code:
$('#frmSermonUpload').ajaxForm({
beforeSubmit: function() {
// Reset errors and clear messages
ClearForm(false);
var formValid = true,
fileExists = CheckFileExists();
console.log('beforeSubmit fileExists: ' + fileExists);
if (fileExists === 'true') {
$('#uploadedFile').addClass('inputError');
$('#fileErrorMsg').append(' A file with that name already exists on the server.');
formValid = false;
} else {
if (!ValidateUploadForm()) {
formValid = false;
}
}
console.log('formValid: ' + formValid);
if (!formValid) {
return false;
}
},
...
Here's the CheckFileExists() function:
function CheckFileExists() {
var fileName = $('#uploadedFile').val().replace(/C:\\fakepath\\/i, ''),
dataString;
dataString = 'checkFileExists=' + fileName;
console.log('fileName: ' + fileName);
console.log('dataString: ' + dataString);
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
return 'true';
} else {
return 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
//console.log('Current value of returnResult: ' + returnResult);
//return returnResult;
}
As you can see I'm using console output to check what's going on. In the CheckFileExists() function, fileName and dataString are being reported correctly. On the PHP side, I know that the POST data is getting there due to some logging I've got going on there.
Here's the PHP code that uses the POST data:
if (isset($_POST['checkFileExists']) && $_POST['checkFileExists'] !== '') {
$log->lwrite('**Checking if file exists.**');
$fileToCheck = $targetPath . $_POST['checkFileExists'];
$log->lwrite('file_exists: ' . file_exists($fileToCheck));
if (file_exists($fileToCheck)) {
echo 'existsTrue';
} else {
echo 'existsFalse';
}
}
What's happening is, in the console, the line console.log('beforeSubmit fileExists: ' + fileExists); is returning "undefined" (beforeSubmit fileExists: undefined).
Here's all of the console output for an upload where the file already exists, so the beforeSubmit should be stopped:
fileName: 042913sermon.mp3
dataString; checkFileExists=042913sermon.mp3
beforeSubmit fileExists: undefined
formValid: true
serverResult: existsTrue
It must be significant that the serverResult line is displaying after everything else. Does that have to do with how long the ajax call takes? If so, is there a way to delay the rest of the script until the ajax call is done executing?
UPDATE
As aorlando pointed out, the order of the console output signified that I needed to add async: false to my $.ajax call. After doing so, the console output was correct, but the function CheckFileExists() is still getting reported as undefined in beforeSubmit.
Ok. Now the problem is the scope of return.
If you use "async: false" you can return in this way (not so elegant)
var returnValue='';
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
returnValue = 'true';
} else {
returnValue= 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
return returnValue;
You must declare a var returnValue out of the scope of the ajax call. Inside the ajax function you can modify the value of returnValue;
This is a solution which use closure, a quite complex javascript feature. Further read something about scope of a variable in javascript: What is the scope of variables in JavaScript?
This is not a very nice solution; is better if you call a function inside "success" function of ajax call as my previous example.
That's all folks!
You are using an AJAX async call.
Your method CheckFileExists()n return a value before the ajax call complete.
So the simplest solutions is to use:
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false ...
if you want to use async call (the default as you can see: http://api.jquery.com/jQuery.ajax/
you must call (for ex.) a postcall function in the success function of the ajax call:
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
postFn('true');
} else {
postFn('false');
}
}, ...
Be carefull with the scope of the postFn
funcion postFn(_result){
console.log(_result);
}
I hope to be clear.
That's all folks!

Page Refresh Only After Page Is Validated

Hi I wonder whether someone may be able to help me please.
I've put together this page which has working 'client' and 'server' side validation.
What I'm now trying to do is add a page refresh and 'scroll to top', once the page has passed validation.
To the script used in the first link I've added the following code to try and invoke this functionality:
setTimeout(function() {
$('body').fadeOut(400, function() {
location.reload();
setTimeout(function() {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
The problem I'm having, is that irrespective of whether the the form passes validation, the page refreshes as can be seen in this page. So the full JavaScript code looks like this:
Post Update - Through working with #rahul, I've now have a working solution as below. NB I only needed to change the JavaScript code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#addlocation").validationEngine();
$("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#saverecordresponse');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
});
});
}
});
}
//prevent form from submitting
return false;
});
});
</script>
and this is a cut down version (I've deleted most of the validation rules for preview purposes) the PHP code which works in conjunction with the JavaScript and saves the record to a MySQL database.
<?php
//sanitize data
$userid = mysql_real_escape_string($_POST['userid']);
$locationname = mysql_real_escape_string($_POST['locationname']);
$returnedaddress = mysql_real_escape_string($_POST['returnedaddress']);
if(empty($locationname)){
$status = "error";
$message = "You need to enter a name for this location!";
}
else{
$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");
if($query){ //if insert is successful
$status = "success";
$message = "Location Saved!";
}
else { //if insert fails
$status = "error";
$message = "I'm sorry, there has been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
I must admit, I'm not sure where the problem lies, but I'm the first to admit I'm a little new to JavaScript and jQuery.
I just wondered whether someone may be able to look at this please and let me know where I'm going wrong, or even perhaps suggest a better alternative to make the page refresh once the form passes validation.
you can easily get it done using return false
check if validation not passed return false
if(Yourvalidation!=true)
{
return false;
}
after this section
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
check value of klass like this
responseMsg.fadeOut(200, function () {
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200, function () {
//set timeout to hide response message
setTimeout(function () {
responseMsg.fadeOut(200, function () {
$(this).removeClass(klass);
form.data('formstatus', 'idle');
});
}, 3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
else
{
return false; //use return false in else condition
}
});
});
You can check the client and server side validation by using this
if(Page_ClientValidate())
return true;
else
return false;

Categories

Resources