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

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>

Related

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

issue with ajax doesnt continue

I have one issue with ajax when I get echo success on my php. I don't get execute the first if
if(text[0]==="success")
Code inside php
if(count($error)==0)
{
$user = ORM::for_table('usuario')->create();
$user->username = $username;
$user->contrasenia = password_hash($password, PASSWORD_DEFAULT);
$user->email = $email;
$user->admin = $is_admin;
$user->save();
echo "success";
}
else
{
$error = json_encode($error);
echo $error;
}
My code in ajax
[![$("#create-button").on('click', function(event){
//cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm()
{
var dataString = $("#userForm").serialize();;
$.ajax({
dataType: "json",
type: "POST",
url: "/altausers",
data: dataString,
success: function(text)
{
console.log("hola");
console.log(text);
if(text\[0\]==="success")
{
alert("hola");
//$("#error").addClass('hidden');
}
else if(text.length > 0)
{
$("#error").removeClass('hidden');
texterror = "<ol type='disc'>";
$.each(text,function(index,value)
{
texterror+="<li>"+value+"</li>";
});
texterror+="</ol>";
document.getElementById("error").innerHTML = texterror;
}
}
});
}
Image console
What is the problem?
Could say me which it is problem?
I have that convert the message success to json too
Replace the success echo with
echo json_encode(["success"]);
or leave echo the same and replace if in ajax
if(text == "success")
The problem could be that it is an array, so you can try this:
$.ajax({
url: "items.php",
async: false,
type: "POST",
dataType: "JSON",
data: { "command" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});
And if you want to see the results:
Object.keys( response ).forEach(function( key ) {
console.log('key name: ', key);
console.log('value: ', response[key]);
});

how do you pass booleans from PHP controller to Ajax request?

I used this system.. sendind a json with success = 0 or 1 depending on success or error, is this correct or there is a better more correct method to pass true or false to the ajax call?
if (empty($item)) {
// add to the DB
$return['success'] = 0;
return Response()->json($return);
} else {
$return['success'] = 0;
$return['message'] = "Already in Collection";
return Response()->json($return);
}
then in Ajax:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form = $(this);
var span = $(form).find('input[name="span_id"]').val();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
if (data.success == 1) {
alert("success");
}
else if (data.success == 0) {
alert("error");
}
}
});
e.preventDefault();
});
});
});
I use true or false and then compare like that if (data.success).
If you want a boolean send a boolean, but it's just my opinion.
This depends only on you, you can save your success as you do or to status...
<?php
if (empty($item)) {
// add to the DB
$return['success'] = true;
} else {
$return['success'] = false;
$return['message'] = "Already in Collection";
}
return Response()->json($return);

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

How to return an error callback in php?

I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});

Categories