jquery - how to create condition in success function - php

I want to create jquery ajax success function based resp from logout.php. If users not sign in,It redirect bring them to login page.,but it's not working as I'm expected,no event occur when user is logged or not.So, what is wrong with my ajax function?
logout.php
<?php
if( !$user->is_logged ) {
echo 'true';
}else{
echo 'false';
}
?>
jquery function in index.html
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
if(resp =='true'){
document.location = '../login_test.html';
}
if(resp=='false'){
alert('U are logged');
}
}
});
});

Change some errors and made it to better view:
PHP:
<?php
header('Content-Type: application/json');
if( !$user->is_logged ) {
echo json_encode(array('status' => 'ok'));
}else{
echo json_encode(array('status' => 'bad'));
}
?>
Javascript:
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
var state = JSON.parse(resp).status
if(state == 'ok'){
document.location.href = '/login_test.html';
}
else{
alert('U are logged');
}
}
});
});
If you have no alert, and have no redirect - you have not .success callback, and problem one level above your condition. In that case show us your errors from js-dev-console from browser.

Related

Codeigniter validation not working with ajax but without ajax working well

when submitting the form using ajax codeigniter validation not working please resolve this issue i am facing this problem from last week
jQuery code that i am using for submitting form
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
data: contactForm.serialize(),
success: function(response){
}
});
});
});
Controller
public function add_account() {
if($this->form_validation->run('add_account')) {
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
} else {
$this->login();
}
}
Here is just the concept. I have not tried codeigniter but am php professional.
You will need to retrieve records as json and pass it to ajax. At codeigniter
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'Account Created Successfully !');
echo json_encode($result);
hence the code might look like below
public function add_account(){
if($this->form_validation->run('add_account')){
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'ok');
echo json_encode($result);
//$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
}else{
$this->login();
}
}
in ajax you can set datatype to json to ensure that you can get response from the server and then let ajax handle the response....
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function(response){
alert(response.message);
console.log(response.message);
//display success message if submission is successful
if(response.message =='ok'){
alert('message submited successfully');
}
}
});
});
});
You have a misunderstanding about what an ajax responder can and cannot do. One thing it cannot do is use PHP to make the browser redirect to a new page. You will have to send a clue back to the success function and then react appropriately.
A few minor changes to the answer from #Nancy and you should be good.
public function add_account()
{
if($this->form_validation->run('add_account'))
{
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post))
{
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
echo json_encode(array("result" => 'ok'));
return;
}
$message = '<span class="error">Account Not Created!</span>';
}
else
{
$message = validation_errors('<span class="error">', '</span>');
}
echo json_encode(array("result" => 'invalid', 'message' => $message));
}
In the Javascript, handle the various responses in the success function of $.ajax
$(function () {
$("#registratiom_form").on('submit', function (e) {
var contactForm = $(this);
e.preventDefault();
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function (response) {
console.log(response); // so you can examine what was "echo"ed from the server
if (response.message=='ok') {
// Simulate an HTTP redirect: to the right page after successful login
window.location.replace( "https://example.com/frontend/somepage");
} else {
//stay on the same page but show the message in some predefined spot
$('#message').html(response.message);
}
}
});
});
});

jquery ajax response in html form

I have send query ajax request to server. The server response in two variable that is errmsg or successmsg . so how can i understand response is whether errmsg or successmsg. More code explain below
script.js
$.ajax({
url:"abc.php",
method:"POST",
data:$('#form').serialize(),
success:function(data){
?????????
}
error:function(data){
.......
}
});
abc.php
<?php
if (condition) {
$successmsg = hello;
echo "$successmsg";
}
elseif (condition) {
$errmsg = Error Occured;
echo "$errmsg";
}
elseif (condition) {
$successmsg = welcome;
echo "$successmsg";
}
else {
$errmsg = Bye;
echo "$errmsg";
}
?>
return error or success depending on what you are doing with your code in php for example
return iferror ? ['errmsg' = 'Error'] : ['successmsg'=>'success'];
then get your response in ajax like
$.ajax({
url : 'your-url,
data : {your - data},
success: function(response){
if(response.successmsg){
console.log(response.successmsg);
}
else{
console.log(response.errmsg);
},
error: function(response){
console.log(response);
}
});
You can return the server's response using this code:
<?php
if ($textvar > 500){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
?>
Then the Ajax code can be:
$.ajax({
cache: false,
url: '/js/checkmsgs.php',
success: function(res){ // This will be applied if the php code is completlly done without any programming mistakes.
if (res == 'SUCCESS'){
alert('Success');
}else{
alert('Error !');
}
},
error: function(){ // this one will be applied if the php code have a mistake !
alert('eeeeeerrror');
}
});

Ajax function issue on return true and false in wordpress

I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.

Page reload not working when the page was called by AJAX

Let's say this is my AJAX
function call_page(id)
{
$.ajax({
type: "POST",
url: "call_me.php",
data: "id=" + id,
success: function(msg){ }
});
}
call_me.php was successfully called.
Let's say this is my call_me.php content
<?php
$var = $_POST['id'];
if(empty($var))
{
header("location: call_me.php?id=101");
}
else
{
do something...
}
?>
Assuming that the first condition 'if(empty($var))' is always satisfied.
The page must reload and the go to the else statement.
But this is not happening. I guess the page isn't reloading.
How can I correct this problem?
Thanks!
Try this
<?php
$var = $_GET['id'];
if(empty($var))
{
// here flag for redirection is set
echo 1;
}
else
{
do something...
}
?>
In AJAX:
$.ajax({
type: "POST",
url: "call_me.php",
data: "id=" + id,
success: function(msg){
// checking the response is for redirection
if(msg == 1)
// javascript code for redirecting to callme.php
window.location = "call_me.php?id=101";
}
});

php header is working but with mistakes

Actually I'm trying to redirect to the index after logging in with ajax button
but what is happening is strange , header is not taking me to the index.php !
i just get the HTML code of the index.php in my login.php page !!
I'm using Smarty to separate the html from php code , and I don't know how to fix the problem !
click the login and get the HTML of the index in login page !
why ?
in login.php page
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}
the ajax function :
function ajax3(Div_Submit,Div_Response,SuccessScript,Data_Submit)
{
var Type = 1;
var Aj_type = "POST";
var post_data = '';
if(!Data_Submit)
post_data = $('#'+Div_Submit+' *').serialize();
else
post_data = Data_Submit;
$.ajax({
type: Aj_type,
url: document.URL,
data: post_data,
dataType: "text",
beforeSend: function(xhr)
{
$.blockUI({ message: '<img src="images/loading.gif" />',
css: { border: 'none', backgroundColor: 'transparent' } });
xhr.setRequestHeader("Ajax-Request", "true");
},
success: function(response) {
$('#'+Div_Response).html(response+'<script>'+SuccessScript+'</script>');
},
complete: function(){
$.unblockUI();
}
});
return false;
}
the html button call :
<div class="buttons" >
<a class="positive" onclick="$('#login_action').val('login');ajax3('login_form','login_form','','')">
<img src="images/checkbox_checked.png" alt=""/>
<font size="3px"> login </font>
</a>
</div>
That wouldn't work as what you expected.
It should be something like this.
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo "success";
}
On your javascript/jquery file.
have something like this
jQuery.ajax({
url: "login.php",
success:function(data){
if(data == "success") window.location = "index.php";
}
});
With AJAX, this is the expected output. What happens is that the AJAX request itself is being redirected to index.php, which I what is then outputted and returned to that request.
If you want to redirect to index.php from AJAX, you would need to exit with a specific code, or a JSON-encoded value and catch that in the AJAX result itself.
Example:
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo json_encode(array('redirect' => 'index.php'));
exit;
}
JavaScript:
$.ajax(
url: 'your-url',
success: function(data) {
if (data.redirect) {
document.location.href = data.redirect;
}
}
);
u can get success response whenever login credentials are appropriate , at that moment change the window location using javascript or jquery..

Categories