dimanche 28 juin 2015

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.

Show AJAX div when image hovered and follow the mouse

I need help. I'm working on a website that's give user a download link to movies. But I can't get the preview_block div showed up when the mouse is hovered on the movie_block. I can't even make the div follow my mouse when I hovered it. Here's my code. I temporarily comment out the style link.

<?php
require_once('includes/variables.php');
?>
<!DOCTYPE html>
<html>
    <head>
        <!--<link href="includes/styles.css" />-->
        <style>#movie_block {
    cursor: pointer;
}
#preview_block {
    position: absolute;
    display: none;
}
body {
    position: relative;
}</style>
    </head>
    <body>
        <div class="">
            <div id="preview_block" style="display:none"><p>test</p></div>
            <table>
                <!-- -->
                <tr>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[0]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[0]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[0]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[0]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[0]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[1]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[1]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[1]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[1]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[1]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[2]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[2]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[2]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[2]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[2]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[3]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[3]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[3]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[3]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[3]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[4]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[4]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[4]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[4]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[4]->title; ?></a>
                        <br>
                    </td>
                </tr>
                <!-- -->
                <tr>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[5]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[5]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[5]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[5]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[5]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[6]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[6]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[6]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[6]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[6]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[7]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[7]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[7]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[7]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[7]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[8]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[8]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[8]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[8]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[8]->title; ?></a>
                        <br>
                    </td>
                    <td>
                        <a href="<?php echo $movieNameList->data->movies[9]->torrents[0]->url; ?>"><span id="movie_block"><img src="<?php echo $movieNameList->data->movies[9]->medium_cover_image ?>" alt="<?php echo $movieNameList->data->movies[9]->title; ?>" /></span></a>
                        <br>
                        <a href="<?php echo $movieNameList->data->movies[9]->torrents[0]->url; ?>"><?php echo $movieNameList->data->movies[9]->title; ?></a>
                        <br>
                    </td>
                </tr>
            </table>
        </div>


        <script>
            $("#movie_block").hover(function(event) {
                $("#preview_block").css({top: event.clientY, left: event.clientX}).show();
            }, function() {
                $("#preview_block").hide();
            });
        </script>
    </body>
</html>

php ajax contact form http_response_code() on line 17

I've tried to get this contact form to work, and I've followed the example http://ift.tt/PtDpvh . I only get the Fatal error: Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom/spirit/mailer.php on line 17 above my contact form. I do not know php at all, but having this contact form is kick-ass! Here are the relevant files:

Here is the html:

<!DOCTYPE html>
<div id="form-messages"></div>
                <form id="ajax-contact" method="post" action="mailer.php">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="exampleInputEmail1">Name</label>
                                <input type="text" id="name" class="form-control" name="name" required placeholder="Name...">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="exampleInputPassword1">E-mail</label>
                                <input type="name" class="form-control" id="email" placeholder="E-mail" required>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Message</label>
                        <textarea class="form-control" rows="3" id="message" name="message" placeholder="Your Message Here" required></textarea>
                    </div>

                    <button type="submit" class="btn tf-btn btn-default">Submit</button>
                </form>

Here is the js file:

$(function() {

// Get the form.
var form = $('#ajax-contact');

// Get the messages div.
var formMessages = $('#form-messages');

// Set up an event listener for the contact form.
$(form).submit(function(e) {
    // Stop the browser from submitting the form.
    event.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
    .done(function(response) {
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // Set the message text.
        $(formMessages).text(response);

        // Clear the form.
        $('#name').val('');
        $('#email').val('');
        $('#message').val('');
    })
    .fail(function(data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');

        // Set the message text.
        if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
        } else {
            $(formMessages).text('Oops! An error occured and your message could not be sent.');
        }
    });

});

});

and here is the mailer.php

<?php
// My modifications to mailer script from:
// http://ift.tt/PtDpvh
// Added input sanitizing to prevent injection

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(200);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "myemail@gmail.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
//            http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your     message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

I know this is not the best way of asking for help. But any help is much appreciated. If I could, I would, buy the person a coffee if it was physically possible :).

Many thanks!

Returning arrays from php with ajax and json

-I have an array that contains more arrays in my php file. I am sending a integer variable (Possibly something else for sometime later that isn't the problem)

-I want php file to return array according to the incoming variable (in this example just 1 and 2.)

-I tried somethings from other posts but they were too complicated and I couldn't understand any of them. And I want to be able to change it whenever I want.

This is what I have done so far..

index.php

<script src="http://ift.tt/1APuVEV"></script>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script type="text/javascript">   
        var sayac = 1;
        $(document).ready(function() {

                $(document).delegate("#klikme", "click", function() {
                        $.post('sayac.php',{"komut": sayac }, function(data){
                                
                                var res = $.parseJSON(data);
                                $('#output').html(res.result[0]);
                                $('#output2').html(res.result[1]);
                        });
                        sayac = sayac + 1;
                        if(sayac > 2)
                                sayac = 1;
                });
        });

</script>
<div id = "klikme">
        KLİK ME!
</div>

<div id = "output">
<?php include 'sayac.php'?>

</div>

<div id = "output2">

</div>

sayac.php

<?php 

        $returnThis = array( array("One" => "Sample Stuff Bla Bla this is one!","Two" => "Sample Text One"), 
                                                array("One" => "Sample Stuff Bla Bla this is one!", "Two"=> "Sample Text Two"));

        if(isset($_POST["komut"]))
        {
                switch($_POST["komut"])
                {
                        case 1:
                                json_encode($returnThis[0]) ;
                                break;
                        case 2:
                                json_encode($returnThis[1]); 
                                break;
                        default:
                                echo "Something is wrong";
                                break;
                }
        }
        
?>

PHP and AJAX login Script secure enough?

I want to create a dynamic login on my website using ajax (with jquery). Now everything is done, and everything works well. My problem is, that i dont know, if everything works secure (enough) to use it, like it's now.

My ajax script:

//LOGIN
$(function(){
  var mail;
  var password;
  $("body").on("click", ".sign-in", function(event){
    mail = $('#login-mail').val();
    password = $('#login-password').val();
    //ajax
    $.ajax({
      type: "POST",
      async: true,
      url: '/index.php',
      data:  { 'mail': mail,'password': password},
      success: function (msg)
        {

          if($(msg).filter('.logged-in').html() == 'success'){
            window.location.replace('/timeline.php')
          }else{
            $('input').css('border','0.1rem solid #EB5757');
            $('.login-failed').html('Falsche E-Mail oder / und Passwort !');
          }
        },
      error: function (err)
      { alert(err.responseText)}
    });
  });
});

The logic behind this: Ajax sends the user and pass to a PhP page:

if(isset($_POST["mail"]) && isset($_POST["password"])){
  //$mU->hashPassword($_POST['password']);
  if($mU->loginUser($_POST["mail"],$_POST["password"]) == true)
  echo '<div class="logged-in">success</div>';
}

$mU->loginUser($_POST["mail"],$_POST["password"]) == true when true, everything is fine. Then the Script "echos" success. In my ajax success function, jquery checks the content of the div.

I hope you know what i mean, because its very hard to explain my "problem". Is my Script secure ? What can I do better (security) ?

jquery Select2 4.0 trigger('change') does not work

var $element = $("#genre").select2({
            placeholder: "select genre",
            maximumSelectionLength: 3,
            ajax: {
                url: function (params) {
                    return "/score/search_genre/"+params.term
            },
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                var select2Data = $.map(data.genre, function (obj) {
                    obj.id = obj.code;
                    return obj;
                });
                return {
                results: data.genre
              };
            },
            cache: false
            },
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 1,
            templateResult: genreSelectFormat, // omitted for brevity, see the source of this page
            templateSelection: function (data) { return data.genre_kr; }
        });

$element.trigger('change');


<select name="genre[]" id="genre" style="width:70%" multiple>
  <?php foreach($genres as $genre) { ?>
     <option selected="selected" value="<?=$genre?>"><?=get_genre_nm($genre)?></option>
  <?php } ?>
</select>

I'm using select two multiple selection with ajax

there's no problem when I does not use with ajax

but with ajax initial option's text does not show up like below

now : ([ⓧ] [ⓧ] [ⓧ] ) <-- options without text

i want : ( [default1ⓧ] [default2ⓧ] [default3ⓧ] ) <-- proper result

php foreach loop prints result well

I don't know what I did wrong

How to attach multiple scroll events on different divs in JavaScript / jQuery?

I need to load dynamically data on scroll event but my data is grouped in different tables. If the number of rows returned from AJAX call is grater than some limit, overflow and height is added to that table.

At document loading I only fetch and populate table title which represent different groups. On first click on a group title a chunk of data (table rows <tr>) is loaded and displayed on the page.

So I need to keep track if the cursor is over some table and than to trigger the scroll event. Here is some code and structure :

// allGroups holds the ids of all the groups
allGroups = [435,56,34,23,452];

$(document).ready(function () {

$.each(allGroups, function(ind, value){

    var item = $('#POI_data_' + value);

    item.on('mouseenter',function(){

        item.on('scroll',function(){
            // fetch new data
        });

    });
    item.on('mouseleave', function(){

        item.off('scroll');
    });
});
});

table structure:

<div id="POI_data_<?php echo $poiRow['id'] ?>">
    <table >
        <!-- FETCH NEW DATA -->
    </table>
</div>

My problem is when mouseenter event triggers on another table, the scroll event is not properly triggered.

Sending a integer value to php with javascript and returning values

I have this div area in my index and I want to use it as a button (for graphical issues) and when this button is cliked I want it to send this value to php file and I want to return some values according to this value. Here is what I've done this far but it didn't work at all.

this is my output.php (index)

<script src="http://ift.tt/1APuVEV"></script>
<script type="text/javascript"> 
        int sayac = 1;
        $(document).delegate("#klikme", "click", function() {
                $.post('sayac.php',{"komut": sayac }, function(data){
                        $('#output').html(data);
                });
                sayac = sayac + 1;
        });

</script>
<div id = "klikme">
        KLİK ME!
</div>

<div id = "output">
<?php include 'sayac.php'?>

</div>

sayac.php

<?php 
        if(isset($_POST["komut"]))
        {
                switch($_POST["komut"])
                {
                        case "1":
                                echo "This is one";
                                break;
                        case "2":
                                echo "This is two";
                        default:
                                echo "Something is wrong";
                                break;
                }
        }
        return false;
?>

AJAX can't received data to controller MVC

I send data by ajax to mvc controller.
i got to correct method but without data.
i tried to get List or strong all the time null

js code:

function sendDataCreateMilestone(parameters) {
    $.ajax({
        url: "/QRCNew/create",
        type: "post",
        dataType: "json",
        data: JSON.stringify(parameters)
    });
}

server:

here i revived all the time null 
 public ActionResult Create (List<string> ids, string collection)
        {
          do....
          }

jQuery: dynamic insert in won't work properly

I'm writing a page in jQuery Mobile and I have an Unordered List which contains elements like these:

<ul id="ul1" data-role="listview" data-theme="d">
            <li>
                <a>
                <h1>Who wants to live forever</h1>
                    <p>Queen</p>
                </a>
            </li>
            <li>
                <a>
                <h1>Personal Jesus</h1>
                    <p>Depeche Mode</p>
                </a>
            </li>
        </ul>

But I want to insert elements DYNAMICALLY, searching in a MySQL database. It works, but the elements that are inserted in the UL DON'T look like the default LI in jQuery Mobile: they appear as simple text thrown in the UL. The jQuery Mobile's "Graphic" is not represented. Here's the codes:

Ajax function for searching through php:

<script>
function ricerca() {
    str = document.getElementById("search").value;
    if (str == "") {
        document.getElementById("ul1").innerHTML = "Nulla";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("ul1").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","cerca.php?ricerca="+str+"&tipo="+document.getElementById("select-choice-0").value,true);
        xmlhttp.send();

    }

Here's the lines of code (in the PHP) that writes the contents in the UL:

// output data of each row
    while($row = $result->fetch_assoc()) {
        if($inizio == 0)
        {if ($row['CodISWC'] != $prev_iswc) {
           echo "<li>
                <a>
                <h1>". $row["NomeCanzone"]. "</h1>
                    <p>". $row["NomeArtista"];
           $prev_iswc = $row['CodISWC']; 
        }
        else{
            echo ", ". $row["NomeArtista"];   
        }

         $inizio = 1;
        }
        else{
            if ($row['CodISWC'] != $prev_iswc) {
           echo "</p>
                </a>
            </li><li>
                <a>
                <h1>". $row["NomeCanzone"]. "</h1>
                    <p>". $row["NomeArtista"];
           $prev_iswc = $row['CodISWC']; 
        }
        else{
            echo ", ". $row["NomeArtista"];   
        }


        }

    }

Asynchronous PHP call to send email

I need to send an email (email.php) which should process asynchronously with main execution. Any echo, error etc happens in the email should not come in play in the main execution. Also the main execution should proceed without having to wait for email to send or fail to send.

Currently an ajax call is made to process.php file which end like the one below. But sendProcessEmail() gets executed first before jumping to next line of code, which is normal. But how could i make sendProcessEmail() asynchronous?

$processdata($sid);
sendProcessEmail($data_email, $data_displayname);// asynchronous 
$form_data = $getLatestData(); // this line should execute right after sendProcessEmail() is called
echo json_encode($form_data);

Spoofing xmlhttprequest (greasemonkey)

I am blocking an XMLHttpRequest from greasemonkey but the page bugs when it gets no response. So i tried spoofing as if the response is recieved. Unforunetly it seems XMLHttpRequest has fields read-only. So i created a fake object :

fakeresponse = "for (;;);"+JSON.stringify(fakeresponse);


var xhr2 = {};
xhr2.readyState = 0;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.readyState = 1;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.readyState = 2;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.readyState = 3;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.response = fakeresponse;
xhr2.responseText = fakeresponse;
xhr2.responseXML = fakeresponse;
xhr2.status = 200;
xhr2.readyState = 4;

if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);

the object is :

Object {response: "for (;;);{"__ar":1,"payload":{"actions":[{"..."},"bootloadable":{},"ixData":{},"lid":"0"}", responseText: "for (;;);...", responseXML: "for (;;);....", status: 200, readyState: 4}

but nothing happens.. is there any other way i can simulate this or do i have to dive in deep with a debugger ? also the page uses a library rather than pure xhr object, can that be an issue ?

ajax code with echo

i have this ajax code

                   <script>
                  $(document).ready(function(){
                      $('ul#tab li:first').html('<?php echo $channel;?>');
                      $('ul#tabs li').on("click",function(){
                          //        $('ul#tab li.active').html($(this).html());
                          $('ul#tab li').html("");
                          //$('ul#tab li.active').html($(this).html());
                          var index = $( "ul#tabs li" ).index( $(this) );
                          $.post("../admin/ajax/ch1.php", {index: index}, function(result){
                              $('ul#tab li.active').html(result);
                          });
                      });
                  });
              </script>

and in the php ch1.php is

<?php
$ch1tab1= file_get_contents("../channels/ch1tab1.html");
$ch1tab2= file_get_contents("../channels/ch1tab2.html");
$ch1tab3= file_get_contents("../channels/ch1tab3.html");
$ch1tab4= file_get_contents("../channels/ch1tab4.html");
$ch1tab5= file_get_contents("../channels/ch1tab5.html");
$channel = $_POST['index'];
if ($_POST['index'] == 0 ){ $channel = $ch1tab1;}
else if ($_POST['index'] == 1){ $channel = $ch1tab2;}
else if ($_POST['index'] == 2 ){ $channel= $ch1tab3;}
else if ($_POST['index'] == 3 ) {$channel = $ch1tab4;}
else if ($_POST['index'] == 4 ) {$channel = $ch1tab5;}
echo $channel; ?>

the varible ch1tab4 have a code , and it is not work , echo blank what i should to do plz ?

Cannot redirect inside the custom success callback on an Ajax wrapper

I am trying redirect a user to the login page if he/she is not logged in anymore or do not have the permission when doing certain functionalities via Ajax. To not get redundant, I implemented a wrapper for the success callback based on the code that I found here that checks if the controller returned not_logged_in to signify that the user does not have permission. If the user doesn't have permission, I redirect the user using the custom success function. The problem is that it doesn't redirect the user to the login page. Instead, it just prints the login page on the console and the actual Ajax call fails. What should I change in my code?

Here is the Ajax wrapper:

function wrapped_ajax(options) {
    var success = options.success;
    options.success = function(data, textStatus, jqXHR) {
        if(success) {
            if (data.not_logged_in) {
                window.location = 'login';
            } else {
                success(data, textStatus, jqXHR);
            }
        }

    };
    return $.ajax(options);
}

Serialize jQuery Variables

I would like to make an AJAX POST to a php script and send over the following variables. I had a look at the jQuery documentation but I struggled to understand its' use anywhere outside of forms.

var amount = $('input[name=amount]').val();
var chance = $('input[name=chance]').val();

These are two decimal values, how could I format them to send them as the data field in an AJAX post request?

If serialize() is not the way to go, what is?

Thanks in advance

a4j:push not using websockets and falling back to long-polling

I am using Richfaces 4.2.2 for my project and from this link, figured out that atmosphere 0.8.4 needs to be used for compatibility. I am able to get push working but it is using long-polling instead of websockets. Webserver is Jboss 8.2 (undertow).

Following configurations were done to achieve this:

<context-param>
    <param-name>org.richfaces.push.initializeOnStartup</param-name>
    <param-value>true</param-value>
</context-param>
 <context-param>  
    <param-name>org.atmosphere.useBlocking</param-name>  
    <param-value>true</param-value>  
 </context-param> 

On server side, push notifications are send to client using

TopicKey topicKey = new TopicKey(key);
TopicsContext topicsContext = TopicsContext.lookup();
topicsContext.publish(topicKey, message);

On client side, notifications are received as. I have added script block to use transport for push as websocket, but it seems to be failing.

<script>
   Richfaces.Push.transport = "websocket";  
   Richfaces.Push.fallbackTransport = "long-polling;  
</script>  

<a4j:region>
    <a4j:push address="update">
        <a4j:ajax event="dataavailable" render="someelements"/>
    </a4j:push>
</a4j:region>

Can anyone guide me along with the missing configurations? OR it is the limitation with the current version of richfaces/atmosphere that long-polling is the only supported transport mechanism?

Drag and Drop between 2 listboxs & Database Update

I want to implement a facility for a web app users for drag an item from a listbox and drop it to the other listbox. After every Drag & Drop needs to update a sql table. I googled about D&D and find some solutions, but I do not know which one is the best? and also I do not know the right way. Which on I have to use? jquery, Ajax, or some other plugins? I'd appreciate If someone give me a pathway to accomplish this task.

Uncaught TypeError: Cannot read property 'length' of undefined when trying to populate responsive datatable using php?

I am trying to fill responsive datatable with ajax request to a php script , the response is returned a JSON_encode format , i can see the response in xhr requests: ["abc","def","ght","jkl"]

Here is the code i am using

Name

                                    </tr>
                                </thead>
                             <tfoot>
        <tr>
            <th>Name</th>

        </tr>
    </tfoot>
    </table>




    $('#dataTables-example').DataTable({
            responsive: true,
               "ajax": "search_autocomplete.php",


    });

});

here is the php script-

   if ($result->num_rows >0) {
// output data of each row
while($row = $result->fetch_assoc()) {


    $list[] =$row['name'];

    }       
      echo json_encode( $list );            

}

Load ajax success data on new page

My ajax call hits the controller and fetches a complete JSP page on success. I was trying to load that data independently on a new page rather than within some element of the existing page. I tried loading it for an html tag but that didn't work either. I tried skipping the success function but it remained on the same page without success data. My ajax call is made on clicking a normal button in the form and the code looks like as shown below.

$.ajax({

    url : '/newpage',
    type : 'POST',
    data : requestString,
    dataType : "text",
    processData : false,
    contentType : false,
    success : function(completeHtmlPage) {
        alert("Success");
        $("#html").load(completeHtmlPage);
    },
    error : function() {
        alert("error in loading");
    }

});

Can't Understand the XmlHttpRequest Code

First I should say I'm a beginner to XMLHttpRequest.

I Need to get a response from the below code that I didn't wrote.

But all I get is objectXMLHttpRequest.

How Can I find out if this function is returning true or false : actually the URL is for a PHP page that will return true or false.

function :

syncRequest:function(method, uri, checkTime, timeStamp, timeInterval)
{
    //if(this.checkUSBAccess(uri))
    {
        var usbParam = 0;//USBToken.getUSBTokenUrl();
        if(usbParam)
        {
            uri += usbParam;
        }
    }

    if (checkTime)
    {
        var d = new Date();
        if ((d.getTime() - timeStamp.getTime()) < (timeInterval*1000))
            return false;
    }
    var errorObj;
    var o = this.getConnectionObject();

    if(method == 'POST'){
        var splitedUri = uri.split('?');
        uri = splitedUri[0];
        var postData = splitedUri[1];
    }

    if(!o){
        return null;
    }
    else{
        var oConn = this;
        if(activeXSRFCode)
        {
            if(method == 'POST')
            {
                if(typeof postData != 'undefined' && postData.length > 0)
                {
                    postData = postData + '&XSRFCode='+ XSRFCode;
                }
                else
                {
                    postData = 'XSRFCode='+ XSRFCode;
                }
            }
            else
            {
                if (uri.indexOf('?') > 0)
                    uri += '&XSRFCode='+ XSRFCode;
                else
                    uri += '?XSRFCode='+ XSRFCode;

            }

        }
        o.conn.open(method, uri, false);

        if(postData){
            this.initHeader('Content-Type','application/x-www-form-urlencoded');
        }

        //Verify whether the transaction has any user-defined HTTP headers
        //and set them.
        if(this._http_header.length>0){
            this.setHeader(o);
        }
        postData?o.conn.send(postData):o.conn.send(null);

        if(activeXSRFCode)
        {
            try
            {
                var rText = eval(o.conn.responseText);
                XSRFCode = rText['XSRFCode'];
                var object1 = {};
                object1.responseText = '('+JSON.stringify(rText['data'])+')';
                return object1;
            }
            catch (e)
            {
                return o.conn;
            }
        }

        return o.conn;
    }
    object1.responseText = '('+JSON.stringify(rText['data'])+')';
    return object1;
},

this is how I want to get result :

$result=syncRequest('GET', url);
Utils.showMessage($result);//create a javascript box that will show the response

javascript ajax generates error Client/server version mismatch: Unsupported client

I have a problem connecting javascript and c# (Windows forms) using http requests. I have a JS code like this:

ext.get_led = function ( callback) {
        // Make an AJAX call to the Open Weather Maps API
        $.ajax({
            url: 'localhost:12754/poll',
            dataType: 'text',
            success: function (data) {
                // Got the data - parse it and return the temperature
                callback(data);
            },
            failure: function () {
                callback("Null");
            }
        });
    };

that is supposed to send an ajax request to the Windows Forms app. The Problem is that whenever I try to execute this function, the Javascript console shows an error: The error being generated when trying to send the ajax request

In the link it gave me (http://ift.tt/1eceNme) there's this: "Client/server version mismatch: Unsupported client"

My c# code looks like that:

public class MyHttpServer : HttpServer
        {
            public int busy;
            public bool isSpeaking = false;
            public float result;
            public MyHttpServer(int port)
                : base(port)
            {
            }

            public override void handleGETRequest(HttpProcessor p)
            {
                if (p.http_url.Equals("/poll"))
                {
                    p.writeSuccess();
                    p.outputStream.WriteLine("SCRATCH");
                    p.httpHeaders = new Hashtable { { "Access-Control-Allow-Origin", "*" }, { "Content-Type", "text/plain"} };
                    return;
                }
            }
            public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
            {

            }
        }

There are another 2 classes in the c# code, but their code is very long, so I won't put it here. I once tested the whole system with communication between 2 apps (not app-web), and it was working perfectly. But, when I wanted my app to communicate with the web, it refuses. The error says something is wrong with my client, but I have no idea what (Also the client - ajax - was tested and working fine).

Whoever helps, thank you.

JS Ajax Get call to a url returning a document

When I go to the url by a browser, it returns a response successfully and starts an automatic download of the document.
I would expect it to return an xml file in the first place but the service cannot be changed and it returns a file whose type is document.

The document's content is as follows; It basically has a list of urls.

name endpoint

name1 url1

name2 url2

name3 url3

.

.

First, how I should make the call successfully by Javascript? The following is always in error.

$.ajax({
         url: "http://url",
         dataType: "document",
         success:  function(document) {                     
                 console.log("success");
         },
         error: function() {                     
                 console.log("error");

         }
     });

Is there any way, after calling the service, to keep the file on the air ( without saving ) then parse each line ?

Datatables draw() without ajax call

I'm trying to resize server-side Datatables to fit the screen size. When the window size is changed I make recalculation of new datatables height and then call draw(false) to redraw the layout of datatable.

Unfortunately, the draw() method makes an ajax call and this makes the solution unusable, because it shows "processing" and takes time to get the data on every small window change.

How to redraw datatables layout without calling AJAX? I don't need to refresh data, I just want to redraw the table.

samedi 27 juin 2015

java ajax autocomplete not working

Ajax auto complete is not working. I debug the code and found that in my controller where I wrote the json line the debugger failed to debug there. I am new too this, plz help me out.

Controller

    response.setContentType("application/json");
        try {
                String term = request.getParameter("term");
                System.out.println("Data from ajax call " + term);

                AutoData a = new AutoData();
                a.setName(term);

                DataDao d = new DataDao();
                List<AutoData> data = d.getData();


                String searchList = new Gson().toJson(data);
                response.getWriter().write(searchList);
        } catch (Exception e) {
                System.err.println(e.getMessage());
        }
}

DataDAO

public class DataDao {
        private String sql;
        private ResultSet rs;


        public List<AutoData> getData(){
            List<AutoData> aData = new ArrayList<AutoData>();
            try{
            sql = "select * from userdetails";
            rs = DBConnection.executeQuery(sql);
            while(rs.next()){

                AutoData a = new AutoData();
                a.setName(rs.getString("userid"));
                aData.add(a);
            }
            }
            catch(Exception e){
                System.out.println(e.getMessage());
            }
            return aData;





}
}

AJAX CODE

$(document).ready(function() {
        $(function() {
                $("#search").autocomplete({     
                source : function(request, response) {
                $.ajax({
                        url : "AutoController",
                        type : "GET",
                        data : {
                                term : request.term
                        },
                        dataType : "json",
                        success : function(data) {
                                response(data);
                        }
                });
        }
});
});
});

Send array from php to js with ajax and json

I am trying to send an array from php (that i have taken from a mysql table to js).Although there a lot of examples out there i can't seem to make any of them work. The code that i have reached so far is:

php_side.php

<!DOCTYPE html>
<html>
<body>

<?php
//$q = intval($_GET['q']);
header("Content-type: text/javascript");

$con = mysqli_connect("localhost","root","","Tileiatriki"); 
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

//mysqli_select_db($con,"users_in_calls");
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);


/*while($row = mysqli_fetch_array($result)) {
     echo $row['User1_number'];
     echo "<br/>";
     echo $row['User2_number'];
         echo "<br/>";
     echo $row['canvas_channel'];
         echo "<br/>";
}*/
echo json_encode($result);

    mysqli_close($con);
    ?>
    </body>
    </html>  

test_ajax.html

    $(document).ready(function(){
      $.getJSON('php_side.php', function(data) {
        $(data).each(function(key, value) {
            // Will alert 1, 2 and 3
            alert(value);
        });
     });
   });

This is my first app that i use something like this, so please be a little patient. Thank you!

PHP FTP_PUT uploading to directory

Im learning PHP by myself from a book called "PHP the Complete Reference - PHP5.2" Im currently at Chapter11 FTP, uploading,deleting,makedir etc but have run into a few questions not covered by the book:

According to my textbook this is a simple code to upload to a server:

$connect=ftp_connect("johnsite.com");
$result=ftp_login($connect,"john@johnsite","johnnyWalker");
if(!$result){
echo'Could not connect to Server';  
}
$result=ftp_put($connect,'myFile.php',FTP_ASCII);
echo'UPLOADING FILE......';
if($result){
    echo'File Uploaded!';
}

My Questions:

  1. To which directory will this upload, how will I modify code if i want to upload to directory say public_html/images/myFile.jpg
  2. In the example myFile.php is hardcoded, what if I want user to select a file to upload? Am I correct in assuming you can do something like this:

    <input type="file" name="myFile" value="upload a file" />
    <input type="submit" name="upload" />
    
    if(isset($_POST['upload'])){
        $fileName=$_POST['myFile']; //file is now assigned to var name
        $result=ftp_put($connect,$fileName,FTP_ASCII); //file linked to var name being uploaded
    }
    
    
  3. Is this the most efficient secure way?

Thank you for reading

php Random variable countdown limited in time

I am writing a randomized countdown that show number of products left in promotion alongside a timer. Number of products left is stored in the database, so all users see the same number. I am using simple php/ajax/javascript solution. My problem is with distributing the random sales so all fit within limited timer and are nicely distributed.

Here is code I have so far:

function start() {
    $date= new DateTime();
    $prod_left = getval("SELECT * FROM counter LIMIT 1");
    if ( $prod_left == 20 ) {
        $fp = fopen("../index.html", "r+");
        while($buf = fgets($fp)){
            if(preg_match("/<!--(.|\s)*?-->/", $buf)){
                fputs($fp, '<script type="text/javascript">$(document).ready(function() {$(".countdown").circularCountdown({startDate:"' . $date->format('Y/m/d H:i:s') . '",endDate:"' . $date->modify("+5minutes")->format('Y/m/d H:i:s') . '",timeZone:+2});});</script></body></html>');
            }
        }
        fclose($fp);
        sleep(30);
        while ($prod_left > 0) {
            if (rand(0,4) > 2) {
                $prod_left--;
                sleep(rand(1,13));
                updateval($prod_left);
            }
        }

    } else {
        echo 'Promocja w trakcie lub zakończona, zresetuj zegar, jeżeli chcesz rozpocząć ponownie';
    }
    exit;
}

My assumption here is: 50% of time decrease timer and wait on average 6.5 seconds, which should on average give me 260 seconds for full sale. Unfortunately its very unevenly distributed. My goal is to have the $prod_value down to 0 not later than 270seconds after loop start, with quite evenly distributed value decreases (can accelerate towards ending) Will you be able to help?

Implementation doesnt need to be in any particular programing language, im just looking for a clue/concept I can follow to achieve this.

What is the strangest, the $prod_left value not always goes to 0, on sime iterations it just sits at 3 or 5.

Please help!

Upload file to a specific Google Drive folder

This is my code used to upload my file to a Google Drive folder following this and this documentation:

url = 'http://ift.tt/1nDTxXQ'
xhr = new XMLHttpRequest()
file.parents = ['0Byw-VOFo8yZ0a3NmSGpTajJmc0E'] # ID of the folder
xhr.file = file
xhr.open 'post', url, true
xhr.setRequestHeader 'Authorization', "Bearer #{ token }"
xhr.onreadystatechange = (event) ->
  if @readyState is 4 and @status is 200
    console.log @responseText
    callback null, event
xhr.send file

Unfortunately, the file is always uploaded to the root folder. I've also tried this: file.parents = [{ id: '0Byw-VOFo8yZ0a3NmSGpTajJmc0E' }]. But it still doesn't work.

Am I missing anything?

Asp.net MVC Loading Parent View from the actionlink of PartialView using Ajax not working

I have a situation where I need to call ParentView from its partial view. Like I have list of ToDos in Partial view where Ajax actionlink is used to edit the data in parent by passing its id. The same is working without using Ajax as it is manipulating url by putting querystring. But we would like to have internal call with Ajax which is not firing.

The code we are using is like that:

<li>@Ajax.ActionLink(@item.ToDoTitle, "Index", new { tdid = @item.ToDoId }, new AjaxOptions { UpdateTargetId = "saved", InsertionMode = InsertionMode.Replace, HttpMethod="POST" })</li>

and controller is like that:

public ActionResult Index(int tdid =0)
    {
        if (tdid !=0)
        {
            ToDo t = new ToDo();
            t.ToDoTitle = "Ramlal";
            t.ToDoDesc = "Shyamlal";
            t.ToDoId = tdid;
            return Json(t);
        }
        else
        {
            return View();
        }
    }

Upload files to Google Drive using Dropzone

This is my current code used for the uploading task:

$imagesDropzone.dropzone
  init: ->
    this.on 'sending', (file, xhr) ->
      xhr.setRequestHeader 'Content-Type', file.type

  url: 'http://ift.tt/1nDTxXQ'
  method: 'post'
  maxFileSize: 5
  paramName: 'images-dropzone-input'
  headers:
    'Authorization': "Bearer #{ uploadBundle.accessToken }"
  addRemoveLinks: 'dictRemoveFile'

And it doesn't work (all uploaded files are broken). I know I need to do something like this:

xhr.send file

But I don't know where to put this call. How can I override the send behavior of Dropzone?

Ajax request to php from angular js

I am trying make an ajax request to php from angular js. But I am not getting the data I have sent. Please let me know where I am going wrong.

The following is the ajax call.

<script type="text/javascript">

    angular.module('app', []).controller("MyController", function($scope, $http) {

    var req = {
        method: 'POST',
        url: 'pujastrail/www/rest/get.php',
        headers: {
            'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
        },
        data: { lang: "fr" }
    }
    $http(req).success(function(data, status, headers, config){alert("done"+data);}).error(function(data, status, headers, config){alert("error"+res);});

        });
</script>

The following is the php code.

<?php
    if (isset($_POST['lang']) && !empty($_POST['lang'])) {
        $lang = $_POST['lang'];//this needs to be sent back to js file
    } else {
        $lang = "eRROR";// but this is being sent back to the js file
    }

    echo (json_encode($lang));
?>

I have tried this using $_REQUEST also but it didnot work.

Rails Form_Tag Ajax Format.js ActionController::UnknownFormat

I have a form_tag for sending an email and I want to use AJAX, so that only the form could update and the rest would look the same.

contact.html.erb

<%= form_tag(site_contact_path, remote: true, class: 'response form-horizontal', authenticity_token: true) do %>
        <h2 class="contact-title">Parašykite mums</h2>
        <div class="form-group">
          <label class="control-label col-sm-4" for="name">Vardas</label>
          <div class="col-sm-8">
            <%= text_field_tag 'name', nil, placeholder: 'Įveskite vardą', class: 'form-control', autocomplete: 'on' %>
          </div>
        </div>

        <div class="form-group">
          <label class="control-label col-sm-4" for="email">El. paštas</label>
          <div class="col-sm-8">
            <%= text_field_tag 'email', nil, placeholder: 'Įveskite el.paštą', class: 'form-control', autocomplete: 'on' %>
          </div>
        </div>

        <div class="form-group">
          <label class="control-label col-sm-4" for="comment">Komentarai</label>
          <div class="col-sm-8">
            <%= text_area_tag 'comment', nil, placeholder: 'Jūsų komentaras', class: 'form-control', autocomplete: 'on', rows: '6' %>
          </div>
        </div>
        <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
        <div class="button-holder"> 
            <%= submit_tag 'Siųsti', class: 'submit' %>
        </div>
        <div class="hidden">
            <p>Ačiū! (Mes pasistenksime atsakyti Jums, kuo greičiau)</p>
        </div>
    <% end %>

routes.rb

post '/contact' => 'site#contact_send_email'

site_controller.rb

def contact_send_email
@name = params[:name]
@email = params[:email]
@comment = params[:comment]

ContactMailer.send_message(@name, @email, @comment).deliver

respond_to do |format|
    format.js
end
end

contact_send_email.js.erb

$('.form-group').hide();
$('.button-holder').hide();
$('.hidden').show();

log

 ActionController::UnknownFormat (ActionController::UnknownFormat):  app/controllers/site_controller.rb:24:in `contact_send_email'

When I press the submit button, the email is send but it seems contact_send_email action can't find contact_send_email.js.erb for some reason or doesn't understand format.js I've tried searching for similar problem on StackOverflow but the solutions didn't seem to make any effect.