want to display div on click of another div in yii2 - javascript

I am new to Yii2 i want to display list of offers at left side when i clicked on offer it should displays details on right side.
this is my tradesmanOffer view page
<?php
foreach ($model as $offer) {
?>
<div class="offer-row" data-id="<?=$offer->o_id?>">
<div class="box">
<div class="offer-col-7"> <div><b>NEW OFFER</b> from
<?php
if ($offer->c_id) {
$contractor = Contractor::getoffername($offer->c_id);
if (!empty($contractor)) {
echo $contractor->name;
}
}
?></div>
this is my .js file:
$(function () {
$(".offer-row").on("click", function (event) {
$(".offers").empty();
var tid = $(this).attr("data-id");
alert(1);
$.ajax({
url: "offer-details?t_id=" +tid,
type: "GET",
contentType: false,
cache: false,
success: function (data) {
//alert(2);
$("#ajaxdiv").html('');
$("#ajaxdiv").html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
return false;
});
});
this is my controller page as OfferController
public function actionOfferList() {
if (Yii::$app->session->get('t_id') != "") {
$model = new TradesmanOffer();
$t_id = Yii::$app->session->get('t_id');
$offers = $model->getOffers($t_id);
return $this->render('tradesmanOffer', ['model' => $offers]);
} else {
return $this->redirect('../site/index');
}
}
public function actionOfferDetails() {
$t_id= $_GET['t_id'];
$model = new TradesmanOffer();
$offer = $model->getOffers($t_id);
return $this->renderAjax('tradesmanOfferNew', ['model' => $offer]);
}
this is my another view tradesmanOfferNew:
<div> <b>NEW OFFER</b> from
<?php
if ($offer->c_id) {
$contractor = Contractor::getoffername($offer->c_id);
if (!empty($contractor)) {
echo $contractor->name;
}
}
?>
and when i clicked on any offer and if refreshed browser it should same data on page.
how i achieve this?please help
thanks in advance

Why are you using contentType: false in your ajax call? Since you're getting some HTML from your call, you should set it to html

Related

pagination automatically sending multiple requests with laravel

hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me

jQuery select2: duplicate tag getting recreated

I asked a question earlier today (jquery select2: error in getting data from php-mysql). However, I am trying to fix it and doing that now I am getting bit strange issue. I am not sure why it is happening like this.
Below is the JavaScript code.
<div class="form-group">
<label class="col-sm-4 control-label">Product Name</label>
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function(term) {
return {q: term};
},
results: function(data) {
return {results: data};
},
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
Here is the php code (fetch.php)
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
//$search='te';
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
select2 version is 3.5
Above code is able to send/receive request from database by using fetch.php.
Problem is in my database there are two records test & temp when I tag any one of them it create new tag.
It should work like this: if database have value then it won't create the new tag with same name.
Update
Tags need an id and a text. The issue you're facing is that your text doesn't match the id.
So, even if you write the same text, Select2 thinks the new text is a new option because the id don't match.
To solve your issue, you need to set the id with the same value as the text. Change the foreach of your fetch.php to the following:
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
Update:
You also need to update the variable lastResults to avoid the duplication of tags with the same text. When you bind select2, you need to change the results property of ajax to this (based on this answer:
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function(term) {
return {q: term};
},
results: function(data) {
lastResults = data.results;
return {results: data};
},
},
Note the lastResults = data.results;. Without this, the lastResults variable is always empty and, when the createSearchChoice function is executed, it will always return a new tag.
Finally it is working now. I would like to thanks #alex & #milz for their support.
Here is the full n final code. Now duplicate tags are not creating. However, i am working to add tag in database.
php/html file
<div class="form-group">
<label class="col-sm-4 control-label">Product Name</label>
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
tags: true,
placeholder: "Please enter tags",
tokenSeparators: [',', ' '],//[","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: 'json',
// type: "POST",
data: function(term,page) {
return {
term: term
};
},
results: function(data,page) {
lastResults = data;
return {results: data};
},
},
maximumSelectionSize: 3,
minimumInputLength: 3,
createSearchChoice: function(term) {
console.log($(this).attr('data'));
var text = term + (lastResults.some(function(r) {
console.log(r.text);
console.log(term);
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
Here is the php file to get the data from database.
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
//if(isset($_GET)){
$search = strip_tags(trim($_GET['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => 'No Products Found', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
It took lots of time. Almost 3 days. I hope it will save someone efforts.
Apply the changes as in the select2.min.js (v4.0.6-rc.1) code snippet below
section 1
c.on("results:select", function() {
var a = e.getHighlightedResults();
if (0 !== a.length) {
var c = b.GetData(a[0], "data");
"true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {
//custom select2 tagging
if(a.attr("aria-selected")){
c.id = c.id + 1;
}
e.trigger("select", {
data: c
})
//"true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {
// e.trigger("select", {
// data: c
// })
}
})
section 2
this.on("query", function(b) {
a.isOpen() || a.trigger("open", {}), this.dataAdapter.query(b, function(c) {
//custom select2 tagging
let searchInput = $(".select2-search__field").val();
searchInput = {results: [{id: searchInput, text: searchInput}]};
a.trigger("results:all", {
data: c,
data: searchInput,
query: b
})
})
})

how to redirect the request to specified php page by ajax call?

how to redirect the request to specified php page by ajax call, below is my code structure
index.html
<html>
<script>
function shift(str)
{
$.ajax({
url: 'destination.php',
type:'POST',
data: {q:str}
}).done(function( data) {
$("#result").html(data);
});
return false;
}
</script>
<body>
<input type='button' value='test' onclick="shift('test');">
<div id='result'></div>
</html>
destination.php
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
header('something.php');
}
else
{
echo "test";
}
?>
this is my code structure if posted string is same as then header funtion should be work else echo something, but header funstion is not working via ajax
You should specify header parameter to Location. Use the code below
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
header('Location:something.php');
}
else
{
echo "test";
}
?>
Hope this helps you
Go With This
You can check the string in jquery like below..
First you must echo the variable in php page.
then,
$.ajax({
url: 'destination.php',
type:'POST',
data: {q:str}
}).done(function( data) {
if(data=="something")
{
window.location.assign("http://www.your_url.com"); //
}
});
return false;
}
You should always retrieve the response in json format and based on that decide where to redirect. use below code for your requirement.
function shift(str) {
$.ajax({
url: 'destination.php',
type: 'POST',
data: {
q: str
}
}).done(function (resp) {
var obj = jQuery.parseJSON(resp);
if (obj.status) {
$("#result").html(obj.data);
} else {
window.location..href = "YOURFILE.php";
}
});
return false;
}
Destination.php
<?php
$string=$_REQUEST['q'];
$array = array();
if($string=="something")
{
$array['status'] = false;
$array['data'] = $string;
}else {
$array['status'] = true;
$array['data'] = $string;
}
echo json_encode($array);
exit;
?>
function shift(str) {
$.ajax({
url: 'destination.php',
type: 'POST',
data: {
q: str
}
}).done(function (data) {
if (data=="something") {
window.location.href = 'something.php';
}
else {
$("#result").html(data);
}
});
return false;
}
in Destination.php
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
echo "something";
}
else
{
echo "test";
}
?>

Jquery light switch setting starting state

I'm using this setup to show if light is turned on or off:
http://www.jquery2dotnet.com/2012/11/jquery-light-switch-on-off-using-css3.html
How can i choose wich switch state to start?
As of now I have a lightvalue in my database, 1 = on 0 = off. I use sql to retrieve this value and load the appropriate light bulb.
But how would i do this with the switch? I don't have switch1 and switch2 so i can load the one i want based on lightvalue.
here is the code:
light.js
var lightVal = document.getElementById("light-bulb2");
function getLightValue(r) {
var lightValue;
$.ajax({
url: 'Database/checklight.php',
type: "POST",
data: {room: r},
success: function(data) {
data1 = JSON.parse(data);
$.each(data1, function(key, val) {
lightValue = val.light;
lightVal.style.opacity = lightValue;
});
},
async: false
});
}
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {light: val, room: room},
success: function(data) {
data2 = JSON.parse(data);
if (data2 < 1) {
alert("Not Updated");
}
},
async: false
});
}
light.php
<div id="temptre">
<div id="light-bulb" class="off ui-draggable" >
<div id="light-bulb2" style="opacity: 0">
<script src="JS/light.js">
</script>
</div></div>
<div class="cube-switch">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
</div>
<script>
getLightValue(<?php echo $_SESSION['sess_room']; ?>);
$('.cube-switch .switch').click(function() {
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({'opacity': '0'});
updateLight(0, <?php echo $_SESSION['sess_room']; ?>);
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({'opacity': '1'});
updateLight(1, <?php echo $_SESSION['sess_room']; ?>);
}
});
</script>
If you want to make switch work, then you need to trigger the click event, so that it can be switch on and off (based on value).
// call(trigger) click event on success
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {
light: val,
room: room
},
success: function (data) {
data2 = JSON.parse(data);
if (data == 1) {
$('.cube-switch .switch').trigger('click', [{
forceStart: true
}]);
} else {
$('.cube-switch .switch').trigger('click', [{
forceStart: false
}]);
}
},
async: false
});
}
// change your click event to handle the passed argument
$('.cube-switch .switch').click(function (e, data) {
if (typeof data !== 'undefined') {
if (data.forceStart) {
// remove the active class, so that it can add the active class later to match switch on
$('.cube-switch').removeClass('active');
} else {
$('.cube-switch').addClass('active')
}
}
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({
'opacity': '0'
});
updateLight(0, <? php echo $_SESSION['sess_room']; ?> );
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({
'opacity': '1'
});
updateLight(1, <? php echo $_SESSION['sess_room']; ?> );
}
});
JSFIDDLE: http://jsfiddle.net/4rkQZ/152/
I'm not very good with php, but give div.cube-switch a class of 'active' if it's on, and remove the inline opacity style (tidy up the php by all means!)
<div href="" class="cube-switch <?php if ($on) { echo ' active'; } ?>">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
<div id="light-bulb" class="off ui-draggable">
<div id="light-bulb2" <?php if (!$on) { echo 'style="opacity:0"'; } ?>></div>
</div>

Ajax search - Laravel

I am trying to create a live search using jquery, ajax and laravel. I also use pjax on the same page, this might be an issue?. Quite simply it should query the database and filter through results as they type.
When using Ajax type:POST I am getting 500 errors in my console. I get zero errors using GET but instead of returning in #foreach it will a full page view (this might be because of pjax).
Where am I going wrong?
Route:
Route::post('retailers/{search}', array(
'as' => 'search-retailers', 'uses' => 'RetailersController#search'));
Controller:
public function search($keyword) {
if(isset($keyword)) {
$data = array('store_listings' => RetailersListings::search($keyword));
return $data;
} else {
return "no results";
}
}
Model:
public static function search($keyword)
{
$finder = DB::table('retailers_listings')
->Where('city', 'LIKE', "%{$keyword}%")
->orWhere('country', 'LIKE', "{$keyword}")
->orderBy('country', 'asc')
->get();
return $finder;
}
View (store.blade.php):
<div id="flash"></div> //loading
<div id="live"> // hide content
<div id="searchword"><span class="searchword"></span></div> //search word
<table class="table">
<tbody>
#foreach($store_listings as $store)
<tr>
<td></td> //echo out all fields eg: {{ $store->name }}
</tr>
#endforeach
</tbody>
</table>
</div>
Form:
<form method="get" action="">
<input type="text" class="search-retailers" id="search" name="search">
</form>
Ajax and JS:
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
var dataString = 'keyword='+ keyword;
if(keyword=='') {
} else {
$.ajax({
type: "GET",
url: "{{ URL::route('search-retailers') }}",
data: dataString,
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
Additional, Here is my controller for pjax, It is important to note I am using the view store.blade.php foreach in for the search and for this store listing.
public function stores($city)
{
$this->layout->header = $city;
$content = View::make('retailers.stores', with(new RetailersService())->RetailersData())
->with('header', $this->layout->header)
->with('store_listings', RetailersListings::stores($city));
if (Request::header('X-PJAX')) {
return $content;
} else {
$this->layout->content = $content;
}
}
Your route is Route::post('retailers/{search}', [...]) and there you go. You pass data to your ajax-call. In GET you get something like url?key=value but using POST the data are added to the request body not to the url.
Knowing this your route is no longer valid since it only looks up for retailers/{search} and not for retailers only (which is the url POST is using).
Well maybe it could help somebody.
As a first problem you are defining the route as POST and then in the ajax request the type GET so it would not work
Also when making POST request Laravel has the csrf check so in order to work, provide it. The js function will be like
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
if(keyword=='') {
} else {
$.ajax({
type: "post",
url: "{{ URL::route('search-retailers') }}",
data: {
'keyword': keywork,
'_token': '{{ csrf_token() }}';
},
dataType: 'html',
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
And you can test your PHP search method doing separate tests for it.

Categories