using ajax from a php function - php

I am new with ajax. I have this php function already from functions.php
function checkUserEmailExistent($email){
...
return $boolean;
}
and this is for my views views.html
<input type='text' name='email' id='email'>
this is for the script.js
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'url',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
}
});
});
my issue is how can I call my php function in ajax to connect it to my html. when it blur it check the email value if it is exist or not.

work in WordPress
JS SCRIPT
jQuery( "#email" ).blur(function() {
jQuery.ajax(
{
url: ajax_url,
type: "POST",
dataType: "json",
data: {
action: 'checkUserEmailExistent',
email: $(this).val(),
},
async: false,
success: function (data)
{
if (data.validation == 'true')
jQuery('.email-massage').html('<div class="alert alert-success">×<strong>Success!</strong> successfully</div>');
else
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
},
error: function (jqXHR, textStatus, errorThrown)
{
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
}
});
});
WP SCRIPT in functions.php
add_action('wp_ajax_checkUserEmailExistent', 'checkUserEmailExistent');
add_action('wp_ajax_nopriv_checkUserEmailExistent', 'checkUserEmailExistent');
function checkUserEmailExistent() {
$email = $_POST['email']; // get email val
/*if() your condition
$email = 1;
else
$email = 0;
*/
if ($email == 1):
$email_val= 'true';
else:
$email_val = 'false';
endif;
echo json_encode(array("validation" => $email_val));
die;
}
in function.php Enqueue file after add this code like this
wp_enqueue_script('themeslug-default', get_template_directory_uri() . '/js/default.js', array('jquery'));
wp_localize_script('themeslug-default', 'ajax_url', admin_url('admin-ajax.php'));

Set url to the php file where you have checkUserEmailExistent function. Then:
function checkUserEmailExistent($email){
...
return $boolean;
}
return checkUserEmailExistent($_REQUEST['value']);

I give the example for validation.This will help you to check
Email id<input type="text" name="email" id="email" size=18 maxlength=50 onblur="javascript:myFunction(this.value)">
You need to add the script
<script>
function myFunction(em) {
if(em!='')
{
var x = document.getElementById("email").value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
document.getElementById("email").value = "";
return false;
exit();
}
var email=$("#email").val();
$.ajax({
type:'post',
url:'email_client.php',
data:{email: email},
success:function(msg){
if (msg.length> 0) {
alert(msg);
document.getElementById("email").value = "";
}
}
});
} }
</script>
Create a page 'email_client.php' and add the code
<?php
$s=$_POST['email'];
include "config.php";
$echeck="select email from client where active=0 and email='".$_POST['email']."'"; //change your query as you needed
$echk=mysql_query($echeck);
$ecount=mysql_num_rows($echk);
if($ecount>='1' && $s!='0')
{
echo "Email already exists";
}
?>

You would call it in your url parameter. However, you'll need to manage your AJAX handler in the PHP script.
AJAX
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'functions.php',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
if (result.success) {
//handle success//
} else if (result.failure) {
//handle failure//
}
}
});
});
PHP
function checkUserEmailExistent($email){
...
return $boolean;
}
if ($_POST['value']) {
$status = checkUserEmailExistent($email);
if ($status === true) {
echo json_encode (array('status' => 'success'));
} elseif ($status === false) {
echo json_encode (array('status' => 'failure'));
}
}

you don't call your server function inside Ajax you only send your data in JSON format to the server on getting this data,server will route(if MVC) it to specific function and return a response to client in JSON format so now inside Ajax you perform operation on success (what to do next ) and in case of failure show the error
How server will route it to specific function that depend on framework you use, but i think they simply use regexp to match with URL

Related

PHP JSON not returning value from php function

Say I have a function as following. alert_danger returns the error message in red box. check_empty checks if a value posted from form is empty or not.
function alert_danger($msg){
$alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
return $alert;
}
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
Now when I want to return the function value using jSON it's not returning the same. The following error is occuring:
// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
What seems to be the problem here?
Here is my jQuery if needed!
$(".action").click(function() {
var form = $(this).closest("form");
var type = form.find(".type").val();
var dataString = form.serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = form.attr("action");
$.ajax({
type: "POST",
dataType : "json",
url: url,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json){
$('.message').html(json.status).fadeIn();
// $('#content').html(json.result).fadeIn();
$(".overlay").hide();
$("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
btnElement.html(btnValue);
if(type == 'admin'){
if($('.message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
$(".overlay").hide();
window.location.replace("dashboard.php");
}, 1000);
}
}
}
});
return false;
});
Consider the following.
PHP
<?php
function checkEmpty($postValue, $msg){
return $postValue == null ? array("status" => "error", "message" => "Empty Value") : array("status" => $postValue, "message" => $message);
}
header('Content-Type: application/json');
echo json_encode(checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!"););
?>
JavaScript
function redirectTo(url, time) {
if (!url) {
return false;
}
time = time != undefined ? time : 0;
setTimeout(function() {
window.location.href = url;
}, time);
}
$(".action").click(function() {
$(this).closest("form").submit();
});
$("form").submit(function(event) {
event.preventDefault();
var type = $(this).find(".type").val();
var dataString = $(this).serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = $(this).attr("action");
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: dataString,
cache: true,
beforeSend: function() {
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json) {
if (json.status == "error") {
$(".message").html("<div class='alert alert-danger error'>" + json.message + "</div>").fadeIn();
} else {
$('.message').html("<div class='alert alert-danger'>" + json.message + "</div>").fadeIn();
$("html, body").animate({
scrollTop: $(".message").offset().top
}, "slow");
btnElement.html(btnValue);
if (type == 'admin') {
if ($('.message').find('#responseBox').hasClass('alert-success')) {
redirectTo("dashboard.php", 1000);
}
}
}
}
});
return false;
});
Typically, it is bad practice to use language X to generate code in language Y. Try decoupling the two languages by making data their only interface -- don't mingle the code.
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript
You have to be careful to not confuse echo and return, they do very different things.
https://www.php.net/manual/en/function.echo.php
https://www.php.net/manual/en/function.return.php
Since you're passing back JSON data to the AJAX Call, I would advise wrapping your HTML inside the callback versus sending it back inside the JSON.
I think you should take a look at your success function. I think it normally runs before the page loads. So, its possible none of the html your referencing in there exists yet. So move it out to a function like this:
success: function(json) {
doSomething();
}
function doSomething(json){
$( document ).ready(function() {
console.log('page has loaded now modify your html with jquery'+json);
}
}

request ajax doesn't work with php validation

I want to use ajax in order to fadeIn a loader during PHP validation and returning the values from it to show visual effect messages, then fadeOut the loader when it finishes. But I did not managed to get a simple return from PHP validation in the .done function.
Can anyone help me please?
Index
<form action="php/valid.php" method="post" id="contact-form">
<input id="name-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="name" placeholder="Name"><br>
<input id="email-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="email" placeholder="Email"><br>
<textarea id="message-contact" class="uk-input uk-textarea uk-width-1-1 uk-margin-small" name="message" placeholder="Message" style="height:200px"></textarea>
<button id="contact-btn" class="uk-margin-small uk-button uk-button-secondary uk-width-1-1" type="submit" name="contact-form">Send</button>
</form>
JS
$(function() {
var data = {
name: $('#name-contact').val(),
email: $('#email-contact').val(),
message: $('#message-contact').val()
};
$('#contact-form').on('submit', function(event) {
$.ajax({
url: 'php/valid.php',
type: 'POST',
dataType: 'json',
data: data
})
.done(function(data) {
if (data.status == 'success') {
console.log('Success !');
} else if (data.status == 'error') {
console.log('Error !');
}
})
.fail(function(error) {
console.log(error);
});
});
});
PHP file
<?
header('Content-Type: application/json');
$error = false;
$regex_name = '#^[\w\s\p{L}-]{2,30}$#iu';
$regex_message = '#^[\s\S]{3,800}$#i';
if (isset($_POST['contact-form'])) {
$name = $_POST['name'];
$from = $_POST['email'];
$message = nl2br($_POST['message']);
if (!empty($name) && !empty($from) && !empty($message)) {
if (preg_match($regex_name, $name) && filter_var($from, FILTER_VALIDATE_EMAIL) && preg_match($regex_message, $message)) {
$error = array('type' => 'success');
} else {
$error = array('type' => 'error', 'value' => 'There are some errors, please check your informations.');
}
} else {
$error = array('type' => 'error', 'value' => 'Some fields are empty, please check your informations.');
}
}
if (isset($error['type']) && $error['type'] == 'success') {
$return_status['status'] = 'success';
echo json_encode($return_status);
}
else {
if (isset($error['type']) && $error['type'] == 'error') {
$return_status['status'] = 'error';
echo json_encode($return_status);
}
}
?>
Thank you.
First, you need to call event.preventDefault() to prevent the form from being submitted normally.
Second, you need to get the values of the inputs in the event handler. Your code is setting data when the page is loaded, before the user has filled in the form.
Third, your PHP script checks for the contact-form parameter. This is sent when you submit the form normally, but your AJAX request isn't setting it. You need to add it to data, or remove if (isset($_POST['contact-form'])) from the PHP (if valid.php is never used for anything else, this check is probably not necessary).
$(function() {
$('#contact-form').on('submit', function(event) {
event.preventDefault();
var data = {
name: $('#name-contact').val(),
email: $('#email-contact').val(),
message: $('#message-contact').val(),
"contact-form": true
};
$.ajax({
url: 'php/valid.php',
type: 'POST',
dataType: 'json',
data: data
})
.done(function(data) {
if (data.status == 'success') {
console.log('Success !');
} else if (data.status == 'error') {
console.log('Error !');
}
})
.fail(function(error) {
console.log(error);
});
});
});
Change button type to button:
<button id="contact-btn" class="" type="button" name="contact-form">Send</button>
Change your js code like below :
$(document).ready(function () {
$('#contact-btn').click(function(event) {
var data = {
name: $('#name-contact').val(),
email: $('#email-contact').val(),
message: $('#message-contact').val()
};
$.ajax({
url: 'php/valid.php',
type: 'POST',
dataType: 'json',
data: data,
success: function(response) {
if (response.status == 'success') {
console.log('Success !');
} else if (response.status == 'error') {
console.log('Error !');
} else
console.log("Somthing went wrong....")
},
error:function(){
console.log("error");
}
});
});
});

PHP not return value without exit function

I need help. I am getting problem in returning value from Codeigniter. Whenever, I use exit; after echo it work fine but whenever i try return true it's dosen't work.
Same as i have comment code in PHP code. if i use exit after echo it works but if i don't do that it returns nothing
Ajax Request
$('#social-form').on('submit', function(e){
e.preventDefault();
var str = $( "#social-form" ).serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str
})
.done(function (data) {
console.log(data);
swal("Information", data, "info");
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});
Codeigniter-3
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($this->input->post() && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
echo 1;
//exit;
//return true;
}
else
{
echo 0;
//exit;
//return false;
}
}
CodeIgniter has a layout, so after outputting a response there could be views that are outputted after your response, such as a footer or a debug bar.
Try using your console to see the status code of the response. Also note that it isn't bad practice in CodeIgniter to exit after AJAX calls, so perhaps you should just write a AJAX response helper which does all that for you (like setting the header and adding the exit).
You probably need to be more specific about what you echo. This is one of several possible solutions.
controller
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($name && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
$out = json_encode(array('result' => 'success'));
}
else
{
$out = json_encode(array('result' => 'failed'));
}
echo $out;
}
javascript
$('#social-form').on('submit', function (e) {
e.preventDefault();
var str = $("#social-form").serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str,
dataType: 'json'
})
.done(function (data) {
console.log(data);
if (data.result === 'success') {
swal("Information", "Success", "info");
} else {
swal("Information", "Failed", "info");
}
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});

AJAX: return true or false on 'success:'

I have the following AJAX script, but for some reason the var ok it's not returning true or false so the form can continue:
function ajax_call(email,title,url){
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
var ok = true;
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if(response == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
}
});
return ok;
}
HTML:
<form onsubmit="return ajax_call();">
...
</form>
PHP:
<?php
//////....
if(!empty($errors)) {
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
} else { echo 'bien'; }
?>
Everything works good, except for the return value.
Thanks in advance.
Prevent the submit completely, send the ajax request, then if it's good, submit the form.
HTML:
<form id="myform">
...
</form>
JavaScript:
$("#myform").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response) == 'bien') {
this.submit(); // submit, bypassing jquery bound event
}
else {
$("#ajax_call").html(response);
}
}
});
});
You are returning ok at the end of your function. This is returned before your ajax request is sent and completed.
You cannot rely on the return value of your function, you should do something inside your "success" part. It basically depends on what you want to do with your return value
I'm a complete newbie to jquery but in some of the scripts I've been working on I've had to prefix the 'response' you have.
For instance...
if(response.tiitle == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
Also be aware you have double letters in your "parametros" but I'm sure that was intentional (i.e. tiitle and not title etc).

Why an AJAX call is giving an error timeout response only in Firefox

My ajax call
I make an ajax call to check if the e-mail address is already used to participate. The php-file returns 0 when it is not used and 1 if it is already used. When it is used it'll make an error label to say so.
This works perfectly in Chrome, Safari, Internet Explorer. But is a complete pain in the ass in Firefox. It checks and gives the correct response, but after 5 seconds it gives a timeout.
I have another ajax call to put all the data in the database and it has the exact same problem.
What do I do wrong?
function controleerDeelnemerEmail(){
var emailVal = $('#email').val();
$.ajax( {
type: 'POST',
url:'?page=home&action=check',
dataType:'text',
data: {'email':emailVal},
success: function( data ){
data = parseInt(data);
if(data == 1){
if( $(".emailerror").length == 0 ){
var error = "<label for='email' generated='true' class='error emailerror' style=''>Dit e-mailadres wordt al gebruikt</label>"
$(error).insertBefore( $('#email') );
}
}
}
})
}
Server Side
public function check(){
if(!empty($_POST)){
$content = $this->deelnemerDAO->controleerDeelnemerEmail( $_POST['email'] );
if( $content == 1 ){
echo 1;
}else{
echo 0;
}
exit();
}
}
You should add an error callback to see if the answer returned is one.
A wrong type can be considered as an error by ajax.
function controleerDeelnemerEmail() {
var emailVal = $('#email').val();
$.ajax({
type: 'POST',
url:'?page=home&action=check',
dataType:'text',
data: {
'email': emailVal
}
}).done(function (data) {
// equivalent to success callback
data = parseInt(data);
if (data == 1) {
if ($(".emailerror").length === 0) {
var error = $("<label>", {
'for': 'email',
'generated': 'true',
'class': 'error emailerror'
}).text("Dit e-mailadres wordt al gebruikt").insertBefore($('#email'));
}
}
}).fail(function (response, status) {
alert('fail');
});
}

Categories