I want to call the codeigniter controller with ajax after the login. But when I execute it, the login page is only refreshed and ajax url isn't calling controller function of codeigniter.
I don't understand what happened. Please help?
Below is my code
function ValidateReg() {
var username = document.getElementById("inputName").value;
var password = document.getElementById("inputPassword").value;
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1)) {
$.ajax({
url: "<?php echo site_url('Dashboard/state'); ?>",
type: 'POST',
complete: function (done) {
console.log("Finished.")
}
});
}
});
}
Here Panel and Dashboard are my two different Controllers
It gets refreshed because it's a submit button and it must be inside form. So it submits the form on click event.
What you need to do is make your function to return false on click of the button so that page doesn't get refreshed.
Update your HTML like this,
<button type="submit" class="btn button text-uppercase" onclick="return ValidateReg();">Login </button>
And your JS function would look something like this:
function ValidateReg() {
var username = document.getElementById("inputName").value;
var password = document.getElementById("inputPassword").value;
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1)) {
$.ajax({
url: "<?php echo site_url('Dashboard/state'); ?>",
type: 'POST',
complete: function (done) {
console.log("Finished.")
}
});
}
});
return false;
}
If what you want to do is go to the page Dashboard/state then using ajax is the wrong approach. You need to redirect to that page instead.
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1))
{
console.log("Finished.");
window.location = "<?php echo site_url('Dashboard/state'); ?>";
}
}
);
The other way to redirect with javascript would be done like this
window.location.replace("<?php echo site_url('Dashboard/state'); ?>");
which is probably better because it does not keep the originating page in the session history.
function ValidateReg() {
var username = document.getElementById("inputName").value;
var password = document.getElementById("inputPassword").value;
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1)) {
$.ajax({
url: "<?php echo site_url('Dashboard/state'); ?>",
type: 'POST',
success: function (done) {
console.log("Finished.")
}
});
}
});
return false;
}
Related
I did some research on this topic but i cant run this id is not send to page.
listdata.php
<td class="text-center" style="min-width:130px;">
<button style="width:100%" class="btn btn-primary detail-customer" data-id="<?php echo $m->id; ?>">Bilgi</button>
</td>
ajax.php
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: "id=" + id
})
.done(function(data) {
window.location = "customers/info";
})
})
controller:
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
print $id;
//$this->template->views('customers/info', $data);
}
Are you naming your ajax file as Ajax.php? is that a PHP file? It definitely should be a js file.
From what I know from Jquery and Ajax, url key takes the location of the PHP file, and the data key should be passed as an object. Take these two files as an example:
Ajax.js
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/absolute_path/to/php_file.php",
data: {my_id:id, my_custom_key: "my_custom_value"},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function(response){
console.log(response);
}
})
.done(function(data) {
window.location = "customers/info";
})
})
Php_file.php
<?php
$id = $POST["my_id"];
$customValue = $POST["my_custom_value"];
$response = ["message"=> "We took your id which is $id and your custom value which is $customValue"];
echo json_encode($response);
?>
This is a very basic example of how to use ajax.
Please try it
$(document).on("click", ".detail-customer", function() {
var id = $(this).data("id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: {"id":id},
Content-Type:"json"
});
.done(function(data) {
window.location = "customers/info";
})
});
"we do not read your complete controller code
if your code is correct total then please
first convert data in json then
return it.
"
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
echo json_encode($id);
//$this->template->views('customers/info', $data);
}
My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}
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.
I have a bootbox dialog with a button named save in a view called table_data.php and I would like to determine whether the Ajax post to database will be done based on a result obtained from the database.
I want the data only to be saved when the database query in home_model.php does not return any rows. However, when I do it, it does not work. It is a cms and I am using codeigniter framework.
My page is blank. And nothing appears. Please help me. I am new to web and have very little experience with JavaScript and php and just started on ajax. Your help will be much appreciated.
table_data.php (view)
bootbox.dialog({
message: '<div class="row"> ' +
'<div class="col-md-12"> ' +
'<form class="form-horizontal"> ' +
'<div class="form-group"> ' +
'<label class="col-md-4 control-label" for="awesomeness">Table ID: </label> ' +
'<div class="col-md-4">' +
'<input id="idtable" type="text" value="'+table_column_15+'"/>' +
'</div><br>' +
'</div>'+
'</form> </div> </div>',
title: "Form",
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function() {
console.log('save');
console.log($('#re_confirm')[0].checked);
var valueid = document.getElementById('idtable').value
if(valueid == 0)
myFunction();
var valueid2 = document.getElementById('idtable').value
if(valueid2==0)
return;
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id" : valueid2
"session_id" : table_column_15
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
console.log(response);
var check = $(response);
}
});
if(check==0)
return;
$.ajax({
url : "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id" : $('#idtable').val(),
},
success: function(response){
...
}
});
}
},
...
,
...
}
});
home_model.php (model)
public function check_occupied($tableid,$sessionid)
{
$sql = "SELECT * FROM booking WHERE table_id=$tableid and session=$sessionid;
$query = $this->db->query($sql);
if ($query->num_rows() > 0)
$imp = 1;
else
$imp = 0;
return $imp;
}
home.php(controller)
public function check_occupied()
{
$tableid = $_POST['table_id'];
$sessionid = $_POST['session_id'];
$imp = $this->home_model->check_occupied($tableid,$sessionid);
$this->load->view('table_data', $imp);
}
I found a few syntax minor errors but the biggest problem is where you are attempting to use the var check as in if(check==0).
Your condition evaluation if(check==0) is outside the success function of the ajax call to check_occupied. Therefore, if(check==0) will execute before the success function runs and sets a value for check. If you console.log(check); just before the if statement you will find the value to be 'undefined'. This console result will also be logged before the output of `console.log(response);' which will confirm the order of execution.
In other words, you need to decide on whether to run the next ajax call inside of the success function of the check_occupied ajax call.
Here's my version. It's untested but I think the concept is sound. This shows only the callback: for the "Save" button.
callback: function () {
console.log('save');
console.log($('#re_confirm')[0].checked);
var valueid = document.getElementById('idtable').value;
if (valueid === 0) {
myFunction();
}
var valueid2 = document.getElementById('idtable').value;
if (valueid2 === 0) {
return;
}
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id": valueid2,
//??? where is table_column_15 declared and initialized? Some global var?
"session_id": table_column_15
//and any other variables you want to pass via POST
},
success: function (response) {
// Handle the response object
console.log('response='+response);
//if I read check_occupied() right, response should only be 1 or 0
//there is no need to assign it to another var, eg. var check = response
//there is no apparent need to turn it into a JQuery object with $(response) either
if (response > 0) {
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id": $('#idtable').val()
},
success: function (response) {
}
});
}
}//end of success function callback for check_occupied() ajax
console.log('ajax to check_occupied is done.');
});
}
In CI, I have setup a controller with a method of logsig(). Then in my index() method I'm calling a view called startpage. In my view I'm using JSON to make an asynchronous call between my view and my controller. How would I code the call. Below is the code I have:
Contoller:
function logsig() {
$this->load->view('startpage', $sync);
header('Content-type:application/json'); .............
View:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// blink script
$('#notice').blink();
$("#action_button").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "processing/logsig.php",
data: dataString,
json: {session_state: true},
success: function(data){
if(data.session_state == true) { // true means user is logged in.
$("#main1").hide();
$('#main1').load('<?=$sync?>').fadeIn();
} else if(data.session_state == false) { // false means user is being registered.
$("#action_button").remove();
$('#success').load('<?=$sync?>');
// onLoad fadeIn
}
}
});
}
});
});
</script>
You can't have your controller load a view and return JSON at the same time. Break out the JSON portion to a separate function.
An oversimplified example could look like this:
// Your existing function, but only displaying the view
function logsig() {
$this->load->view('startpage', $sync);
}
// A new function whose sole purpose is to return JSON
// Also notice we're using CI's Output class, a handy way to return JSON.
// More info here: codeigniter.com/user_guide/libraries/output.html
function get_json() {
$this->output->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
}
Then, in your JavaScript, call get_json:
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url('processing/get_json.php'); ?>",
// ... truncated for brevity ...
});
If I read your question correctly, your JS postback code isn't working:
url: "processing/logsig.php",
Your CI url should be something like:
url: <?php echo site_url("processing/logsig"); ?>,
The site_url() function requires the URL helper. Load that in the beginning of your loadsig() function:
$this->load->helper('url');
Try This
Controller ---------
public function AjaxTest() {
$rollNumber = $this->input->post('rollNumber');
$query = $this->welcome_model->get_students_informationByRoll($rollNumber);
$array = array($query);
header('Content-Type: application/json', true);
echo json_encode($array);
}
View-----
<?php echo validation_errors(); ?>
<?php echo form_open('welcome/SearchStudents'); ?>
<input type="text" id="txtSearchRoll" name="roll" value="" />
<input type="submit" name="btnSubmit" value="Search Students" onclick="return CheckAjaxCall();"/>
<?php echo '</form>'; ?>
Scripts ----------
function CheckAjaxCall()
{
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>welcome/AjaxTest',
dataType:'json',
data:{rollNumber: $('#txtSearchRoll').val()},
cache:false,
success:function(aData){
//var a = aData[0];
//alert(a[0].roll);
$.map(aData, function (item) {
var stData = "<td>"+ item[0].roll +"</td>" +
" <td>"+item[0].Name+"</td>" +
"<td>"+item[0].Phone+"</td>" +
"<td> Edit </td>"+
"<td> Delete </td>";
$('#tblStudent').text("");
$('#tblStudent').append(stData);
//alert (item[0].roll + " " + item[0].Name);
});
//alert(aData);
},
error:function(){alert("Connection Is Not Available");}
});
return false;
}