Ajax won't call Codeigniter controlllers's method - javascript

I'm total beginner to ajax (don't know jquery at all) so i've been using simple ajax without jquery, what i want to do is simple to call codeigniter's controller method. Dont know what i'm wrong at. Here's my ajax function and controller:
function usernameOnChange() {
var username = document.getElementById("register_username").value;
if (username.length == 0) {
document.getElementById("usernameGlyph").className = "glyphicon glyphicon-remove";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("usernameGlyph").className = 'glyphicon glyphicon-ok';
}
};
var link = "<?php echo base_url("index.php/Test/checkUsername?username="); ?>" + username ;
xmlhttp.open("GET", link, true);
xmlhttp.send();
}
}
And here's my controller (it's still test controller just to see that my ajax-codeigniter php connection is working).
<?php
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper("url");
$this->load->library("form_validation");
$this->load->helper("security");
$this->load->helper("form");
}
public function checkUsername($username) {
echo "<script>alert('CODEIGNITER RESPONDED!');</scirpt>";
}
}
?>
Thanks in advance!

Before you start with ajax, need to understand that ajax required to have good output from the PHP to get perfect result of the call. In your codeigniter controller, you are echoing a script tag. Please dont do that when you use a ajax call.
Sample Codeigniter Controller function
<?php
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper("url");
$this->load->library("form_validation");
$this->load->helper("security");
$this->load->helper("form");
}
public function checkUsername($username) {
$output = array('status'=>200,"message"=>"Your Ajax is called");
header('Content-Type:application/json;');//Please do not forgot to set headers
echo json_encode($output);
}
}
Here the controller will give perfect output which javascript can read it easiliy
For jQuery
<script type="text/javascript">
$.get('<?php echo base_url("index.php/Test/checkUsername?username=xyz"); ?>',function(data){
alert(data['message']);
});
</script>

First of all your this line will produce error or unexpected result.
var link = "<?php echo base_url("index.php/Test/checkUsername?username="); ?>" + username ;
//double quote inside double quote
It should be like this
var link = "<?php echo base_url('index.php/Test/checkUsername?username='); ?>" + username ;
You also need to know how site_url and base_url function produce links
Finally I think your link should be like this.
var link = "<?php echo base_url('index.php/Test/checkUsername/'); ?>" + username ;
//you can remove index.php if you set your config file properly.

Okay, so here's solution that I've found out and it works fine. It changes icon-span of input field to tick if login username that is typed at the moment exists in database. Otherwise it changes icon to cross. Don't forget to add "&" when sending via "get" more than 1 parameter to controller's method.
$("#login_username").keyup(function() {
$.ajax({
type: 'GET',
url: '<?php echo base_url().'index.php/Test/checkLoginUsername'; ?>',
data: 'type=' + $('#logintype').is(':checked') + '&username=' + $("#login_username").val(),
success: function(newClassType) {
$("#usernameLoginGlyph").removeClass().addClass(newClassType);
}
})
});
Here's my controller method that echos result class type of icon.
public function checkLoginUsername() {
// type = true for customer; false for artist
$type = $this->input->get('type');
$username = $this->input->get('username');
if ($type === "true") {
if ($username === "" || $this->Customer_model->getCustomerByUsername($username)) {
echo "glyphicon glyphicon-ok";
} else {
echo "glyphicon glyphicon-remove";
}
} else {
if ($username === "" || $this->Artist_model->getArtistByUsername($username)) {
echo "glyphicon glyphicon-ok";
} else {
echo "glyphicon glyphicon-remove";
}
}
}

Related

create dynamic select box through ajax with large data

I am working with codeigniter and ajax. There are two select boxes like country and states.I am appending options to states select box based on country, through ajax request.
It works fine for few hundreds of records.
But When number of records exceed 1000, ajax take too much time to create select box, even page goes to not responding state.
I am using this code:
var country_id = $(selector).val();
$.ajax({
url:'<?php echo base_url()?>getstates',
crossDomain: true,
data:'country_id ='+country_id ,
success:function(data){
var dataObj = jQuery.parseJSON(data);
$(dataObj).each(function(){
// Remove options
$('#selectBoxState').find('option').not(':first').remove();
// Add options
$.each(dataObj,function(index,data){
$('#selectBoxState').append('<option value="'+data['state_id']+'">'+data['state_name']+'</option>');
});
});
},
error: function() {
alert("failure");
}
});
What will be the best way to do so.
Here are my working solutions for CodeIgniter 3.x
Controller Page
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controller_name extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load-helper('dropdown');
$dropdownItems = listData('countryTableName','countryId', 'countryName',['where' => ['countryStatus' => 1]]);
$selected = array('null');
$data['countryDropdown'] = form_dropdown('countryId',$dropdownItems,$selected);
$data['stateDropdown'] = form_dropdown('stateId',[], '', 'required="required"');
$this->load->view('page_view',$data);
}
public function get_state()
{
$countryId = $this->input->get('countryId');
$dropdownItems = listData('stateTableName','stateId', 'stateName',['where' => ['countryId' => $countryId,'stateStatus' => 1]]);
$selected = array('null');
echo $stateDropdown = form_dropdown('stateId',$dropdownItems,$selected);
}
}
Place this dropdown_helper.php in Helper directory
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
function listData($table,$name,$value,$options = []) {
$items = array();
$CI =& get_instance();
if(array_key_exists('where',$options)) {
$CI->db->where($options['where']);
}
$query = $CI->db->select("$name,$value")->from($table)->get();
if ($query->num_rows() > 0) {
foreach($query->result() as $data) {
$items[$data->$name] = $data->$value;
}
$default = array('null' => 'Please Select');
$select = $default + $items;
$query->free_result();
return $select;
}
}
In view page just echo
<?php echo $countryDropdown; ?>
<?php echo $stateDropdown; ?>
js file
$(function(){
$('select[name=countryId]').on('change',function(){
$('select[name=stateId]').html('');
$.ajax({
url: 'controller_name/get_state?countryId='+$(this).val(),
type: "GET",
}).done(function(data) {
$('select[name=stateId]').html(data);
}).fail(function() {
}).always(function() {
});
});
});

How to call a function in the URL (PHP)

Currently I have this code as shown below.
Whereby, when I click on the button, it will show either success or fail.
I have another php script on another webpage to call from it.
Currently I call the php script, using the php file name. I would like to check is there a way for me to call the php file using a function in the url?
The reason is because, in the php script, I would have several functions to call from. I do not want to create multiple php file.
below is my code.
<script>
function bookBTN(x) {
$.getJSON('http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + x, function(data) {
if (data.avail == "yes") {
alert("Success");
}
else { alert("Failure"); }
});
}
</script>
<script>
function viewBTN(x) {
$.getJSON('http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x, function(data) {
if (data.avail == "yes") {
alert("Success");
}
else { alert("Failure"); }
});
}
</script>
movieOne.php
<?php
$seatNum= $_GET["seatNum"];
getSeatNum1($seatNum);
function getSeatNum1($seatNum) {
$seatNum = $_GET["seatNum"];
$url = 'http://movie.com/movieOne?seatNum=' . $seatNum;
$result = file_get_contents($url);
echo $result;
?>
<?php
$seatNum= $_GET["seatNum"];
getSeatNum2($seatNum);
function getSeatNum2($seatNum) {
$seatNum = $_GET["seatNum"];
$url = 'http://movie.com/movieOne?seatNum=' . $seatNum;
$result = file_get_contents($url);
echo $result;
?>
When I only run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + x and having only 1 php function inside movieOne.php , it works fine.
When I run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + xand http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x , having only 1 php function inside movieOne.php , it works fine too.
However when I run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + xand http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x , and have 2 different function (as the code above), the button doesn't work.
If you want to call function from url like codeigniter do, i have an example for you
URL example: http://localhost/jastip/ajax/request.php/get_orders
(function () {
$url_function = explode('/', $_SERVER['REQUEST_URI']);
$function_name = get_defined_functions()['user'];
if (in_array($url_function[4], $function_name)) {
$index = array_search($url_function[4], $function_name);
$dynamic_fun = $function_name[$index];
$dynamic_fun();
} else {
var_dump("Page not found");
die;
}
})();
function get_orders()
{
echo "get orders";
}
function get_something()
{
echo "get something";
}

Calling javascript function in my PHP code

I searched up some questions on stackoverflow and used the suggested solutions, however, I can't seem to get my php code working the way I'd like.
When I visit projects.php?message=success or projects.php?message=removed, the JavaScript function does not execute. In my debugging, I've confirmed the JavaScript is working correctly by attaching it to a button with the onclick property.
My php code:
<?php
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$alert= GET('message');
if ($alert == success) {
echo '<script type="text/javascript"> window.onload=success(); </script>';
} elseif ($alert == removed) {
echo '<script type="text/javascript"> window.onload=removed(); </script>';
}
?>
My JavaScript code:
<script>
function success() {
$.notify({
// options
icon: "pe-7s-cloud-upload",
message: 'New project entry was successfully added.'
},{
// settings
type: 'success'
});
}
function removed() {
$.notify({
// options
icon: "pe-7s-trash",
message: 'Project entry was successfully deleted.'
},{
// settings
type: 'danger'
});
}
</script>
You need quotes around the texts and properly set window.onload:
<?php
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$alert = GET('message');
echo "<script>window.onload = function () { ";
if ($alert == "success") echo "success();";
else if ($alert == "removed") echo "remove();";
echo " };</script>";
?>
If those two are all you need, you can also do this:
$alert = GET('message');
if ($alert == "success" || $alert == "remove") {
echo "<script>window.onload = $alert;</script>";
}
Edit:
To clarify an issue from the comments: to set window.onload to a function, one cannot use
window.onload = myFunc(); // WRONG!
(This will call the function, then set window.onload to the result)
The correct way is:
window.onload = myFunc;
// OR
window.onload = function () {
myFunc();
};
I've tested is the inexistent constant you're using called success.
As #Chris G said
Change the if for :
if ($alert == "success")

Create Instance of PHP object from AJAX call

I'm playing with using AJAX to perform a simple login function using PHP. I haven't been able to get the AJAX call to successfully create an instance of the Controller class in the login handler file. I feel like I'm just not seeing something that is really basic.
I want to just say thank you in advance for any help! Also, this is not meant to be a real website or a real login script. I understand there are SO many security holes the way it is currently written. I fully intent to add all the bells, whistles, validation, etc. necessary to turn this simple code into something useful as soon as I understand the mistake.
The 4 files that should communicate with each other are as follows:
view/login.php
function signIn( )
{
if(checkString( ))
{
$.ajax({
type: "POST",
url: "ajax.php",
data: "username=" + $("#username").val( ) + "&password=" + $("#password").val( ),
dataType: "html",
async: false,
cache: false,
success: function(result){
$("#temp_container").html(result);
}
});
}
}
AJAX.php
<?php
if(isset($_POST['username']) && !empty($_POST['password']))
{
$controller = new IndexController( );
$result = $controller->login($_POST['username'], $_POST['password']);
if($result > 0)
$user_validation = array('true', 'view/chat_app.php');
else
$user_validation = array('false', 'index.php?error_num=1');
echo json_encode($user_validation);
}
else if(isset($_POST['username']) && empty($_POST['password']))
{
//notify the user they didn't put in a password
}
?>
Controller.php
<?php
include_once("model/indexModel.php");
class IndexController
{
public $model;
public function __construct( )
{
$model = new IndexModel( );
}
public function login($username, $password)
{
$result = $model->login($username, $password);
if($result >= 1)
return true;
else
return false;
}
}
?>
Model.php
<?php
include_once("config/config.php");
$db = new mysqli($GLOBALS['config']['db_host'], $GLOBALS['config']['db_username'], $GLOBALS['config']['db_password'], $GLOBALS['config']['db_name']);
class IndexModel
{
public function login($username, $password)
{
global $db;
$statement = $db->prepare("SELECT 1 FROM authorized_users
WHERE username = ?
AND password = ?");
$statement->bind_param('ss', $username, $password);
$statement->execute( );
$statement->close( );
return $statement->affected_rows;
}
}
?>

Ajax to controller function(codeigniter) not working properly

Loading the builder controller
<a class = "button tiny" href = "<?php echo site_url('builder/app/'.$experiment->eid); ?>"> Edit </a>
CodeIgniter Controller
class Builder extends MY_Controller{
public function index(){
$data['title'] = 'Experiment';
$data['main_content'] = 'experiment/add_experiment_form';
$this->load->view('_main_layout', $data);
}
public function app($eid = 0){
$data['title'] = 'Experiment';
$data['eid'] = $eid;
$data['main_content'] = 'experiment/add_experiment_form';
$this->load->view('_main_layout', $data);
}
public function save() {
$message = $this->input->post('msg');
echo $message;
}
}
JAVASCRIPT
$("#getObjectValues").click(function () {
var msg = '[';
for(i=1; i<$.count; i++){
if (i!=1) {msg+=","}
var offset = $('#obj'+i).offset();
var xPos = offset.left;
var yPos = offset.top;
msg += "("+xPos+","+yPos+")";
}
msg += ']';
$.ajax({
url:"builder/save",
type:"POST",
data:{'msg':msg},
success: function(data) {
alert('success '+data);
window.location.href = "<?php echo site_url($this->session->userdata('active_role').'/experiments'); ?>";
}
});
});
Clicking the edit button from another html file triggers the app function from the builder controller. It then loads the page add_experiment_form with the supplied javascript is a separate html file. When the getObjectValues button is clicked, the variable msg to collect some information. Then using ajax, I pass msg to the controller function save(). The problem arises when I alert the variable s on the success part. It prompts the raw HTML of the add_experiment_form rather than the $message from the save() function.
The thing is when the I change the button's href to just 'builder', the whole system is working properly, meaning the success function alerts the right message, not the whole html code.
use echo json_encode($message); then response on success
var = $.parseJSON($data);
alert (json)

Categories