Affichage des articles dont le libellé est Active questions tagged ajax - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged ajax - Stack Overflow. Afficher tous les articles

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'";

Executing Angular.js-controller method on element shown

How to execute controllers method on element shown. I have a tabs, and i want load data when user open a tab, if i using ng-init, information loads after page loading.

var systemSettingsController = manageApp.controller("SystemSettingsController", [ "$scope", function($scope) { $scope.tab = 1; $scope.initTab = function(tab) { $scope.tab = tab; }; } ]); var emailManagementController = manageApp.controller("EmailManagementController", function($scope, $http) { $scope.smtpServer = ""; $scope.smtpLogin = ""; $scope.smtpPassword = ""; this.init = function() { $http.get("/api/EmailSettings") .then(function(res) { var obj = angular.fromJson(res.data); $scope.smtpServer = obj["Email.SmtpServer"]; $scope.smtpLogin = obj["Email.SenderAddress"]; $scope.smtpPassword = obj["Email.SenderPassword"]; }); }; ...

I want execute method init (EmailManagementController) without using ng-init, and at the moment when this element is displayed on the screen, that is, its display will change to a property different from none.

Not sending mail AJAX/PHP with modal no page refresh

I'm new. I have been searching and researching to make my AJAX send my form after submit and making a modal appear, I have figured out the modal to appear and make the page not refresh, and at one point I made the form send to my mail, but now I don't know what I did and I am so confuse, so if somebody can help or share a link and read it I would appreciate it :D. I'm using bootstrap. Thanks very much for reading. :D

Here is my HTML in the body (I have the javascripts all linked)

<div class="row">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <form id="miformulariopers" method="post" action="php/sendmail.php" role="form">
            <div class="form-group">
                <label for="nombre">Nombre</label>
                <input type="text" class="form-control" id="nombre" name="nombre" placeholder="Tu nombre">
            </div>
            <div class="form-group">
                <label for="apellido">Apellido</label>
                <input type="text" class="form-control" id="apellido" name="apellido" placeholder="Tu apellido">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail1">Email</label>
                <input type="email" class="form-control" id="exampleInputEmail1" name="mail"placeholder="Tu correo">
            </div>
            <div class="form-group">
                <label for="InputMessage">Mensaje</label>
                <textarea class="form-control" rows="3" placeholder="Tu mensaje" id="InputMessage" name="mensaje"></textarea>
            </div>
            <div class="form-group">
                <button id="buttonright" type="submit" class="btn btn-default" data-toggle="modal">Submit</button>
            </div>
            </form>
        </div>

This is my PHP:

<?php
$destinatario = 'mymail@gmail.com';
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$mail = $_POST['mail'];
$asunto = 'Correo de la web';
$mensaje = $_POST['mensaje'];
$cabeceras = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
?>
<?php
$success = mail($destinatario, $asunto, $nombre, $apellido, $mail, $mensaje, $cabeceras);
if ($success) {
    echo '<h1>Envío realizado</h1>';
    echo '<p>Personaliza tu mensaje aquí. Respetando las etiquetas "p"</p>';
} else {
    echo '<p><strong>Error al enviar el mensaje. Inténtelo de nuevo.</strong></p>';
}
?>

And my JS and AJAX:

$("#miformulariopers").submit(function () {
  event.preventDefault();
  $("#message").modal('show');

});
$("#buttonright").click(function () {
$.ajax({
        type : "POST",
        url : "php/sendmail.php",
        data: '#miformulariopers'.serialize(),
        dataType: "json",

        });
        });

AJAX Parsing HTML returns [object Object]

I'm trying to load a page in with AJAX using a method I found here.

Everything goes well until I get to the parse_html function. The correct values from the elements on the next webpage are assigned to the body variable (that is, a string of the HTML code from the body tag). But when it turns that into the jQuery object, $body ends up being equal to Object (which I think is maybe correct? I THINK this is a DOM object that has all the HTML from the body tags in it).

Finally, the jQuery object "$content" is made equal to the contents of the first "#content" element. However, response.$content ends up being equal to "[object Object]".

How do I make it so that when I use $content.html(response.$content) the #content div is filled with the HTML from the new page instead of [object Object].

function find_all($html, selector) {
  return $html.filter(selector).add($html.find(selector));
}

function parse_html(html) {
  return $($.parseHTML(html, document, true));
}

// Convert page contents to jQuery objects
function parse_response(html) {

  // 'body' is equal to the strings of text in between the body tags
  var body = /<body[^>]*>([\s\S]+)<\/body>/.exec(html),

  $body = body ? parse_html(body[1]) : $(),

  // '$content' is equal to the contents of the first #content element
  $content = $.trim(find_all($body, '#content').first().contents());

  // Output the variable "$content"
  return {
    '$content': $content
  }
}

For context, here is where I call these functions inline:

url = History.getState().url,
rel = url.replace(root, "/");
$.get(rel).done(function (data) {

    var response = parse_response(data);

    var $content = $("#content");

    $content
        .slideUp(500) // Get it off screen to start
        .promise()
        .done(function () {
            $content
                .html(response.$content)
                .slideDown(500);
        });
}).fail(function () {
            document.location.href = url;
            return false;
});

create a jquery function that adds points into total-points column in MySQL table based on comparion

jquery comparison of rows from a user prediction table and a result a results table. If the values are identical i want to award 3 point to user and add to total points.

$('#pred_table tr').each(function(){

            var currentRowHTML=$(this['Home_Score']&&this['Away_Score']).html();

            $('#fixure tr').each(function(){
                if($(this['Home_Score']&&this['Away_Score']).html()===currentRowHTML){


    //not sure where to begin with the doCalculation function

                    $(this).doCalculation("award 3 points into total points in another
                    table in database");

            }
        });
    });

JSONP issue with Cordova and WebAPI Error: Unexpected token :

I'm having an issue with a some cross site communication in a cordova app I'm toying with, the error is on the ajax call below.

Error in browser

Uncaught SyntaxError: Unexpected token :

The interesting part is that in the response the JSON is there, it just don't arrive to the success.

The WebAPI method

public JsonResult Search(string query)
{
    query = query.ToLower();
    RPAS_Operator op = new RPAS_Operator();
    SearchResultModel sm = SearchSupport.ParseData(op.RPAS_Operators.Where(a =>
    a.Name.ToLower().Contains(query)));
    return Json(sm, JsonRequestBehavior.AllowGet);
}

The jQuery

function Search(query) {
    var url = baseURI + "Search/Search/?query=" + query;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'jsonp',
        cache: false,
        jsonp: 'callback',
        success: function (data) {
            console.log(data);
            document.getElementById("testOutput").innerText = data;
        }
    });
}

How to write php code inside jquery to update database table

I am working in Banking project .I want to write php code to update table upon successful Transaction using ajax . suppose i am sending request from fundtransfer.php to external API and the External API is also responding correctly .Now upon successful API respond i want to update my database table field name status from pending to completed .

    <script>
        $(document).ready(function()
        {
            $.ajax(
            {
            url:"http://ift.tt/1HoFteZ",
            type:"post",
            data:"variable="+value,
            success:function(result)
            {
                if(result==100)
                {
                    $("#message").html(successful transaction);
                    //Now i want to update my database tabale status saying Successful Transation 
                    //where to write these all php mysql code to update my database table
                   // without loading and redirecting page
                }   

                else
                {
                    $("#message").html(some thing gone wrong);
                }

            }
            });
        });
    </script>

redirect not work properly in codeigniter

Halo, i'm using ajax to post form into controller codeigniter. I want to redirect after ajax post, but controller doesn't redirect.

This is my ajax

$.ajax({
    type:"POST",
    url:form.attr("action"),
    data:form.serialize(),

    success: function(){

     },
    error: function(){
    alert("failure");
    }
});

}); });

this is my controller

public function checkout_data(){
    $this->account_model->checkout_simpan();
    redirect('produk/payment/last_steps');
}

this is my form

<form class="form-horizontal col-md-offset-3" id="form-checkout" action="<?php echo base_url('produk/payment/checkout_data');?>">

What wrong with my code ?

unable to reload the page after ajax success

I am trying to login using facebook JS, I am using the following code :

function FBLogin(){
    FB.login(function(response){
        if(response.authResponse){
            FB.api('/me', function(response) {
                    //alert(response);
                    jQuery.ajax({
                        url: 'someurl.php',
                        type: 'POST',
                        data: 'id='+response.id+'&firstname='+response.first_name+'&last_name='+response.last_name+"&email="+response.email,
                        dataType : 'json',
                        success: function(data, textStatus, xhr) {
                        $(document).ajaxStop(function(){
                          setTimeout("window.location = 'otherpage.html'",100);
                        });
                        },
                        error: function(xhr, textStatus, errorThrown) {
                            alert(textStatus.reponseText);
                        }
                    });
                   //window.alert(response.last_name + ', ' + response.first_name + ", " + response.email);
                 });
        }
    }, {scope: 'email'});
}

In this I have a ajax call, I want to reload the page after the ajax success. In someurl.php, I am just echo some text, I want to reload the page after the ajax success.

I have tried

success: function(data, textStatus, xhr) {
                            $(document).ajaxStop(function(){
                              setTimeout("window.location = 'otherpage.html'",100);
                            });
                            },

and

success: function(data, textStatus, xhr) {

                            window.location.reload();
                        },

but none of code is working, Please help me guys, How can I reload the page when the ajax is success

ajax get request in node js express

Hi Guys working a litle bit on my Node js Skills.

Would like to add some data to mongodb using a button click.

Client side code looks like this

        $(function() {
        $('#add').click(function(){
            $.ajax({
                type: "GET",
                url: "/item/<%= products._id %>/add"
            }).done (function (data) {
                alert(data);
                console.log(data);
            });
        });
    });

  <button type="submit" id="add" class="btn btn-primary">Interessted</button>

Server side code like this

    app.get('/item/:id/add', function(req, res) {

    Listing.findByIdAndUpdate(
        { _id : req.params.id},
        { $push : {"product.interessteduser": req.user._id }},
        {  safe: true, upsert: true},
        function(err, model) {
            if(err){
                console.log(err);
            }

        });
});

The Code works perfectly for me. But if i wait a litle bit i get another request in my console.

Looks like this

GET /item/557eec02aa1046b805190207/add 200 120001ms
GET /item/557eeb82aa1046b805190206/add 200 120000ms

So every time request /item/:id/add and wait for 120000ms i get another request. How to stop this?

I would like to hit the button once do the /item/557eeb82aa1046b805190206/add Get request and that's all.

Uncaught Error: Error: An invalid exception was thrown

I am trying to use ExternalInterface to call a Flash Function from javascript.

My JS:

function thisMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
    return window[movieName]
}
else {
    return document[movieName]
}
}

function DoThis() {
$.ajax({
    url: 'POSTINGURLHERE',
    type: 'POST',
    dataType: 'json',
    data: { 'at': 1 },
    success: function(result) {
        thisMovie("ID").Lol(result['xD']);
    }
});
}

This code works perfectly on Localhost, just not on my public webhost? I am getting on Google Dev Tools: http://ift.tt/1IDt7fE

I have the flash callbacks set in the swf, perfect for Localhost as mentioned. So why is it not working on my webhost?

AJAX PHP response interpretation

I noticed that there are several ways for an AJAX call made by jQuery to interpret data. I had a look at json, but maybe it is an over complication for what I am trying to do.

My php script ALWAYS returns a 1 integer string SOMETIMES followed by a 1 integer int OR a 2 integer int.

So it can either return

x or xy or xyz

where x, y, and z are real single numbers.

How could I decode this response and assign jQuery var to the reply. I was thinking something like.

var code = firstNumberOf response
var value = secondNumberOf and thirdNumberOff response

But var value can also just be the second number if there is only a second number and not a third one.

Thanks in advance, I have been dwelling on this for ages.

Make indexable an ajax based webpage

I want to make indexable my ajax based website.

I have read this doc: http://ift.tt/PGKKpZ But I don't understand it at all.

I think I need to do it:

  1. Write this tag in a webpage, for example: www.myweb.com/mypage

    <meta name="fragment" content="!">
    
    
  2. I'm using UrlRewriteFilter for my Tomcat Server (http://ift.tt/L066wZ), so I think I could redirect the urls with the substring: "?_escaped_fragment_=" to a html snapshot (which I can build manually, writing my custom meta-description, title and content???)

    <rule>
       <from>^/mypage\?_escaped_fragment_=</from>
       <to type="forward">/snapshots/mypage.html</to>
    </rule>
    
    
  3. Write the URLs (without the escaped fragment) into the sitemap.xml

    ...
    <url>
    <loc>http://ift.tt/1ed3v19;
    ...
    </url>
    ...
    
    

Is it right? I need to do something more?

Reactive javascript - convert ajax calls to Bacon.js stream with pagination

How can I convert calls to server API, with pagination support, to a Bacon.js / RxJs stream?

For the pagination I want to be able to store the last requested item-index, and ask for the next page_size items from that index to fill the stream.

But I need the 'load next page_size items' method to be called only when all items in stream already been read.

Here is a test that I wrote:

var PAGE_SIZE = 20;
var LAST_ITEM = 100;
var FIRST_ITEM = 0;

function getItemsFromServer(fromIndex) {
    if (fromIndex > LAST_ITEM) { 
        return [];
    }

    var remainingItemsCount = LAST_ITEM-fromIndex;
    if (remainingItemsCount <= PAGE_SIZE) {
        return _.range(fromIndex, fromIndex + remainingItemsCount);
    }
    return _.range(fromIndex, fromIndex + PAGE_SIZE);
}


function makeStream() {
    return Bacon.fromBinder(function(sink) {
        var fromIndex = FIRST_ITEM;

        function loadMoreItems() {
            var items = getItemsFromServer(fromIndex);
            fromIndex = fromIndex + items.length;
            return items;
        }

        var hasMoreItems = true;

        while (hasMoreItems) {
            var items = loadMoreItems();
            if (items.length < PAGE_SIZE) { hasMoreItems = false; }
            _.forEach(items, function(item) { sink(new Bacon.Next(item)); });
        }        

        return function() { console.log('done'); };
    });
}

makeStream().onValue(function(value) {
    $("#events").append($("<li>").text(value))
});

http://ift.tt/1Lw93Ba

Currently the 'getItemsFromServer' method is only a dummy and generate items locally. How to combine it with ajax call or a promise that return array of items? and can be execute unknown number of times (depends on the number of items on the server and the page size).

I read the documentation regarding Bacon.fromPromise() but couldn't manage to use it along with the pagination.