insert a jquery function to a page in yii - php

i have to use a jquery function in yii. i have a code like that and add it in view page.
<script type="text/javascript">
jQuery(function() {
jQuery( "#item" ).draggable();
jQuery( "#droppable" ).droppable({
drop: function( event, ui ) {
var $self = jQuery(this);
var dropOffset = $self.offset();
var itemOffset = ui.offset;
var itemRelativePosition = { left: (itemOffset.left - dropOffset.left), top: (itemOffset.top - dropOffset.top) };
console.log(itemRelativePosition);
jQuery('#layout').val( '{ left: '+itemRelativePosition.left+', top: '+itemRelativePosition.top+'}' );
}
});
});
</script>
but i cant know why it does not work.is there any other trick to use this code.

You need to register the jquery code
<?php
// Javascript
Yii::app()->clientScript->registerScript('register_script_name', "
var partner_only = '".CHTML::activeId($model,'partner_only')."';
jQuery(function() {
jQuery( '#item' ).draggable();
jQuery( '#droppable' ).droppable({
drop: function( event, ui ) {
var $self = jQuery(this);
var dropOffset = $self.offset();
var itemOffset = ui.offset;
var itemRelativePosition = {
left: (itemOffset.left - dropOffset.left), top: (itemOffset.top - dropOffset.top)
};
console.log(itemRelativePosition);
jQuery('#layout').val( '{ left: '+itemRelativePosition.left+', top: '+itemRelativePosition.top+'}' );
}
});
});
", CClientScript::POS_READY);
?>
Hope this answers your question

Add next code to your view file:
Yii::app()->getClientScript()->registerScriptFile('//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
Yii::app()->getClientScript()->registerScriptFile('//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js');

Related

GMaps centering not working

I'm working on an app with few points of coordinates but I can't get the center points. Can anyone help? this is my code:
<div id="mymap"></div>
<script type="text/javascript">
function initMap() {
var locations = <?php print_r(json_encode($hospitalmap)) ?>;
var mymap = new GMaps({
el: '#mymap',
lat: mymap.getCenter().lat(),
lng: mymap.getCenter().lng(),
zoom:13
});
//gMap.setCenter(new google.maps.LatLng(-6.2598513, 106.6160752));
$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.HospitalLatitude,
lng: value.HospitalLongitude,
title: value.HospitalName,
click: function(e) {
alert('This is '+value.HospitalName+'.');
}
});
});
}
</script>
PS it works if i sent the center manually
EDIT: I tried to change it with rohit's guide to this
var bounds = new google.maps.LatLngBounds();
var mymap = new GMaps({
el: '#mymap',
zoom:13
});
$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.HospitalLatitude,
lng: value.HospitalLongitude,
title: value.HospitalName,
click: function(e) {
alert('This is '+value.HospitalName+'.');
}
});
bounds.extend(marker.position);
}
);map.fitBounds(bounds);
}
</script>
still not working at the moment. Please help!
Heres the data sample:
var locations = [
{"HospitalID":2,"HospitalName":"RS Bethsaida","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Curug Sangereng, Kelapa Dua, Tangerang, Banten","HospitalPhone":"02183929302","HospitalEmail":"bethsaida#gmail.com","HospitalLatitude":"-6.254463","HospitalLongitude":"106.622776","Balance":"5250007","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"},
{"HospitalID":3,"HospitalName":"RS Mayapada","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Modernland, Jl. Honoris Raya Kav. 6, Kelapa Indah, Klp. Indah, Kec. Tangerang, Kota Tangerang, Banten","HospitalPhone":"02100001920","HospitalEmail":"rs#mayapada.com","HospitalLatitude":"-6.204981","HospitalLongitude":"106.641538","Balance":"0","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"}];
Now the below is a working sample, you can replace the locations by your PHP code, and hope this works well.
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="https://maps.google.com/maps/api/js?key=AIzaSyD95RyzZ5IEngrkYckzqRMAwyCZ7-eezMw"></script>
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.js"></script>
<div id="map">dfas</div>
<style>
#map {
width: 98%;
height: 600px;
margin-bottom:50px;
margin-left:15px;
}
</style>
<script type='text/javascript'>
function initMap() {
var locations = [
{"HospitalID":2,"HospitalName":"RS Bethsaida","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Curug Sangereng, Kelapa Dua, Tangerang, Banten","HospitalPhone":"02183929302","HospitalEmail":"bethsaida#gmail.com","HospitalLatitude":"-6.254463","HospitalLongitude":"106.622776","Balance":"5250007","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"},
{"HospitalID":3,"HospitalName":"RS Mayapada","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Modernland, Jl. Honoris Raya Kav. 6, Kelapa Indah, Klp. Indah, Kec. Tangerang, Kota Tangerang, Banten","HospitalPhone":"02100001920","HospitalEmail":"rs#mayapada.com","HospitalLatitude":"-6.204981","HospitalLongitude":"106.641538","Balance":"0","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"}];
var map;
var bounds = new google.maps.LatLngBounds();
map = new GMaps({
el: '#map',
lat: -6.254463,
lng: 106.622776
});
$.each( locations, function( index, value ){
map.addMarker({
lat: parseFloat(value.HospitalLatitude),
lng: parseFloat(value.HospitalLongitude),
title: value.HospitalName,
click: function(e) {
alert('This is '+value.HospitalName+'.');
}
});
bounds.extend({lat: parseFloat(value.HospitalLatitude), lng: parseFloat(value.HospitalLongitude)});
});
map.fitBounds(bounds);
}
initMap();
</script>
Thanks

using the $.post with php&jquery

Ok, Im trying to make a draggable CMS system, now Im stuck on the next problem.
When Im done dragging my 'div' I want to save my new left and top (x and y) variables in my MySQL database using PhP.
I get my left and top variables by the next line of codes:
$(function() {
$( "#3" ).draggable({
stop: function () {
$.post("upload.php", {
left: this.getBoundingClientRect().left,
top: this.getBoundingClientRect().top
})
},
containment: "#containment-wrapper",
scroll: false
});
my upload.php is:
<?
mysql_query("UPDATE nvt SET left='". $_POST['left'] ."'")or die(mysql_error());
mysql_query("UPDATE nvt SET top='". $_POST['top'] ."'")or die(mysql_error());
header("Location: inlogged");
?>
When I'm done dragging my div there is just no reaction?
I think you are missing }); at the end. The code should be :
$(function() {
$( "#3" ).draggable({
stop: function ( event, ui ) {
$.post("upload.php", {
left: parseInt( ui.offset.left ),
top: parseInt( ui.offset.top )
})
},
containment: "#containment-wrapper",
scroll: false
});
}); //see the change

Javascript handling multiple IDs

I'm completely new in javascript. The problem is, I have multiple textarea and div which 'echo'-ed out via PHP with ID (for example textarea_1,textarea_2...), and I wanna do something like, when the textarea is on focus, only that particular textarea which being focussed will slide down and expand.
Html
<textarea id="comment_textarea_1"></textarea>
<div id="button_block_1"><button type="submit">Submit</button><button type="submit" id="cancel_1">Cancel</button></div>
<textarea id="comment_textarea_2"></textarea>
<div id="button_block_2"><button type="submit">Submit</button><button type="submit" id="cancel_2">Cancel</button></div>
Javascript
$(document).ready(function () {
var $this = $(this);
var $textareaID = $this.attr("id").replace("comment_textarea_");
var $buttonblockID = $this.attr("id").replace("button_block_");
var $cancelID = $this.attr("id").replace("cancel_");
var $textarea = $('#'+$(textareaID));
var $button = $('#'+$(buttonblockID));
var $cancel = $('#'+$(cancelID));
$textarea.focus(function(){
$textarea.animate({"height": "85px",}, "fast" );
$button.slideDown("fast");
return false;
});
$cancel.click(function(){
$textarea.animate({"height": "18px",}, "fast" );
$button.slideUp("fast");
return false;
});
});
Thank you!
I explained it in the code. Try this.
$(document).ready(function () {
// select all the textareas which have an id starting with 'comment_textarea'
var $textareas = $("textarea[id^='comment_textarea']");
$textareas.on("focus",function(){
// now $(this) has the focused element
$(this).animate({"height": "85px",}, "fast" );
// find the button block of this div and animate it
$("div[id^='button_block']",$(this)).slideDown("fast");
});
$textareas.on("focusout",function(){
// now $(this) has the focused out element
$(this).animate({"height": "18px",}, "fast" );
// find the button block of this div and animate it
$("div[id^='button_block']",$(this)).slideUp("fast");
});
});
I believe I understand what you're attempting. Please let me know if the following is the effect you're after:
$("[id^='comment_textarea_']").on({
focus: function(){
$(this).stop().animate({ height: '85px' }, 750).next().slideDown();
},
blur: function(){
$(this).stop().animate({ height: '20px' }, 250).next().slideUp();
}
});​
Fiddle: http://jsfiddle.net/pwype/2/
I'm confused. The above answers are concentrating on using ID's... The last time I checked this is one of the main reasons we have the class attribute?
For example:
$(document).ready(function()
{
$('.comment-textarea').focus(function()
{
$(this).animate(
{
'height' : '85px'
}, 'fast');
$(this).next('.button-block').slideDown('fast');
}).blur(function()
{
$(this).animate(
{
'height' : '18px'
}, 'fast');
$(this).next('.button-block').slideUp('fast');
});
});
And the HTML:
<textarea id="comment_textarea_1" class="comment-textarea"></textarea>
<div id="button_block_1" class="button-block"><button type="submit">Submit</button><button type="submit" id="cancel_1">Cancel</button></div>
<textarea id="comment_textarea_2" class="comment-textarea"></textarea>
<div id="button_block_2" class="button-block"><button type="submit">Submit</button><button type="submit" id="cancel_2">Cancel</button></div>
And a little fiddle to show it working:
http://jsfiddle.net/ngYMh/

drag and drop with jquery and php

hy, i have a php array with the name of some images!
i list all the images use this:
$files = $_SESSION['files'];
$imgid = $_POST['id'];
if ($files){
foreach($files as $image ):
print '<li id="liupimages">'."\n";
print '<img id="'.$imgid.'" alt="'.$image.'" src="uploads/'.$image.'">'."\n";
print "</li>\n";
endforeach;
print <<<JS
<script>
$(".thumbs li a").click(function(){
var largePath = $(this).attr("href");
$('.thumbs li').removeClass('thumbac');
$(this).parent().addClass('thumbac');
$("#largeImg").hide()
.attr({ src: largePath })
.load(function() {
$(this).show();
});
return false;
});
</script>
JS;
}
i use jquery-ui to drag and drop images using this function:
$(function() {
$("#upimagesQueue").sortable({ opacity: 0.6, cursor: 'move', update: function() {
//??
}
});
});
after i drag and drop one image i want to be able to update the php array to!
how to do this?
Use ajax:
$.get("re-arrange.php", { 'myArray[]': ['file1', 'file2']} );
http://api.jquery.com/jQuery.get/
Don't use jQuery use dom-drag it's much better and more functional.
Add this code:
<script type="text/javascript" src="http://www.dynamicdrive.com/dynamicindex11/domdrag/dom-drag.js"></script>
<script type="text/javascript">
Drag.init(document.getElementById("exampleid")); //sets the id to look for to make object draggable
</script>

how to pull dynamic data from mysql to anguarJS then google map markers

I am trying to pass dynamic data from mysql then creating multiple markers on google.
Here is my html code.
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div class="map">
<div id="map" style="width: 100%;height:738px;"></div>
</div>
</div>
Here is the angularjs Script.
//Angular App Module and Controller
var investup = angular.module('mapsApp', [])
investup.controller('MapCtrl', function ($scope, $compile) {
var cities = [
{
title: 'xyz',
city : '<img src="images/xxx.jpg" />',
lat : 12.2917925,
long : 76.6704174
},
{
title: 'Add to Cart',
city : '<button class="org-btn" ng-click="cartone()" style="display:block;font-size:12px;margin:0 auto 0 auto;">Add to Cart</button>',
lat : 12.2725645,
long : 76.6705986
},
];
//Define your locations: HTML content for the info window, latitude, longitude
var popup = [
['<img src="images/xyz.jpg" />'],
['<img src="images/xyz.jpg"/>'],
];
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [iconURLPrefix + 'red-dot.png', iconURLPrefix + 'purple-dot.png']
var iconsLength = icons.length;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(12.2982778, 76.6903664),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
}
$scope.popup = popup;
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var activeInfoWindow;
var activeInfoWindow2;
var iconCounter = 0;
$scope.markers = [];
for (i = 0; i < cities.length; i++) {
var createMarker = function (info) {
var marker = new google.maps.Marker({map: $scope.map,icon: icons[iconCounter],position: new google.maps.LatLng(info.lat, info.long),popup: popup[i][0]});
google.maps.event.addListener(marker, 'click', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
var contentString = "<div><h2>" + info.city + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow = infoWindow;
});
google.maps.event.addListener(marker, 'mouseover', function() {
var contentString = "<div><h2>" + marker.popup + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow2 = infoWindow;
if(activeInfoWindow != null)
activeInfoWindow.close();
});
google.maps.event.addListener(marker, 'mouseout', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
});
$scope.markers.push(marker);
}
createMarker(cities[i]);
iconCounter++;
}
$scope.openInfoWindow = function(e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
Here is the screenshot of the result
This is the static code when i'm placing php code in cities and popup section to not showing the result.
Problem is when i don't how to call php code in angularJS. Kindly help me.
Thanks in advance.
1- You probably would need to use a framework to handle JSON serialization for you.
For the sake of simplicity you can use this library (https://github.com/mevdschee/php-crud-api), and copy api.php to the server root directory.
2- Using $http:
investup.controller('MapCtrl', function($scope, $compile, $http) {
$http.get('/api.php/cities').success(function(response) {
var cities = response.cities;
// the rest of controller function body
}).catch(handleError);
})

Categories