I have an issue redirecting to another page in codeigniter, this is my js:
<script type="text/javascript">
$(document).ready(function () {
var url = $('#baseurl').val();
var form = $('#customerinfo');
$('#next').click(function (e) {
if ($("form")[0].checkValidity()) {
// Prevent submit.
e.preventDefault();
//Start loading
var checkbox = $('#Accept');
if (checkbox[0].checked == true)
{
$.post(url + 'customerinfo/next', form.serialize(), function(response) {window.location.href=url + 'paymentinfo';});
}
else
{
$("#errmsg .msg").text("You need to read and accept the terms and conditions before you can continue!");
$("#errmsg").css("display", "block");
}
$(".loading-add-ticket").css("display", "block");
// Send request.
}
else console.log ( "invalid form" );
});
});
</script>
What it does:
When the next button is clicked it submits the form via ajax, the form is then processed on the server and upon completion the user is redirected using the following block of code:
<?php
class CustomerInfo extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
// Write to $title
$this->template->write('title', 'Customer Info');
// Write to $content
$this->template->write_view('content', 'tickets/customerinfo');
// Write to $sidebar
$this->template->write_view('sidebar', 'sidebar');
// Render the template
$this->template->render();
}
function next()
{
if ($_POST) {
if (isset($_POST['Accept']))
{
$data[0] = array(
'TravelInsurance' => $_POST['TravelInsurance'],
'LuggagePayment' => $_POST['LuggagePayment'],
'Donations' => $_POST['Donations'],
'FirstName' => $_POST['FirstName'],
'LastName' => $_POST['LastName'],
'CityTown' => $_POST['CityTown'],
'ContactNo' => $_POST['ContactNo'],
'Address' => $_POST['Address'],
'Accept' => $_POST['Accept']
);
$this->session->set_userdata('customerinfo', $data);
redirect(site_url('paymentinfo'));
}
}
}
}
?>
The problem:
The redirect never happens, when i check the post response using firebug in my browser i notice that the target page has been returned :
What i want: I need the page to be redirected to the target page, i am new to codeigniter so i do not know what i am doing wrong.
current fix:
In the success function on my ajax function i am using javascript to redirect to the next page but i do not want the redirects to be handled on the client side.
Somtimes with forms i prefer to use
header("Location: /Controller/method/value");
i know that's a dirty method but sometimes is helpful
Related
I am trying to make a delete button which I'll be able to delete some user from my database but main thing how to call PHP function with clicking on some div etc..
<div class="cross" onclick='<?php deleteUser("Nickname")?>'>X</div>
<?php
function deleteUser($username) {
//... code
}
?>
Html can't directly call php, it can do a separate call to load the same page, with the action.
<?php
function deleteUser($username){}
if($_GET['action'] == "delete")
{
deleteUser($_GET['username']);
}
?>
<a class="cross" href='?action=delete&username=NickName'>X</a>
The reason for this is because PHP runs on the server, BEFORE anything is sent to the browser. So it requires another page load to run the function by clicking something. It is possible to use javascript and AJAX calls to send a call to a php script without reloading the main page. Just look into Jquery's post or ajax features.
You cannot call a PHP function that resides on the server by just clicking on a div that exists on the client browser.
You need to trigger a Javascript event (using e.g. jQuery), that will call a function on the server (e.g. through AJAX), that after checking the parameters are correct and the user has the right of calling it will do what you seek.
There are ready-made frameworks that would allow you to do that.
Otherwise (after including jQuery in your HTML page) you can do something like,
<div class="cross" id="deleteUserButton" data-user="nickname">X</div>
<script type="text/javascript">
$('#deleteUserButton').on('click', function() {
let nick = $(this).attr('data-user');
$.post('/services/delete.php',
{
cmd: 'delete',
user: nick
}).then( reply => {
if (reply.status === 'OK') {
alert("User deleted");
}
});
<?php
$cmd = $_POST['cmd'];
switch($cmd) {
case 'delete':
$user = $_POST['user'];
if (deleteUser($user)) {
$reply = [ 'status' => 'OK' ];
} else {
$reply = [ 'status' => 'failure', 'message' => 'Doh!' ];
}
break;
...
header('Content-Type: application/json;charset=UTF-8');
print json_encode($reply);
exit();
Now I am upgrading my website user experience, so I'm trying modify my form from form action to ajax.
Coding now work fine, server side can update the database, but I don't know how to return the custom message to my user.
My html coding.
<form method="post" id="jnfarm_pop">
blablabla...
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login();">submit</button>
</form>
My php file plugin.php
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
My jQuery
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
Now the alert doesn't work, I am also try like
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
result = JSON.parse(result); alert(result.final); //not working also
}
and
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result = JSON.parse(result)) => {
alert(result.final); //this show alert unidentified
}
Can someone correct my coding?
Change
return json_encode(['final' => $final]);
to
echo json_encode(['final' => $final]);
return is really only useful when you're inside a PHP function. If you want to output something back to the caller of the script then you need to use echo, as always.
To make your example work do the following:
change your PHP code from
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
to:
<?php
//coding.....
$final = 'custom wording';
echo json_encode(['final' => $final]);
?>
and your jQuery code from this:
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
to this:
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert(result);
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
PHP can return something to an ajax call by either printing or echoing. And ajax can't use variables you defined in PHP. The echo'ed value in your PHP script will be the result value in your ajax call.
I have a front-end Ajax call set up to randomize an image whenever a button is pressed. I set it up as follows:
Functions.php
define("AJAX_URL", admin_url('admin-ajax.php'));
add_action("wp_enqueue_scripts", "enqueue_eyewebz_scripts");
function enqueue_eyewebz_scripts()
{
wp_enqueue_script("jquery");
...
wp_enqueue_script("root-js", JS_URL . "/root.js", array("jquery"));
$script_params = array(
'ajax_url' => AJAX_URL
);
wp_localize_script('root-js', 'theme_vars', $script_params);
}
root.js
function parallax_randomize(e)
{
var data = {
'action': 'randomize_parallax',
'dataType': 'json'
};
console.log(theme_vars.ajax_url);
jQuery.post(theme_vars.ajax_url, data, function(response) {
console.log(response);
var dynb = JSON.parse(response);
jQuery('#front-location span').html(dynb.location);
jQuery('.parallax-slider').fadeOut('fast', function () {
jQuery('.parallax-slider').attr('src', dynb.url);
jQuery('.parallax-slider').fadeIn('fast');
});
});
}
Dynamic background callback
class Dynb
{
function Dynb()
{
...
$this->set_up_ajax();
...
}
public function set_up_ajax()
{
add_action('wp_ajax_randomize_parallax', array($this, 'randomize_parallax'));
}
public function randomize_parallax()
{
$data = set_dynamic_background(true);
echo json_encode($data);
wp_die();
}
}
new Dynb();
In Firefox, this works just fine, but in Chrome, my JS Ajax call returns 0. I can't for the life of me figure out what the problem is. Anyone?
just add exit() in randomize_parallax() function,i think it will fix your issue
When sending an ajax request from the front-end, you need to include an action that has wp_ajax_nopriv_ ... (shown below) if you want this to work. If you don't add that action, users that are not logged in will not be able to call for the ajax function.
add_action('wp_ajax_nopriv_randomize_parallax', array($this, 'randomize_parallax'));
I am using kartik select2 widget in my yii2 basic app. now i have to display province names in select2 widget on ajax call. It is working fine if i put it directly in form. however not working with ajax call.
Here are my form fields:
<?= $form->field($model, 'role')->dropDownList(
ArrayHelper::map(SubAdminRoles::find()->all(), 'id', 'role_name'),
[
'prompt' => 'Select Role',
'onchange' => '
if($(this).val() != 3) {
$( "#user_area" ).html("showLoading");
$.post( "fetch-area-list?id='.'"+$(this).val(),
function(data) {
$( "#user_area" ).html(data);
})
}'
]
) ?>
<div id="user_area">
</div>
And here is my action code
public function actionFetchAreaList($id) {
// $this->layout = 'none';
$data = [];
if($id == 1) {
$provinceList = \app\modules\adminpanel\models\ProvinceMaster::findAll(['status' => 1, 'is_deleted' => 0]);
foreach($provinceList as $obj) {
$data[$obj['id']] = $obj['province_name'];
}
//print_r($data);
//exit;
} else if($id == 2) {
$subDistrictList = \app\modules\adminpanel\models\SubDistrictMaster::findAll(['status' => 1, 'is_deleted' => 0]);
foreach($subDistrictList as $obj) {
$data[$obj['id']] = $obj['sub_district_name'];
}
}
echo '<label class="control-label">Select Province</label>';
echo Select2::widget([
'name' => 'state_2',
'value' => '1',
'data' => $data,
'options' => ['multiple' => true, 'placeholder' => 'Select Province']
]);
exit;
}
now when i try to get it through ajax i comes with display:none property so i am not able to show my select2 box.
I Also tried changing display:none to display:block in select2 class. In that case i got the select box, but is simple html multiple select box not select2 widget.
How to get it from controller using ajax call?
Thanks in advance.
It is bad practice to render html inside action.
In your case widget requires related JS for initialization. But it will not include in your response.
Move all your html to view area-list and render using following code:
public function actionFetchAreaList($id) {
$this->layout = false;
// ... preparing data
return $this->renderAjax('area-list', [
// ... some view data
]);
}
Method renderAjax renders a named view and injects all registered JS/CSS scripts and files. It is usually used in response to AJAX Web requests.
I also have similar project like this.
I have 2 combobox (using select2). When select a district from the first combobox. It will call an ajax request to get province list and fill into the second combobox.
Here is my solution:
Using Select2 widget as normally in form
Using javascript to call ajax request and change data of the second combobox.
My controller response data in json format.
$('#district-selector').on('change', function() {
var districtId = $(this).val();
var url = $(this).attr('tb_href');
$('#province-selector').html('');
$.get(
url,
{
city_id: districtId
},
function(response) {
if (response.error == 0 && response.data.length) {
$('#province-selector').append(new Option('', ''));
$.each(response.data, function() {
console.log(this.id + '--' + this.title);
var newOption = new Option(this.title, this.id);
$('#province-selector').append(newOption);
});
}
$('#province-selector').trigger('change');
}
);
});
Demo: demo link
I have the following method which allows a user to login into my application:
public function login()
{
if($this->Auth->user())
{
$this->Session->setFlash(__('Already logged in...'), 'default', array(), 'auth');
$this->redirect(array('controller'=>'pages','action'=>'display','home'));
}
if ($this->request->is('ajax'))
{
$this->layout = 'ajax';
if ($this->Auth->login())
{
}
else
{
}
}
else if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
It allows a user to login either using a post request or via an ajax request. However with regards to the ajax requests how do I pass the results back using JSON? So for example if the user enters the wrong details pass back an error message?
I have the jQuery AJAX already setup so I just need to do some extra logic in the success method to deal with the return which will either show the error message from the server or do a redirect again based on the return from the server.
e.g.
$('form').live('submit', function (event) {
// Declare the form
var form = $(this);
// Stop the form from doing a native postback
event.preventDefault();
// Get the data from the form
var data = form.serialize();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data,
success: function (responseHtml) {
// If correct login details
if(success){
window.location.href('INSERT LOCATION TO REDIRECT TO FROM SERVER');
} else {
alert('INSERT MESSAGE FROM THE SERVER');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error!');
}
});
});
Can anyone help? I'm using CakePHP 2.0 and all of the tutorials I have seen on the net and on here have either been outdated or much too long-winded for what I'm trying to achieve.
Edit: you need to use the following php code
if ($this->Auth->login())
{
$arr = array("login" => "true" , "redirect" => "/redirect_url");
echo json_encode($arr);
}
else
{
$arr = array("login" => "false" , "error" => "Invalid Login Credentials");
echo json_encode($arr);
}
on the javascript side you need to modify your javascript to handle json values using jQuery.getJSON. example of jQuery.getJSON is availabe here http://api.jquery.com/jQuery.getJSON/
use this jQuery code
<script type="text/javascript">
$.getJSON("login.php", function(data) {
if(data.login)
{
//redirect user with data.redirect
}
else
{
//display error with data.error
}
})
</script>