dimanche 28 juin 2015

Ajax pass values from view to controller

so I'm trying to pass some values from my view to the controller, the controller gets a list and returns it.

when I try to get the values from my textboxes etc. they are all undefined... not sure what exactly I'm doing wrong here. pretty new to javascript..

here's the js code

<script type="text/javascript">
$(document).ready(function () {
    $("#getFreeApartements").on('click', function () {

        var amounta = $('#amounta').val();
        var amountc = $('#amountc').val();
        var amountan = $('#animals').val();
        var arr = $('#arrival').val();
        var dep = $('#departure').val();
        var atype = $('#atype').val();


        $.ajax({
            type: 'GET',
            data: { 'amountp': amounta, 'amountc': amountc, 'amountanimals': amountan, 'arrival': arr, 'departure': dep, 'apartmentType': atype },
            url: '@Url.Action("GetFreeApartements", "Bookings")',
            success: function (result) {
                $('freeAp').html(result);
            }
        });
        alert(amounta); // --> return undefined

    });
});

textboxinput field

    <div class="form-group">
        @Html.LabelFor(model => model.Adult, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10" id="amountp" name="amountp">
            @Html.EditorFor(model => model.Adult, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Adult, "", new { @class = "text-danger" })
        </div>
    </div>

controller:

        public ActionResult GetFreeApartements(int ap, int ac, int aa, DateTime arr, DateTime dep, ApartmentType type)
    {
 //do some stuff with received values here...
        var freeApartements = db.Apartments.ToList();
        return Json(freeApartements, JsonRequestBehavior.AllowGet);

    }

I also tried serializeArray without any success... I'm not getting any errors in the explorer console.. the function gets called, but values are null.. --> undefined should be the error.

any ideas?

Joomla Ajax Request Error

I got following error

Method get_slotsAjax does not exist

my call in healper file

 xmlhttp.open("GET","?option=com_ajax&module=quickcontact&method=get_slots&format=json",true);

my function call

public function get_slots()
{
 ....
}

Went by this documentation.

What am I Missing?

ajax checkbox filtering in codeigniter

I try to filter data in my view using select box. I'm using codeigniter and I want to filter it using ajax. I already test the code and look at the console, and ajax post return result. The problem is, i don't know how to display the result in my view. I mean, how i suppose to write in 'success: function(){}'

this is my ajax

  <script>
$(document).ready(function() {
$("#selectBerdasar").change(function() {
    var key = $(this).val();
    console.log(key);
    var postdata = {key: key};
    var url = '<?php echo site_url('produk/filter/GetFilterJson');?>';
    $.post(url, postdata, function(result) {
        console.log(result);
        if (result) {
            var obj = JSON.parse(result);
            $('col-item').empty();
            $.each(obj, function(key, line) {

             });
        } else {

        }
    });
});

});

this is my view

<div class="row">

  <div class="col-md-4 pull-right">
    <select class="form-control" id="selectBerdasar">
     <!--  <option>Produk Terbaru</option>
      <option>Produk Terpopuler</option> -->
      <option value="termahal">Harga Termahal</option>
      <option value="termurah">Harga Termurah</option>
      <option value="alfabet">Alfabet A-Z</option>
    </select>
  </div>
</div>


  <div class="row">
    <?php foreach ($produk as $data) {?>
  <div class="col-xs-6 col-sm-4 col-md-4">
    <div class="col-item">
<a href="<?php echo base_url('produk/item/detail/' . $data['id_produk']);?>">
<div class="photo">
    <img src="<?php echo base_url();?>asset/user/img/produk/<?php echo $data['gambar'];?>" class="img-responsive" alt="" />
</div>
<div class="info">
    <div class="row">
        <div class="price col-md-12">
        <h5><?php echo $data['nama_produk'];?></h5>
        <h5 class="price-text-color">Rp.<?=number_format($data['harga_produk'], 0, ',', '.')?></h5>
    </div>

</div>
    <div class="clearfix">
    </div>
</div>
</a>
</div>
  </div>
   <?php }

?>

 </div>

I just don't know how to display the result in my view.

Google Maps v3 API: use first user location to center the map

I am building a Google Maps based web app on which I plot a moving dot of the user location. I am fetching continuously the user location from a server and would like to use the current user location when loading the map to center the window around it, meaning, when the user loads the site, the map will be centered around the first lat/long fetched from the server but enable the user to pan the map afterwards without re-centering it around where the user is. I was able to keep the map centered constantly around the user location but can't figure out how to use the first fetched location to center the map during initialization. My code is below, any help would be greatly appreciated. Thanks!

 <script>

          var locations = [
                ['location a', 37.771678, -122.469357],
                ['location b', 37.768557, -122.438458],
                ['location c', 37.755121, -122.438973],
                 ['location d', 37.786127, -122.433223]
              ];
          var map;
          var i;
          var marker; 
          var google_lat = 37.722066;
          var google_long = -122.478541;
          var myLatlng = new google.maps.LatLng(google_lat, google_long);
          var image_dot = new google.maps.MarkerImage(
              'images/red_dot.png',
              null, // size
              null, // origin
              new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
              new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
          );

          function initialize() {

            var mapOptions = {
              zoom: 12,
              center: myLatlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            setMarkers(map, locations);
          } //initialize();


          function setMarkers(map, locations) {

              for (var i = 0; i < locations.length; i++) {
              var beach = locations[i];
              var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
              marker = new google.maps.Marker({
                position: myLatLng1,
                icon: image_dot,
                map: map
              });
            }
          }

          google.maps.event.addDomListener(window, 'load', initialize);

    </script>

    <script type="text/javascript">

            var Tdata;
             var image = new google.maps.MarkerImage(
              'images/bluedot_retina.png',
              null, // size
              null, // origin
              new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
              new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
           );
            var userMarker = new google.maps.Marker({icon: image});

            $.ajax({
                    method : "GET",
                    url: "get_location.php",
                    success : function(data){
                        Tdata=JSON.parse(data);
                        myFunction();
                    }
            });

            function myFunction(){
                    var interval = setInterval(function() { 
                        $.get("get_location.php", function(Tdata) {
                            var JsonObject= JSON.parse(Tdata);
                            google_lat = JsonObject.lat;
                            google_long = JsonObject.long;
                            myLatlng = new google.maps.LatLng(google_lat, google_long);
                            userMarker.setPosition(myLatlng);
                            userMarker.setMap(map);
                            //map.setCenter(myLatlng); --> this is not what I want since it will always keep the map centerd around the user 
                        });
                    }, 1000);
            }

     </script>

Close image on modelpopup doesn't work after postback

I have ajax modelpopup extender in my webform with CancelControlID set to an image imgClose. When I click on imgClose after popup has been displayed it closes the popup. But if I click on any controls or select some controls that require postback, clicking the image wouldn't do nothing at all. Previously I had a button as CancelControlID for same modelpopup. It also had the same problem. I got around it with OnClick="btnClose_Click"codebehind method and hiding modelpopup.

For the imgClose I tried using client-side method but it doesn't work. Any ideas?

Here's my modelpopup extender image control and javascript

<img id="imgClose" alt="Close" src="image/close-button-red.png" runat="server" onclick="closeModelPopup()" />


<ajx:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnTest"
                BackgroundCssClass="modalBackground" PopupControlID="divPreview" DropShadow="true"
                CancelControlID="imgClose">


<script type="text/javascript">
    function closeModelPopUp() {
        $find('ModalPopupExtender1').hide();           
    }
</script>

Simple AJAX Note Taking App to record same notes written through out every / any page

I want to use the Simple AJAX Note Taking App for my website but it looks like they have coded it for the user to create notes PER WEBPAGE (I'll explain how I worked this out later) which isn't exactly what I want.

I want users to be able to create their own notes using this script but for their entire session surfing my website. So in other words, it doesn't matter what webpage they are on, the notes they they've written down is recorded / saved 'globally' and they can refer to those SAME notes that they've written down regardless what page they're on.

***Just so you know, I intend to use this script in a global php include for all my pages. The PHP include looks like this: **

<?php include( $_SERVER['DOCUMENT_ROOT'] . '/test/inc/noteapp.php' ); ?>

(Please understand that I suck a php and javascript)

So to show you how their demo works (I've uploaded the demo onto my domain name): Click here PAGE 1 ... Now quickly write down some notes on that page and then go to my other page that also uses this script PAGE 2

You'll notice that the notes that you've written down on PAGE 1 aren't showing up on PAGE 2.

I want the notes that you've written down on PAGE 1 to show up on PAGE 2, PAGE 3, page 4 (doesn't matter what directories they're on) etc etc ...

Let me show you their code and explain to you how it works:

Here is their PHP code for the script:

<?php

$note_name = 'note.txt';
$uniqueNotePerIP = true;

if($uniqueNotePerIP){

// Use the user's IP as the name of the note.
// This is useful when you have many people
// using the app simultaneously.

if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $note_name = 'notes/'.md5($_SERVER['HTTP_X_FORWARDED_FOR']).'.txt';
}
else{
    $note_name = 'notes/'.md5($_SERVER['REMOTE_ADDR']).'.txt';
}
}


if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
// This is an AJAX request

if(isset($_POST['note'])){
    // Write the file to disk
    file_put_contents($note_name, $_POST['note']);
    echo '{"saved":1}';
}

exit;
}

$note_content = '

            Write your note here.
';

if( file_exists($note_name) ){
$note_content = htmlspecialchars( file_get_contents($note_name) );
}

?>

In the PHP code above, notice the directory notes/ ... this is the directory where the users written notes will be saved (in a txt file). Now as mentioned above, I will be putting this php code into a php include which will be put on every page of my website. My website will have many directories / sub directories which means that this notes/ directory (which I want in the root of my domain) needs to be pathed correctly so that it always finds the notes/ directory in the root.

How would I path it?

That's my first problem ... now moving onto the second problem (not a crucial issue) - take a look at their javascript:

$(function(){

var note = $('#note');

var saveTimer,
    lineHeight = parseInt(note.css('line-height')),
    minHeight = parseInt(note.css('min-height')),
    lastHeight = minHeight,
    newHeight = 0,
    newLines = 0;

var countLinesRegex = new RegExp('\n','g');

// The input event is triggered on key press-es,
// cut/paste and even on undo/redo.

note.on('input',function(e){

    // Clearing the timeout prevents
    // saving on every key press
    clearTimeout(saveTimer);
    saveTimer = setTimeout(ajaxSaveNote, 2000);

    // Count the number of new lines
    newLines = note.val().match(countLinesRegex);

    if(!newLines){
        newLines = [];
    }

    // Increase the height of the note (if needed)
    newHeight = Math.max((newLines.length + 1)*lineHeight, minHeight);

    // This will increase/decrease the height only once per change
    if(newHeight != lastHeight){
        note.height(newHeight);
        lastHeight = newHeight;
    }
}).trigger('input');    // This line will resize the note on page load

function ajaxSaveNote(){

    // Trigger an AJAX POST request to save the note
    $.post('index.php', { 'note' : note.val() });
}

});

Notice at the bottom of this code index.php ... I'm guessing that's the webpage that the ajax must work on? Generally I like to put most (if not all) of my javacript into a combined js file which is included on every page. So if I do that with the javascript above, then I've got a problem with index.php being index.php because a lot of my web page won't all be called index.php (eg: about.php etc) ... so is their any way to change index.php to be something else to automatically refer to the page the user is on regardless what it's called?

If this cannot possibly be done, then I suppose I'd have to put this javascript on each page (and not in my combined javascript file) and amend index.php to whatever page it's on.

I'd appreciate your help and I hope I've explained well enough.

How to get information in jquery function from the php file

Hello guys my question is how to get an db information (in my case points just a number) from the php file to the jquery ajax script so here is my jquery:

function rate_down(id) { 
    var id = id;
//submit data to php script

    var data = {
      "id": id,
    };

    $.ajax({
      type: "POST",
      url: "rating.php",
      data: data,
      success: function(response) {

      var currentValue = /* here i want to put the db number */
      var newValue = +currentValue - 1;
      $("#points_"+id).text(newValue);




      },
      error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
      } 
    });
};

And i want my raiting.php im not sure if i shoud post it becouse its usless but here is my mysql query in raiting.php:

$pic_id = (int) $_REQUEST['id'];
mysql_query = mysql_query"SELECT points FROM `photos` WHERE `id` = '$pic_id'";