I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.
Related
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 need to send id and get database values according to the id without page refresh.and display data in my view,
here is my view,
<div>
Click on me
</div>
<script type="text/javascript">
function getSummary(id)
{
$.ajax({
type: "POST",
url: '<?php echo site_url('ajax_controller/getBranchDetails'); ?>',
cache:false,
data: "id=" + id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
controller
public function getBranchDetails(){
$b_id = $this->input->post('branch_id');
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
//echo json_encode(array('data'=>$data));
}
I need to display $data['results'] in my view
model
<?php
class Ajax_model extends CI_model{
function getRecords($id)
{
$this->load->database();
$query = $this->db->query("SELECT * FROM companydetails WHERE id='$id'");
return $query->result();
}
}
Try this code ,It is working .
<script type="text/javascript">
function getSummary(id)
{
$.post("<?php echo site_url('ajax_controller/getBranchDetails'); ?>",
{branch_id:id},function(data,status){
$('#summary').html(data);
});
}
</script>
Note : Check whether you have included jquery.min.js . If not mention the below code in view part header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
Try this instead:
<script type="text/javascript">
function getSummary(id) {
$.ajax({
type: 'POST',
url: "<?php echo site_url('ajax_controller/getBranchDetails'); ?>", // <-- properly quote this line
cache: false,
data: {branch_id: id}, // <-- provide the branch_id so it will be used as $_POST['branch_id']
dataType: 'JSON', // <-- add json datatype
success: function(data) {
// if you need to present this in a html table,
// likely, you need to use $.each() and build the markup using the json response
$('#summary').html(data);
}
});
}
</script>
Model: (Don't directly use variables inside the query string)
$sql = 'SELECT * FROM companydetails WHERE id = ?';
$query = $this->db->query($sql, array($id));
Controller:
public function getBranchDetails()
{
$b_id = $this->input->post('branch_id', true);
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
echo json_encode($data); // <-- uncomment
}
I have the following on com_show/views/tmpl/default.php:
function CategoryItems(){
$("button").click(function() {
var ids = this.id;
var u = "<?php echo JURI::root();?>index.php?option=com_show&controller=names&task=showName&id=" + ids;
jQuery.ajax({
type:'GET',
url: u,
data: { id: ids },
success: function(data) { }
}); //end of ajax
});
return false;
}
And on controller I have the following:
function showName(){
$myid = JRequest::getVar('id', 'no value');
return $myid;
}
The problem is on ajax part. When I try getting the returned value from function 'showName()' in controller 'name', Am always getting 'no value' instead of the id.
Kindly assist,
I am new to using ajax and I am having trouble with posting variables and accessing those variables in my controllers.
Here is the Controller Code
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
/* $this->load->model('product_model');
$q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
$data = $this->product_model->get_record_specific($q);
echo json_encode($data[0]->quantity);
*/
echo $product;
}
function index()
{
$this->load->view('autocomplete_view');
}
}
If I change the echo to a string inside single quotes like this 'Hello World', it will return the hello world back to the view correctly. But it will not do the same if I try it as it currently is. Also if I use echo json_encode($product); it then returns false.
Here is view code with ajax.
$( document ).ready(function () {
// set an on click on the button
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: 'productName',
success: function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<h1> Get Data from Server over Ajax </h1>
<br/>
<button id="button">
Get posted varialbe
</button>
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
//echo $product;
//in ajax dataType is json -here You have to return json data
echo json_encode($product);
}
...
}
//javascript file
var productName = $('#productName).val();//get value of product name from form
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: {productName:productName},//You have to send some data from form
success: function(msg){
alert(msg);
}
});
My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.