PHP not return value without exit function - php

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

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>

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

add header in php with AJAX

My question is simple, I'm using AJAX and i want to redirect the user to another page if the user fill up the registration form properly, however if the user failed to match his/her password. i want to show an error message.
here is my PHP code:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
header("Location: anotherpage.php");
exit();
}
else
{
echo 'password does not match';
}
}
}
here is my ajax:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('#error').text(data);
}
});
return false;
});
The problem here is that it doesn't redirect to another page unless i refresh the page.
You can simply use javascript to redirect to the page like below:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo true;
}
else
{
echo 'password does not match';
}
}
}
And for redirecting, you can use:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data === true) {
window.location = 'Your url path here';
} else {
$('#error').text(data);
}
}
});
return false;
});
Instead of header("Location: anotherpage.php"); just do echo '1' and in your AJAX call, if data['responseText'] == '1' than just do a document.location.href = 'anotherpage.php'
JavaScript does not work with header() as it is browser-based language whereas PHP communicates directly with the Server. The best solution would probably be to return an error flag and message json_encode()'d.
If you return 0 (error) then display a message.
If you return 1 (success) redirect with JavaScript to a URL passed by php. That way you will be able to easily change the new URL should anything change in the website.
JavaScript
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: 'json',
data: frm.serialize(),
success: function (data) {
if (data.r == 0){
$('#error').text(data.m);
}
if (data.r == 1){
document.location.href = data.m;
}
}
});
return false;
});
PHP
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo json_encode(array(
'r' => 1,
'm' => 'anotherpage.php'
));
exit();
}
else
{
echo json_encode(array(
'r' => 0,
'm' => 'Passwords do not match'
));
exit();
}
}
}
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data) {
winlow.location = data;
}
}
});
return false;
});
In your action page just echo the link where you wanna redirect if you want

Handling ajax responses with Codeigniter

I've been handling success/error messages by returning json encoded arrays as a response, but it suddenly occurred to me that this probably isn't the correct way of handling notifications.
For example, my controller will look like this:
public function controller_name() {
//validate form input
$this->form_validation->set_rules('id', 'id', 'required|is_natural_no_zero');
// if validation was successful with no errors
if ($this->form_validation->run() && $this->model_name->method()) {
$this->data['status'] = 'success';
$this->data['message'] = 'This is the success message';
echo json_encode($this->data);
} else {
$this->data['status'] = 'error';
$this->data['message'] = validation_errors();
echo json_encode($this->data);
}
}
Then the jQuery:
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (r) {
json = $.parseJSON(r);
if (json.status == 'success') {
if (json.message == 'added') {
$this.addClass('success');
} else {
$this.removeClass('success');
}
} else {
console.log('There was an error')
}
What's the best practice way to do this? Can I throw exceptions to use the ajax error?
Sending erroneous http status code should trigger the jQuery ajax error handler:
public function controller_name() {
//validate form input
$this->form_validation->set_rules('id', 'id', 'required|is_natural_no_zero');
// if validation was successful with no errors
if ($this->form_validation->run() && $this->model_name->method()) {
$this->data['message'] = 'This is the success message';
} else {
$this->output->set_status_header('400'); //Triggers the jQuery error callback
$this->data['message'] = validation_errors();
}
echo json_encode($this->data);
}
JS:
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (r) {
var json = $.parseJSON(r);
},
error: function( jqXhr ) {
if( jqXhr.status == 400 ) { //Validation error or other reason for Bad Request 400
var json = $.parseJSON( jqXhr.responseText );
}
}
});

Categories