Managing AJAX call with Zend Framework - php

I am trying to integrate an AJAX search function but I am having trouble getting the Zend Framework portion right. I have the following Controller and Action.
class IndexController extends Zend_Controller_Action
{
public function indexSearchAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()->isPost()) {
$search = new Model_Index();
$this->_helper->json($search->indexSearch());
$this->view->indexSearch = $result;
}
} else {
//regular controller logic goes here
echo "regular controller";
}
}
Copy of my Ajax call is as follows:
$.ajax({
type: "POST",
url: "/index/index-search/format/json",
data: dataString,
dataType: "json",
cache: false,
success: function(html)
{
I just want the model to return a simple message to ensure that it is working up to this point. with that said, here is a copy of my function in the model:
public function indexSearch()
{
$testMessage = "this was returned via ajax";
return $testMessage;
}
Code that triggers the Ajax call:
$(document).ready(function(){
$(".search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{
}
else
{
$.ajax({
type: "POST",
url: "/index/index-search/format/json",
data: dataString,
dataType: "json",
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}
return false;
});
});
I dont know what I am missing, this is my first attempt to getting AJAX calls to work in ZF2 and its not working out.
Any help would be greatly appreciated! cheers!

The issue was that I was returning html when I was expecting json... I've since changed this:
here is the controller action:
public function indexSearchAction()
{
$this->_helper->layout('homelayout')->disableLayout();
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()->isPost()) {
$q=$_POST['searchword'];
$indexSearch = new Model_Index();
$result = $indexSearch ->indexSearch ($q);
$this->view->indexSearch = $result;
}
} else {
//regular controller logic goes here
}
}
jQuery Ajax handling code:
$(document).ready(function(){
$(".search").keyup(function() {
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox==''){
$("#display").hide();
} else
{
$.ajax({
type: "POST",
url: "/user/user-search/",
data: dataString,
cache: false,
success: function(html)
{ $("#display").html(html).show(); }
});
}return false;
});
});
jQuery(function($){
$("#searchbox").Watermark("Search");
});
Model_index function indexSearch() script:
public function indexSearch($q)
{
$select = $this->select()
->from($this)
->where('username LIKE ?', '%' . $q . '%');
$row = $this->fetchAll($select);
return $row;
}
Here is the input box element for users to search with:
<input type="text" class="rounded search" id="searchbox" /><br />
<div id="display">
</div>
view script (index-search.phtml) which displays the contents in the div:
<div class="display_box" align="left">
<ul class="index-list">
<?php echo $this->partialLoop('user/search-dropdown.phtml', $this->indexSearch);?>
</ul>
and last but not least, the view script that is mentioned in the partial loop above that iterates through the returns contents of the database and into a format that can be displayed within the dropdown. below is search-dropdown.phtml:
<li class="user-list-item" >
<div class="search-list-item-container" >
<?php
$validator = new Zend_Validate_File_Exists();
$validator->addDirectory('users/');
if ($validator->isValid('/' . $this->username . '/' . $this->username . '.jpg')) { ?>
<div class="search-list-item-picture">
<img class='search-pic' src="..\users\<?=$this->username ?>\<?=$this->username ?>.jpg?t=<?=time(); ?>">
</div>
<?php } else { ?>
<div class="search-list-item-picture">
<img class='search-pic' src="..\skins\blues\images\f1.png">
</div>
<?php }?>
<div class="search-list-item-name">
<?php echo $this->username; ?>
</div>
</div>
The end result is as follows:
thanks to everyone who assisted here! MUCH APPRECIATED

Most likely it is because of this line
$this->_helper->viewRenderer->setNoRender(true);
Followed by your attempt to use a view with this line
$this->view->indexSearch = $result;
If you're going to turn your views off, then you'll need to echo out your content. So something like echo $result;
On top of that, your ajax function is expecting JSON data to be returned, but you're actually returning plain text/html. If you know that you're ultimately going to be returning/echoing json, then during your testing, you can simply comment out the line dataType: "json", until you are done with your initial testing, and then add it back. If you are not going to be using json at all, simply remove that line.
See this simple JSFiddle example

Related

How to load content on click in yii2 framework?

I'm working on yii2 project and we need to load blocks with ajax on click.
I wrote ajax part that works correctly but im stuck with javascript. My mentor says I should use .append but I cant find way to link it somehow with controller action.
php:
public function actionGetProjects() {
$post = Yii::$app->request->post();
$projects = Project::find()->orderBy('created_at DESC')->limit(15)->offset($post['page']*15)->all();
if (count($projects)>0) {
$this->return['code'] = 200;
$this->return['html'] = $this->renderPartial('_projects', [
'projects' => $projects
]);
} else {
$this->return['code'] = 404;
}
return json_encode($this->return);
}
UPD:
HTML
<div class="projects">
<div class="pageHeader">My Projects</div>
<?php foreach ($projects as $project) {?>
<a href="project/<?=$project->id?>" class="project-block">
<img src="<?=$project->projectImages[0] ? '/img/products/'.$project->projectImages[0]->image:''?>">
<div class="project-title"><?=$project->name?></div>
<div class="project-address"><?=$project->address?></div>
<div class="project-readmore">Read more</div>
</a>
<?php } ?>
<a class="projects-load-btn" href="#">Еще</a>
</div>
New JS:
$(".projects-load-btn").on("click", function(e) {
event.preventDefault();
var id = $(this).data("id") || 0;
$.ajax({
type: 'POST',
url: '/ajax/get-projects',
data: { id: id },
dataType: "json",
success: function (data) {
if(data.code == 200){
$('.projects').addClass('test');
$('.projects').html('');
$('.projects').append(data);
}
},
errors: function (errors) {
console.log(errors);
}
});
});
Do you have urlManager component configured with enablePrettyUrl set to true in your config file?
If so, yii2 uses the following default routing template: <controller>/<action>
In you case this would result in /ajax/get-projects url.
The complete JavaScript code would look something like this:
$(".projects-load-btn").on("click", function(e) {
e.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "/ajax/get-projects",
data: { id: id }
}).done(function (data) {
$(".projects").append(data);
});
});
If I remember correctly you should not send the action as a variable through POST.
It depends on how routing was set in your Yii2 app, thus I'm only guessing:
An ajax call:
$.post("Ajax/getProjects", {id:id}, function(data) { ... });
Appending something in DOM:
$(".projects").append(jsonResponse.html);
Guessing this is school work, thus not giving the whole solution...

Stopping ajax code from running based on result from database

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.');
});
}

Get a single row from the database using AJAX in CodeIgniter?

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.

Unable to retrieve variables from ajax post in codeigniter

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

Using jQuery JSON in CodeIgniter

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

Categories