request ajax doesn't work with php validation - php

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

Related

How should be the response to an ajax request in php backend?

I am trying to catch success in client side but I can't. if I put
error:function(data){
console.log(data);
console.log('error');
}
this code in ajax request this catchs something but It shouldn't be in errror.
I tried so much things but couldn't find solution.
Here my ajax request in client side;
<script>
$(document).on("submit", "#request-form", function(event){ //request-form id li form post edildiğinde
event.preventDefault();
var serialized = $(this).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){ //formda boş yer var ise
alert("Fill in all fields");
}else{
$.ajax({
url: "http://127.0.0.1/rent_website/mail-sender/mail.php", //"https://stanstedcab.co.uk/project/mail-sender/mail.php",
type: "POST",
data: serialized,
dataType: "json",
function(data, status) {
console.log('function works');
if (data.success) {
console.log(data);
console.log('Başarılı');
} else {
console.log('else', data)
}
},
});
}
});
</script>
And here backend side;
<?php
$response = array();
if ($_POST){
if(isset($_POST["your-pickup"]) && isset($_POST["your-drop"]) && isset($_POST["Vehicle"]) &&
isset($_POST["meeting-time"]) && isset($_POST["your-name"]) && isset($_POST["your-phone"]) &&
isset($_POST["your-email"]) && isset($_POST["your-message"])) {
//here some mail settings
if($mail->Send()){
$message = "Email sent";
$response["success"] = true;
$response["message"] = $message;
echo json_encode($response);
return $response;
} else {
$response = array('result' => 'Email couldn\'t sent', 'success' => false);
echo json_encode($response);
return $response;
}
}else{
$response = array('result' => 'Fill all fields.', 'success' => false);
echo json_encode($response);
return $response;
}
}
?>
I'd try to do the Javascript in this way like shown here in the examples: https://api.jquery.com/jquery.ajax/
<script>
$(document).on("submit", "#request-form", function(event){ //request-form id li form post edildiğinde
event.preventDefault();
var serialized = $(this).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){ //formda boş yer var ise
alert("Fill in all fields");
}else{
$.ajax({
url: "http://127.0.0.1/rent_website/mail-sender/mail.php", //"https://stanstedcab.co.uk/project/mail-sender/mail.php",
type: "POST",
data: serialized,
dataType: "json"
}).done(function(data) {
console.log('function works');
if (data.success) {
console.log(data);
console.log('Başarılı');
} else {
console.log('else', data)
}
});
}
});
</script>

Ajax - problem with response inside a div

I am trying to show the value of ajax response inside a div.Ajax. Problem arise when I get the response. Response is showing in the div only for split second and hides automatically. I tried changing id to class but the error persist still. The alert displays properly when tested. What do I miss? I have the following code in my view file.
The div:
<div id="result"></div>
Ajax:
$(document).ready(function() {
$('#submit').click(function() {
$.ajax
({
type:'post',
cache: false,
url:'save.php',
data: $("#action").serialize(),
dataType: "html",
success: function(response) {
if(response == 'success')
{
alert('success');
}
if(response == 'empty')
{
alert('empty');
}
if(response == 'bad')
{
$("#result").html(response);
}
}
});
});
});
save.php:
<?php
$co= 'aaa';
if(!empty($_POST['tosave']))
{
if($_POST['tosave'] == $co)
{
$foo = fopen("plik.txt","a+");
flock($foo, 2);
fwrite($foo,$_POST['tosave']."\r\n");
flock($foo ,3);
fclose($foo);
echo "success";
exit();
} else {
echo 'bad';
exit;
}
} else {
echo "empty";
exit;
}
?>
This might be because you don't prevent the default behavior on the submit button which is to send the form's data to the specified link, maybe in your case the link is on the same page than your PHP leading to only see the message in the div for a split second before the page reloads itself.
So to prevent this default behavior, you have to catch the event and use the preventDefault() function like so :
$('#submit').click(function(event) { //we pass the event as an attribute
event.preventDefault(); //we prevent its default behavior so we can do our own stuff below
$.ajax
({
type:'post',
cache: false,
url:'save.php',
data: $("#action").serialize(),
dataType: "html",
success: function(response) {
if(response == 'success')
{
alert('success');
}
if(response == 'empty')
{
alert('empty');
}
if(response == 'bad')
{
$("#result").html(response);
}
}
});
});
});
First of all there is a mistake in your Ajax call code you have write your submit.click() submit function under document.ready().remove document.ready() because submit.click()will run when you submit the form. Second thing is you should add
event.preventDefault() to prevent the default behabiour of your submit form otherwise it will display for short time and then it will disappeared.See my code below it is working.
AJAX WITH HTML FORM:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="action">
<input type="text" name="tosave" value="bbb">
<button type="submit">clickme</button>>
</form>
<div id="result"></div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
$("#action").click(function(event) {
event.preventDefault();//TO PREVENT THE DEFAULT BEHAVIOUR OF FORM
$.ajax
({
type:'post',
cache: false,
url:'https:save.php',
data: $("#action").serialize(),
dataType: "html",
success: function(response) {
if(response == 'success')
{
alert('success');
}
if(response == 'empty')
{
alert('empty');
}
if(response == 'bad')
{
$("#result").html(response);
}
}
});
});
</script>
PHP:
<?php
$co = 'aaa';
if (!empty($_POST['tosave'])) {
if ($_POST['tosave'] == $co) {
$foo = fopen("plik.txt", "a+");
flock($foo, 2);
fwrite($foo, $_POST['tosave'] . "\r\n");
flock($foo, 3);
fclose($foo);
echo "success";
exit();
} else {
echo 'bad';
exit;
}
} else {
echo "empty";
exit;
}
?>
**OUTPUT DISPLAY IN DIV: bad**

unable to upload file in codeigniter using AJAX

I'm trying to upload the file in CodeIgniter using Ajax but the problem is the file is uploading in the database but unable to do it without loading the page. Every time I upload a file it uploading successfully but navigating to its controller address with JSON code. I just want to upload the file without refreshing page.
View FILE
<?php echo form_open_multipart('maker/Checkout/docs', array('id'=>'upload_file')); ?>
<div class="form-group">
<label for="userfile">Upload existing CV</label>
<input class="form-control" type="file" name="userfile" id="userfile" size="20" />
</div>
<div class="form-group">
<button class="btn btn-info" type="submit">Upload</button>
</div>
<?php echo form_close() ?>
Ajax Code
<script>
$(function() {
$('#upload_file').unbind('submit').bind('submit', function() {
e.preventDefault();
var form = $(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
return false;
});
});
</script>
Controller
public function docs() {
$status = "";
$msg = "";
$file_element_name = 'userfile';
if ($status != "error")
{
$config['upload_path'] = dirname($_SERVER["SCRIPT_FILENAME"])."/assets/img/posts";
$config['upload_url'] = base_url()."/assets/img/posts";
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|docx|docs|txt|xml';
$config['max_height'] = 102048;
$config['max_width'] = 102048;
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$file_id = $this->Checkout_model->newcheckout($data['file_name']);
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
I just want to upload the file without refreshing the page. Currently, it's uploading the file but after upload its navigating to the controller address.
The reason why you're navigating to controller is because your call to preventDefault is from a non existent identifier e causing an error, you can remove it since you have return false later or just define the e.
Now when you're trying to upload a file with ajax you use a FormData object
$(function() {
$('#upload_file').unbind('submit').bind('submit', function(e) {//<-- e defined here
e.preventDefault();
var form = $(this);
var data = new FormData(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: data,
processData: false,
contentType: false,
dataType : 'json',
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
return false;
});
});
Slightly different variation of solution that worked for me is given below:
<script type="text/javascript">
$(function() {
$('#upload_file').unbind('submit').bind('submit', function(e) {
e.preventDefault();
var file = document.getElementById('userfile').files[0];
if(file==undefined){
return false;
}
var formData = false;
if (window.FormData) {
formData = new FormData();
formData.append("userfile", file);
}
var form = $(this);
if(formData!==false){
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: formData,
processData: false,
secureuri: false,
contentType: false,
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
}
return false;
});
});
</script>

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

using ajax from a php function

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

Categories