How to load content on click in yii2 framework? - php

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...

Related

Load a data from a page to another page using jquery ajax

I have two pages, index.php and block1.php
I wanted to load a data from block1.php to a div #details in index.php
here's my code
index.php
<div id="pop_box">
<div class="close"><span id="close">×</span></div>
<div id="block"></div>
<div id="details"></div>
</div>
block1.php
<script>
$(document).ready(function() {
var lnk;
$('[href]').click(function() {
lnk = '';
lnk = $(this).attr('href');
if (lnk.charAt(1) == "b") {
var lot = lnk;
$.ajax({
url: "2dmap_func.php",
method: "POST",
dataType: "text",
data: {
lot: lot
},
success: function(data) {
//alert(data);
$('index.php #pop_box #details').load(data);
}
});
}
});
});
</script>
as you can see I want to load the data from block1.php to index.php's div#details and this code doesn't work.
$('index.php #pop_box #details').load(data);
In you index.php add following line:
<?php include_once 'block1.php' ?>
In your block1.php change following line:
$('index.php #pop_box #details').load(data);
to
$('#details').html(data); // if data is valid html

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

Ajax POST to Cakephp Controller always give array() result

i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});

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.

Managing AJAX call with Zend Framework

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

Categories