Ajax to controller function(codeigniter) not working properly - javascript

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)

Related

how to pass values from ajax to controller on button click?

this is my js code which is executed on button click
$("#search_tutor").click(function(){
$("#show_tutors").hide();
var subject = $( ".subject" ).val();
var degree_level = $(".degree_level").val();
var city = $(".city").val();
console.log(subject);
console.log(degree_level);
console.log(city);
$.ajax({
url:"<?php echo base_url(); ?>public_controller/search_tutor_jquery",
method:"post",
data:{subject: subject, degree_level : degree_level, city : city},
success:function(data){
$('#search_results').html(data);
}
});
});
and this is controller function
public function search_tutor_jquery(){
$subject = strtolower($this->input->post('subject'));
$degree_level = strtolower($this->input->post('degree_level'));
$city = strtolower($this->input->post('city'));
echo $subject; //prints nothing
$data['filtered_tutors'] = $this->public_model->search($subject,$degree_level,$city);
$this->load->view('public/search_results',$data);
}
values are being logged in console but i cannot receive values in controller. can somebody help me out?
thanks in advance
What do you mean by
$('#search_results').load("<?php echo base_url('public_controller/search_tutor_jquery') ?>");
Try
$('#search_results').html(data);
Read about load() function here. It sends a new empty request and load that data to your element. It doesn't load the response.
Have you tried using
$_POST['subject']
instead of
$this->input->post('subject')
?

How can I display data returned from a PHP function when a HTML button is pressed

I want to display in my page the fixtures generated from the PHP function but only when I press the "Generate Fixtures" button. I know that AJAX should be used but I can't pass the data from the function to the div in my HTML page.
PHP code
$teams = array("FC FCSB", "AFC Astra Giurgiu", "FC Dinamo 1948", "FC Viitorul 2009", "CSM Politehnica Iasi", "Universitatea Craiova", "FC Botosani", "CFR 1907 Cluj");
$fixPair = new Fixture($teams);
$schedule = $fixPair->getSchedule();
$i = 1;
foreach ($schedule as $rounds) {
echo "<h5> Etapa " . $i . " </h5>";
foreach ($rounds as $game) {
echo "{$game[0]} vs {$game[1]}<br>";
}
echo "<br>";
$i++;
}
echo "<hr>";
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
document.getElementById("demo").innerHTML = "Fixtures should be displayed here";
//alert("action performed successfully");
});
});
});
<script
src="https://code.jquery.com/jquery-3.4.1.min.js">
</script>
<input type="submit" class="button" name="insert" value="GENERATE FIXTURES" />
<div id="demo"></div>
Update your event handler as:
$('.button').click(function(e){
// Prevent form submit
e.preventDefault();
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// response variable stores all data received from ajax.php script
// As you use jquery - you can select
// element by id with $("#id") selector
$("#demo").html(response);
});
});

How to fetch data from mySQL and view in Modal

I am trying to show some records from my table columns named tid and ketprob by showing Modal when clicking on a link. The modal and query looks fine (checked by echoing last_query), but the modal is showing no data... Please help me :(
JS Code:
$('#showdata').on('click', '.item-info', function(){
var tid = $(this).attr('data');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>repeatproblem/infoReprob',
data: {tid:tid},
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<p>'+data[i].tid+'</p>'+
'<p>'+data[i].ketprob+'</p>';
}
$('#infoModal').modal('show');
$('#view_errorcode').html(html);
},
error: function(){
alert('Gagal Info Kode Error!');
}
});
});
My Controller:
public function infoReprob(){
$result = $this->m->infoReprob();
echo json_encode($result);
}
My Model:
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}
You are using return $query->row(); syntax in your model if this condition is true: $query->num_rows() > 0, so that means your model will return the object representation of the first row of the query and the $result variable in your controller below will be an object with two properties: tid and ketprob
public function infoReprob(){
$result = $this->m->infoReprob();
echo json_encode($result);
}
Now have a look at your ajax call success callback function
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<p>'+data[i].tid+'</p>'+
'<p>'+data[i].ketprob+'</p>';
}
$('#infoModal').modal('show');
$('#view_errorcode').html(html);
}
Since your controller above uses echo json_encode($result); syntax, your ajax call will return the json representation of $result variable and the data variable in your success callback function above will be like below
{ "tid": "1", "ketprob": "abc" }
The problem is, data.length in your ajax success callback function will be undefined because data isn't an array, so the for loop won't be executed and html will be an empty string, see this jsfiddle. That's why your modal is showing no data.
To fix the problem, I'd suggest changing your model code as below
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
return $query->result();
}
By using return $query->result(); syntax, your model will always return an array of object. As the result, your ajax call will return a json like this
[ { "tid": "1", "ketprob": "abc" } ]
which is a json array, so data.length in your ajax success callback function won't be undefined and your modal will show the data. See this jsfiddle, you'll see that the html variable is not empty.
I guess you should use echo $query->row(); instead of return $query->row();.
Solved by changing return $query->row(); to return $query->result();
Going to learn about this. Or can anybody tell about the different.. Thanks
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}

Ajax won't call Codeigniter controlllers's method

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

PHP is not reloaded automatically after processing

Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}

Categories