validate form without refreshing page and showing error through validationEngine - php

I'm using in the same page a validation engine with date picker.
Datepicker: http://jqueryui.com/demos/datepicker/
Validationengine: http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
I've added a jQuery.noConflict(); to make it work (at the beginning of the code).
Now, I need to make my insert through a PHP file, but without refreshing the page, and by displaying an error message in the same bubble of validationEngine (for example when the email is already registered in the BDD).
should I import jQuery to make my insert in the same page
without causing conflicts, or can I use one on the query already used
for the same purpose?
How do I display a server response through the validationEngine?
My code is the following one.
$(".btn_newsletter").live('click', function() {
$.ajax(
{
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
if (data.check==0) {alert('Error : Sorry '); return false;}
if (data.check==1) {alert('yep!!!');
}
},
cache: false,
type: "POST",
dataType: 'json'
});
}
This is my PHP code.
$ip= $_SERVER["REMOTE_ADDR"];
$select = "select * from av_newsletter where email='".$_POST['email']."'";
$exist = $_BASE->query_array($select);
if ($exist) {
$check = "0";
}
else {
$ajout="INSERT INTO av_newsletter(id,sub_date,email,ip) VALUES (NULL,now(),'$email','$ip')";
$add=$_BASE->query($ajout);
if ($add) {
$check="1";
}
}
$return_arr["check"] = $check;
echo json_encode($return_arr);
It doesn't work; I've no alert, but also no errors.

If you are not tied in too deeply to your 'Validationengine' I would recommend using this one, is has served me well for years, it has support for making remote checks so you could do something like this:
$(document).ready(function(){
var save_options = {
success: userSaved, //callback function
url: '/users/save',
response: 'json',
method: 'post'
};
var validationObj = {
rules: {
name: "required",
email: {
email: true,
required: true,
remote: "/user/check_email/"
}
},
messages: {
name: "Please name yourself",
email: {
required: "Please enter your email address",
email: "Invalid email address",
remote: "Email already in use."
}
},
errorPlacement:function(error, element) {
error.appendTo( element.next() );
},
submitHandler: function(form) {
$(form).ajaxSubmit(save_options);
},
success:function(label) {
label.html(" ").addClass("checked");
}
};
});
And then on the PHP side at the '/users/check_email' endpoint the PHP does the following:
echo $emailExists ? json_encode(false) : json_encode(true);

Ok, before we spam the comments and get to far off topic, please execute this code which should get you started in getting it to work eventually.
$(".btn_newsletter").live('click',function() {
alert('clicked'); // click is executed
$.ajax({
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
alert(data); // should alert the data
if(data.check==0){ alert('Error : Sorry '); return false; }
if(data.check==1){ alert('yep!!!'); }
},
error: function(request, status, error) {
alert('failed '+status);
},
cache: false,
type: "POST",
dataType: 'json'
});
});

it works :)
$(".btn_newsletter").live('click',function() {
var data ="email="+$('#email').val();
$.ajax({
url: "php/functions/signin.php"+"?"+data,
success: function(data) {
if(data.check=='1'){ alert('yep!!!'); }
if(data.check=='0'){ alert('Error : Sorry '); return false; }
},
cache: false,
type: "POST",
dataType: 'json'
});
});
and in my signin.php I catch the value of the input like this $email=$_REQUEST['email']
Thanks a lot! time for me to see about validation engine how to link this with :)

Related

Js Validator Plugin Remote Rules for Unique Value Checking Without Refresh Page Not Working After Ajax Call

I'm trying to validate an designation name with a remote rules.
On first time form submit by entering test value, form submitted and value bind by ajax. but after second time without refresh page i m trying to submit form by adding same value test which i added. i m not getting error for existing name.
here is the js code
$("#designationaddedit").validate({
rules: {
designation_name: {
required: true,
},
designation_copy_name: {
remote: {
url: base_url + 'Designation/designation_name_exists',
type: "post",
data: {
designation_copy_name: function() {
console.log("1");
return $( "#designation_copy_name" ).val();
}
}
}
},
},
messages: {
designation_name: {
required: "Enter Designation name"
},
designation_copy_name: {
remote: 'Designation name is already exists.'
},
},
});
$(document).on('submit', '#designationaddedit', function(event) {
event.preventDefault();
var designation_id = $('#designation_id').val();
var designation_name = $('#designation_name').val();
var action = $('#action').val();
var table = $('#designationTable').DataTable();
var info = table.page.info();
var currentpage = info.start;
if ($("#designationaddedit").valid()) {
$('.preloader').show();
$.ajax({
url: base_url + 'designation/add',
type: 'POST',
dataType: 'json',
data: { submit: 1, designation_id: designation_id, designation_name: designation_name, action: action },
success: function(response) {
$('.preloader').hide();
if (response.success == 1) {
$("#designation_model").modal('hide');
} else {
}
}
});
}
})
below code fixed my issue. I hope it's help you.
remote: { url: "http:url.com", type: "post", data: { USER_ID: userid }, async: false, // set async = false }

how to get ajax "success" and "error" response using php-crud-api

I am having issues validating a response from API.
I am using php-crud-api and I am passing the values from my login form to the url filter[], the server responds with a 200 OK and returns the json data from the table. However I don't need the json data just a "success" or "error" response. Any help would be amazing. Thank you in advance for any feedback.
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
crossDomain: true,
data: "filter[]=email,eq,email=" + log_email + "&filter[]=password,eq,password=" + log_password,
dataType: 'json',
success: function(data) {
if (data == "null") {
console.log("Email and Password DIDN'T match");
$( "#invalid-login" ).popup( "open" );
}
else if (data == "true") {
console.log("it's a !!MATCH!!");
window.location = "content.html";
}
}
});
return false;
});
});
I've read the documentation of https://github.com/mevdschee/php-crud-api and its written that it will return the output in json format only "Condensed JSON ouput: first row contains field names", so you need to change your code accordingly or you can use some other option.
Luckily the API developer got back to me and he offered the following solution:
in the ajax call add the following line to limit the output:
+"&columns=email"
Replase:
if (data == "null") {
With:
if (data.users.records.length==0) {
In the else clause, just replace:
else if (data == "true") {
with:
else {
RESULT:
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
data: "filter[]=email,eq,"+log_email+"&filter[]=password,eq,"+log_password+"&columns=email",
crossDomain: true,
dataType: 'json',
cache: false,
success: function(data) {
if (data.itouchyou.records.length == 0) {
//FAIL
$( "#invalid-login" ).popup( "open" );
console.log("Email and Password DIDN'T match");
}
else {
// SUCCESS
window.location = "content.html";
console.log("it's a !!MATCH!!");
}
}
});
return false;
});
});

ajax not properly parsing the value returned by php

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;
});
});

Handle error in jQuery.ajax() when something doesn't work

I have a php file with a form that is sent using jQuery.ajax(). The problem that I have if the email is not sent and the error message is not shown.
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
$('#result').css('background', 'green');
},
error: function(responseText) {
$('#result').css('background', 'red');
}
});
return false;
});
});
As the email is not sent the error not shows anything but the success yes. So, I change my mail.php code for that other code.
<?php
if(2 > 4) {
true;
} else {
false;
}
?>
When I press the button, the success action stills working and I don't know why.
The error callback is only triggered if the ajax call fails, not if the PHP mail function fails, and not if you return false, that would be a success as you received something back from the server (the string "false").
To catch errors like that you can either trigger an error from PHP or just catch it in the success handler:
success: function(data) {
if (!data || $.trim(data) == 'false') {
$('#result').css('background', 'red');
}else{
$('#result').css('background', 'green');
}
},
and PHP
<?php
echo 2>4 ? 'true' : 'false';
?>
Remove the error function & make changes to your success function
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
if(responseText)$('#result').css('background', 'green');
else $('#result').css('background', 'red');
}
});
The error function will not trigger unless jQuery fails to connect to your php file, in this case you would wan't to handle your own errors, first off what does this do?
if(2 > 4) {
true;
} else {
false;
}
this would not send anything back to jQuery i recommend the following
if(2 > 4) {
echo 'true';
} else {
echo 'false';
}
then in your jQuery
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(result) {
if(result === 'true') {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
},
error: function(error) {
alert(error)
}
});
return false;
});
});
In your both cases, the success callback is fired:
success: function(responseText) {
if(!!responseText) //!! convert string to boolean
$('#result').css('background', 'green');
else
$('#result').css('background', 'red');
},
First in mail.php file echo that you want to return:
<?php
if(2 > 4) {
echo "true";
} else {
echo "false";
}
?>
And then in success function do that:
success: function(responseText) {
if(responseText) {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
}
It also depends on the version of the jquery you are using. If its 1.9 then you can handle it using the done, fail and always function
For 1.9
var request = $.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
}
});
request.done(function(e){
//GET THE STATUS FOR THE EMAIL FROM THE PHP SCRIPT
//ASSUMPTION THAT FETCHING e=1/0 - 1 - Success, 0 - Failure
if(parseInt(e))
{
$("#result").css("background","green");
}
else
{
$("#result").css("background","red");
}
});
1) Your php script doesn't return anything. For instance, if you eliminate all javascript from your html page, and your form's action attribute specifies myphp.php, and myphp.php looks like this:
<?php
$html = "<html><head></head><body><div>Hello world.</div></body></html>";
?>
What will be displayed after you click on the form's submit button?
2) The error function is called if the request fails. Getting a response of nothing or false from your php script is not a failure of the request. A successful request means that the browser sent out a request, the server received the request, the server caused your php script to execute, and the server sent back the results of your php script as a response. A request fails if the server is too busy to respond to the request, the server crashes while handling your request, you request a file that doesn't exist, etc.

Validate if website exists with AJAX

I'm trying to check if a website exists with an ajax call, but I'm not sure I am getting it right. On my page I grab a URL on click
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(){
$("#start").remove();
},
error: function(){
alert("Bad URL");
}
});
});
a=And then check on ajax.php
$url = $_POST['url'];
ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
return true;
} else {
return false;
}
It seems I am getting SUCCESS no matter what... What am I missing?
It seems I am getting SUCCESS no matter what... What am I missing?
This is extremely pretty straightforward.
Because of this reasons:
// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
$("#start").remove();
}
Which should be
success: function(respond){
//you don't have to return TRUE in your php
//you have to echo this one instead
if ( respond == '1'){
$("#start").remove();
} else {
//handle non-true if you need so
}
}
In php replace this:
if(strlen($r)>1) {
return true;
} else {
return false;
}
to
if(strlen($r)>1) {
print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}
Oh yeah, also don't forget to fix this as well:
data: "url="+url,
to data : {"url" : url}
As Nemoden said, you get a success message even if it returns false.
You need to check the data returned and then remove the element.
for example
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(response){
if (response == 'whatever you are returning') {
$("#start").remove();
}
},
error: function(){
alert("Bad URL");
}
});
});
Success callback is called whenever server-side script returned an answer (there were no connectivity errors or server-side errors). Is this answering your question?
See the difference:
$("#go").click(function() {
var url = $("#url").val(),
ajax_data = {url: url};
$.post({
"/ajax.php?cb=?",
ajax_data,
function(response){
if (response.status) {
// URL exists
}
else {
// URL not exists
}
$("#start").remove();
},
'json'
});
});
php back-end:
printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));

Categories