samedi 9 mai 2015

Rewrite Javascript to jQuery with Ajax

I'm totally new to jQuery and I need to rewrite this bit of javascript to jQuery. Can you help me out? Is this correct?

Javascript:

var xmlHttpRequest = new XMLHttpRequest();

function getTasks(){
var name=document.getElementById("name").value;
var summary=document.getElementById("summary").value;
    if (xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
        {
            document.getElementById("open").innerHTML=xmlHttpRequest.responseText;
        }
  xmlHttpRequest.open("Post","jsontaskmanager?name=" + name + "&summary=" + summary, true);
  xmlHttpRequest.send();
}

jQuery:

var xmlhttp = new XMLHttpRequest();

$("document").ready(function(){
    var name = $("name").val();
    var summary = $("summary").val();
    //blah
    $.ajax({
        url: "jsontaskmanager",
        type: "POST",
        dataType: "json",
        data: { name: name, summary: summary },
        success: function(response) {
            $("open").html(response);
        }
    });
});

Redner jade block in specific div - node.js

My problem is that I have to render specific block in div #test by ajax. Is it somehow possible?

I also tried to use case statement in jade file ->

block main
  - var friends = 10
  case friends
    when 0
      block test
    default
      block test1

but after any change in JS i could not refresh just "main" block.

Any suggestions?

I have one file with a big amout of blocks and I want to control rendered blocks by changing it in js and ajax refreshing. Other method is the first one i mentioned - rendering specific block in div using ajax.

Sending form using Ajax - Spring MVC

I have problems with sending my form using Ajax.

Here is form:

<form method="POST" id="add-card-form" action="${pageContext.request.contextPath}/card/add" class="form-horizontal">
 <select name="type" class="form-control">
    <c:forEach items="${cardTypes}" var="cardType">
       <option value="${cardType.id}">${cardType.name}</option>
    </c:forEach>
 </select>
 <select name="category" class="form-control">
    <c:forEach items="${cardCategories}" var="cardCategory">
       <option value="${cardCategory.id}">${cardCategory.name}</option>
    </c:forEach>
 </select>
<textarea type="text" name="description" class="form-control" rows="6"></textarea>
 <input type="submit" id="add-card-submit" value="Add card" class="btn btn-primary"/>

Here is Ajax function:

$(document).on('submit', '#add-card-form', function(e) {
    var frm = $('#add-card-form');
    e.preventDefault();

    var Form = this;
    var data = {};

    $.each(this, function(i, v){
        var input = $(v);
        data[input.attr("name")] = input.val();
        delete data["undefined"];
    });

    //temporary solution
    data["type"] = parseInt(data["type"]);
    data["category"] = parseInt(data["category"]);

    console.log(data);
    if(frm.valid()) {
        $.ajax({
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: JSON.stringify(data),
            success:  reloadBoard,
            error: function (callback) {
                console.log(callback);
            }
        });

        refreshForm(frm);
    }
});

And here is a controller action:

@RequestMapping(value="/add", method = RequestMethod.POST)
public @ResponseBody Card addCard(@RequestBody Integer type,
                                  @RequestBody Integer category,
                                  @RequestBody String description) {

    Card card = new Card();

    card.setType(cardTypeService.findById(type));
    card.setCategory(cardCategoryService.findById(category));
    card.setDescription(description);
    card.setOwner(1);

    cardService.saveCard(card);

    System.out.println("Card with id " + card.getId() + " added!");

    return card;
}

Variable data values:

Object {type: 1, category: 1, description: "New Card"}

When I try to send this form I always get error 400: http://localhost:8080/card/add 400 (Bad Request)

Can you tell me what is wrong with this code? I've ridden few posts, articles about sending data using Spring MVC + Ajax but no one helped.

How to do load() on ajax loaded images?

want to do nice image loading, but my images are loaded by ajax (prepend). How to do load() on each image. I want it to load one by one, order doesn't matter. Before image load I want some loading gif.

Here is what I tried:

.done(function( data ) {
        var obj = JSON.parse(data);
        for(i = 0; i < obj.length; i++)
            if(obj[i].indexOf("blank.gif") > -1)
                continue;
            else
                $("#images_for_this_gallery").prepend("<div id='fd_" + i + "' class='featured_image_div'>" +
                "<span class='imageloading'>loading</span>"    + //LOADING MEESAGE FOR EACH IMAGE
                "<img class='images' src='" + image_path +  obj[i] + "' />" + // IMAGE FOR NICE LOAD
                "<a href='#' id='" + obj[i] + "' class='image_delete'>X</a>" +
                "</div>").hide();
    });

And here is my attempt:

$(".images").each(function() {
        if (this.complete) {
            // this image already loaded
            // do whatever you would do when it was loaded
        } else {
            $(this).load(function() {
                $(".imageloading").hide();
                $(this).show();
            });
        }
    });

Here is another attempt:

$(function() {
        $(".images").load(function(){
            $(".imageloading").hide();
            $(".images").show();
        });
    });

It works on normal image but not on ajax generated image...

Thank you!

Getting a mysqli_num_rows() error for no reason?

So basically, this is my situation right now. I am using xampp(apache friends) for my localhost and I am currently in the process of building a simple chat room windows using AJAX and PHP. Currently, I have two files and those are C:/xampp/htdocs/AJAX CHAT/index.php and C:/xampp/htdocs/AJAX CHAT/chat.php.

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://ift.tt/kkyg93">
<html xmlns="http:http://ift.tt/lH0Osb">

<head>
  <meta http-equiv="Content-Type" content="text/html" />
  <title>Deontray's Chat Room!</title>

  <script src="jquery-1.7.2.js" type="text/javascript"></script>
  <script type="text/javascript">
    function chat_initial() {
      var user = document.getElementById("chat_user").value;

      $.post('./chat.php', {
        stage: "initial",
        user: user
      }, function(data) {
        alert(data);
      });

      /*
                                get user
                                check if taken
                                hide the initial div
                                display the primary div
                                */
    }
  </script>

  <style type="text/css">
    <!-- #chatbox {
      background-color: #DDD;
      border: 1px solid #000;
      width: 700px;
      height: 500px;
    }
    #chatbox #initial {
      text-align: center;
      margin: auto;
      width: 250px;
      padding-top: 100px;
    }
    -->
  </style>
</head>

<body>

  <div id="chatbox">

    <div id="initial">

      <table>
        <tr align="center">
          <td>Enter a username to start chatting:</td>
        </tr>
        <tr align="center">
          <td>
            <input type="text" name="chat_user" id="chat_user" style="width: 200px;" />
          </td>
        </tr>
        <tr align="center">
          <td>
            <br />
            <input type="button" value="Enter chat!" onClick="chat_initial();" />
          </td>
        </tr>
      </table>

    </div>

    <div id="primary"></div>

  </div>


</body>

</html>

chat.php

<?php
//connect to MySQL database
        mysqli_connect("localhost", "root", "deontray");
        mysqli_select_db("tutorials");

//read the stage
        $stage = $_POST['stage'];
//primary code
        if($stage == "initial"){
                //check the username
                $user = $_POST['user'];
                
                $query = mysqli_query("SELECT * FROM `chat_active` WHERE user = '$user'");
                if (mysqli_num_rows($query) == 0){
                        $time = time();
                        //
                        mysqli_query("INSERT INTO `chat_active` VALUES ('$user', '$time')");
                        //set the session
                        $_SESSION['user'] = $user;
                        
                        echo "good";
                }
                else
                        echo "Username Taken";
        }
        else
                echo "Error.";
?>
This is my error: Warning: mysql_num_rows expects parameter 1 to be resource, boolean given.

calender extender not working in ASP.NET

I am trying to add

Calender Extender using AJAX

on my web application. I am trying to popup calnder on click of textbox I have tried all steps as mentioned here in this example

I have redownloaded AJAX TOOLKIT 4.5 and psted it in bin folder. But nothing happens my codes are

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

.

<asp:TextBox ID="txtfrom" runat="server"></asp:TextBox>
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajax:ToolkitScriptManager>
<ajax:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtfrom" PopupButtonID="txtfrom"></ajax:CalendarExtender>

So let me know what I a missing here.

Thanks

Long running Ajax request blocking short Ajax status updates

I have a ASP.NET MVC application running on IIS. I have the following handlers /DoWork (lets say it takes 10 minutes) and /ReportStatus (lets say it takes <1s). DoWork does the work while ReportStatus returns the progress of the work.

I wanted to asynchronously run the /DoWork by running $.ajax request from Javascript on it and then monitor its progress by repeatedly querying the /ReportStatus also through asynchronous $.ajax wrapped in function registered in window.setInterval. However, what I am seeing is that the long running $.ajax on /DoWork blocks all the other queries on /ReportStatus until it the DoWork finishes.

How do I circumvent this? I would guess that this has to do with IIS server setting possibly denying two active requests from one host? Any ideas?

My first idea is to have the /DoWork run the actual work in background asynchronous thread and immediately return. However I would like to know if there are better options as I want to keep the connection open during the /DoWork run.

Small JS loop issue

I have a script that calls data from a database. For every result a new div is output. However when the button that calls the function search() is clicked, I only get one result. I guess the question is: how do I create a new div for every result, not just set it to the first row found?

function search()   {
    var xhr2 = new XMLHttpRequest();
    xhr2.addEventListener ("load", view);
    var reg = document.getElementById("type").value;
    xhr2.open("GET", "getresults.php?type=" + reg);
    xhr2.send();
}
function view(e, resulthtml)    {
    var array = JSON.parse(e.target.responseText);
    for (var count=0; count<array.length; count++)
    {
    var id = array[count].id;
    var username = array[count].username;
    var srcpath = array[count].srcpath;
    var title = array[count].title;
    var type = array[count].type;
    var postcode = array[count]. postcode;
    var description = array[count]. description;
    var price = array[count].price;
    var phone = array[count].phone;
    var lat = array[count].lat;
    var lon = array[count].lon;

    resulthtml =          "<div class='col-md-4'>"
                + "<div class='thumbnail'>"
                + "<img id='a' class='a' alt='300x200' src='" + srcpath + "'>"
                + "<div class='caption'>"
                + "<h3>"
                + description
                + "</h3>"
                + "<p>"
                + "£" + price + ""
                + "</p>"
                + "<p>"
                + "Contact number:"
                + "</p>"
                + "<p>"
                + "<input type='submit' value='Contact seller' onclick='search()'/>"
                + "</p>"
                + "</div>"
                + "</div>"
                + "</div>"

    }
    document.getElementById("row").innerHTML = resulthtml;
}   


</script>

History API - Ajax pages + Json

I have a structure of my site like this IMAGE
I'm trying to create some page transition with ajax & history API

CODE:

history.pushState(null, null, "/members/" + dataLink + ".php" ); // update URL
console.log(dataLink);
$(".ajax-container").load('/members/single.php', function(){
     fillPage(dataLink); // load datas from json
});

Everything works fine, I can load the page correctly with datas but now I have to implement the behavior of the back button (using history api / popstate )but I've no idea how to do that because every member-page in filled with data from json.

$(window).bind('popstate', function() {
 // what inside here? It should call the previous page + the data from json like the previous ajax call
});

Any ideas?

Need help iterating through a complex Json (no jquery)

I need to create a symfony2 bundle that generates a sidebar from a YAML file

I created this YAML structure

Sidebar:
  - Frontpage:
        - Dashboard:
            _icon: 'icon-home'
            _route: 'link'
  - Actions:
          - My_Likes:
              _icon: 'icon-dislike'
              _route: 'link'
          - My_Dislikes:
              _icon: 'icon-home'
              _route: 'link'
  - Interests:
          - Add_Interest:
              _icon: 'icon-home'
              _route: 'link'

which returns this JSON as a response.

{
  "Sidebar": [
    {
      "Frontpage": [
        {
          "Dashboard": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    },
    {
      "Actions": [
        {
          "My_Likes": {
            "_icon": "icon-dislike",
            "_route": "link"
          }
        },
        {
          "My_Dislikes": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    },
    {
      "Interests": [
        {
          "Add_Interest": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    }
  ]
}

Using ajax, the json is returned on the 'data' variable on the client side

Sidebar.model.request(function(data)
{ 
    for(var a=0; a< data.Sidebar.length; a++ )
    {
       console.log(data.Sidebar[a]);
    }
});

I need to find a way to iterate through the parents and find the corresponding children. I only need help creating the for loop, so a solution using console.log(data[stuff]); would be enough


EDIT: here is the adjusted snippet of Daniel Rosano's code

    Sidebar.model.request(function(data)
    { 
        //Get Sidebar items
        var SidebarItems = data.Sidebar;

        //Find Categories in Sidebar Items
        for(var a=0; a< SidebarItems.length; a++ )
        {
            var category = SidebarItems[a];

            //Get Category name and append it to sidebar
            var category_name = getSubitemName(category);
            Sidebar.view.renderCategory(category_name);

            //find subitems in categories
            for(var b=0; b < category[category_name].length; b++)
            {
                var button = category[category_name][b];
                var button_name = getSubitemName(button);

                var button_attributes = button[button_name];

                console.log(button_attributes['_icon']);
                Sidebar.view.renderButton(button_name);
            }
        }

        function getSubitemName(parent)
        {
            for(child in parent)
            {
                return child.toString();
            }
        }
    });

this is the result, thanks Daniel

Obviously incomplete but this is the result

Update value during AJAX request

I've recently been working on a shoutbox that refreshes every 3 seconds but I want the time values to update every time the request was finished. So if the value was "3 seconds ago" I want it to show "6 seconds ago". At the moment it is able to load new messages but it doesn't update the value itself. I've tried it myself as well as you can see on line 12.

function readChatMessages() {
$.ajax({
    url: "/inc/player_chat_output.php?latestid=" + lastid
}).done(function(data) {
    var obj = JSON.parse(data);
    for(var i = 0; i < obj.length; i++)
    {
        lastid = obj[i].id;
        $("#chatbody").prepend("<tr class='chatrow'><td><a href='/user/" + obj[i].author + "'>" + obj[i].author + "</a></td><td>" + obj[i].message + "</td><td id='chatrowtime-" + obj[i].id + "'>" + getJSAgoFromUNIX(obj[i].date) + "</td><br></tr>");
        document.getElementById("chatrowtime-" + obj[i].id).innerHTML = getJSAgoFromUNIX(obj[i].date);
        $(".chatrow").each(function(index) {
            document.getElementById("chatrowtime-" + obj[i].id).innerHTML = getJSAgoFromUNIX(obj[i].date);
            if(index > 14)$(this).remove();
        });
    }
});

}

Database entering blank data from Facebook using AJAX Post & PHP

I’m creating a Facebook Canvas game, and up until now I have been hosting it on my laptop at localhost, along with my database which was also hosted locally using phpMyAdmin. I’m now moving both online and have encountered a problem with the database.

When I hosted it locally, I was able to grab details about the player (their Facebook ID, first name, last name, email, gender) and insert that data as a row into my database whenever the player loaded the homepage. This worked without any problems on localhost.

However, since I moved it online, it’s inserting blank fields instead of Facebook data. The online database is connecting correctly, and it will enter other values if I write them directly into the Insert statement in my .php script. I think the problem may be to do with the AJAX post I’m using.

I’m calling a Javascript function onload of the homepage, this runs the following piece of code:

function getUserDetails() {

FB.login(function(response) {
  if (response.authResponse) {
    console.log('Welcome!  Fetching your information.... ');

     FB.api('/me', function(response) {

     if (response.error) {
       console.log('Error - ' + response.error.message);
     }
     else {
       var userid = response.id;
       var userfirst_name = response.first_name;
       var userlast_name = response.last_name;
       var useremail = response.email;
       var usergender = response.gender;

       $.ajax({
         url: 'scripts/php_scripts/insertuserdetails.php',
         data: {'userid' : userid,
               'userfirst_name' : userfirst_name,
               'userlast_name' : userlast_name,
               'useremail' : useremail,
               'usergender' : usergender},
        type: "POST",
        success: function(response){

                 if(response==1){
                         alert( "Insert worked!");
                         }
                    else{
                       alert( "Insert failed!" );
                              }
                    }
       });
     }
    });
  } else {
    console.log('User cancelled login or did not fully authorize.');
  }
 }, {scope: 'email'});
}

And the PHP file it posts to is this:

<?php 

session_start();

require_once 'facebook-php-sdk-v4-4.0-dev/autoload.php';

use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookSignedRequestFromInputHelper;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;

FacebookSession::setDefaultApplication('myappid', 'myappsecret');

$servername = "myservername";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$userid = $_POST['userid'];
$userfirst_name = $_POST['userfirst_name'];
$userlast_name = $_POST['userlast_name'];
$useremail = $_POST['useremail'];
$usergender = $_POST['usergender'];

$sql = "INSERT INTO player (fb_id, f_name, l_name, email, gender) VALUES 
('$userid', '$userfirst_name', '$userlast_name', '$useremail', '$usergender');";
$sql .= "INSERT INTO bank (fb_id, cb, gb, invite)
VALUES ('$userid', '200', '0', '');";

$result = mysqli_multi_query($conn, $sql);
if ($result) {
   $verify=1;
}
else{
  $verify=0;
}
echo $verify;

mysqli_close($conn);

?>

I don’t understand why everything is working correctly except for the blank values for the Facebook data (for example, the ‘200’ and ‘0’ are getting inserted correctly). Is it possible that the Insert statement is firing before the Facebook data arrives? And if so, how could this be an issue when it's hosted online but not be an issue when it's hosted locally?

Thanks for any help in advance!

How to add a Facebook ticker to my website

I want a Facebook ticker on my website. I want the ticker to display comments that have been posted on my wall.

Has anyone done this before and able to help? Or is there a generator?

How to automatically validate coupon and adjust price?

I'm trying to add a coupon to my checkout page, using an AJAX request that validates the coupon and updates the price accordingly. However, on loading the checkout view I get the error message wrong number of arguments (4 for 1..2) referring to the line <%= form_for @actioncode, method="post" ... in the form where the coupon is entered. I've tried to follow the steps here. How should I adjust my code?

The checkout view contains the following form:

<%= form_for @actioncode, method="post", url="check_actioncode_path", remote: true do |f| %>
  <%= f.text_field :coupon_code, :placeholder => "Enter your coupon" %>
  <%= f.submit "Submit Coupon Code" %>
<% end %>

Routes:

post 'check_actioncode' => 'actioncodes#check_actioncode'

In actioncodes controller I have:

def check_actioncode
  @actioncode = Actioncode.find(params[:actioncode])
  respond_to do |format|
    if !@actioncode.nil?
      format.js   {}
    else
      flash.now[:success] = "Action code not found or expired"
    end
  end
end

I'm still trying to build the javascript itself. I try to adjust code from http://ift.tt/1InTN92 but am unsure how to do so.

<script language = "javascript">
<!--
function validate(coupon_code) {
// Somehow check if coupon_code matches one of the actioncodes in the Actioncode model (has a column 'actioncode')
if (...)
 {
 window.alert("Action Code Accepted! Click the Buy Now button to finalize the payment");
 }
// If no match found.
if (...)
 {
 window.alert("Sorry, The Action Code you entered is invalid. Please check and try again!");
 }
}

function CalculateOrder(form) {
 // Will have to change the code below to apply the discount: each actioncode in the Actioncode model has a value in the the column 'discount' (a percentage discount).
 if (form.coupon_code.value == "GOLD20")
 {
 form.discount_rate.value = "...";
 form.discount_rate2.value = "...";
 form.on3.value = "Coupon Entered";
 form.os3.value = "...% Discount Applied";
 }
}
//-->
</script>

Ajax call taking to failure block for php service

I have created a web service using php and when I access from a rest client I get the proper JSON response. I am calling the method from ajax call integrated in a drupal site. the service response is HTML hence it is going to error block.

PHP CODE:

$api_response = array('result' => 1, 'message' => 'Successfully user added!');
        header("Content-Type: application/json; charset=utf-8");
        $json_response = json_encode($api_response);
        echo $json_response;

JS CODE:

$.ajax({
        url:'http://localhost:8888/testService.php',
        type: 'GET',
        dataType:'json',
        success: function(data) {
          console.log("SUCCESS DATA");
        },
        error: function(error) {
          alert("ERROR OCCURED 123");
        }
      });

Help appreciated

JSF invalid behavior with jstl foreach with different jsf version

I am not really sure how should I describe the problem. I am currently learning JSF, and today tried to implement something like ajax reloaded table with pagination.

Here is my code in JSF:

<c:forEach var="pageNo" begin="0" end="${adapter.pagesNumber}">
<c:choose>
    <c:when test="#{adapter.currentPage == pageNo}">
        <li class="active"><h:commandLink value="#{pageNo+1}" disabled="true" /></li>
    </c:when>
    <c:otherwise>
        <li><h:commandLink value="#{pageNo+1}" action="#{adapter.setCurrentPage(pageNo)}">
                <f:ajax render=":#{cc.attrs.tableId} @form" />
            </h:commandLink></li>
    </c:otherwise>
</c:choose>

And I am using JSF from:

<dependency>
     <groupId>org.glassfish</groupId>
     <artifactId>javax.faces</artifactId>
 </dependency>

My intention was to have buttons with page numbers, with currently active page button highlighted and disabled (no same page reloading).

Now, first screenshot shows my view before any action: (first page): enter image description here

Lets say I clicked on page number 6,

And now, when I use JSF with version

     <version>2.2.4</version>

I got expected result: enter image description here

But when I switch on versions above e.g.

     <version>2.2.5</version> // tested up to 2.2.11

I'm getting something like this: enter image description here

After I've clicked on page no 9 i got another "pagination" sequence:

1 2 3 4 5 7 8 9 6 10 11

but the current page in left bottom corner says it's 9th page. Table content is valid too.

Does anyone have ever faced with situaton like this or what am I doing wrong, if the same code works totally different with different JSF versions? What can be a reason of such weird behavior?

Getting PHP to change a text file via AJAX without refreshing the page

I'm developing a simple site for Year 12 IT, and what it needs to do is sell coffees (or at least give the appearance, we aren't actually selling anything). When orders are submitted, they get converted to PHP variables and then laid down as a brief order summary; a summary of that order gets posted to a text file. All good so far.

The problems come in when I try to clear the text file/"confirm the orders" (post the file contents to a log and then clear the file itself). Using pure PHP (writing both as submit buttons, checking for isset(), and then using file_get_contents()) works perfectly, but forces a page request that also resubmits the most recent order. Using mixed AJAX/PHP lets me create nice little notifications for cleared/confirmed orders and is supposed to refresh specific page areas and avoid resubmits, but for some reason full refreshes and resubmits still happen. Why?

PHP:

<?php

$txtManip = $_REQUEST['txtFunk'];

if($txtManip == "clear"){
    file_put_contents('orders.txt', '');
}

if($txtManip == "confirm"){
    $n = 1;
    $custNum = $n++;

    $confirmedOrders = "Customer " . $custNum . " " . "ordered " . file_get_contents('orders.txt') . "\n";
    file_put_contents('log.txt', $confirmedOrders, FILE_APPEND | LOCK_EX);
    file_put_contents('orders.txt', '');
}
?>

Javascript:

clearButton.addEventListener('click', notifyClear);
confirmButton.addEventListener('click', notifyConfirm);

function orderCleared(){
    orders.style.display = "block";
    orderScrollText.innerHTML = "Order another coffee";
    orderShifter.removeEventListener('click', orderDisp);
    orderShifter.addEventListener('click', orderHide);
}

function notifyClear(){     
    ajaxTime.onreadystatechange = function(){
        if (ajaxTime.readyState == 4 && ajaxTime.status == 200){
            notification.style.display = "flex";

            setTimeout(function(){
                    notifyBox.style.display = "none";
            }, 4000);

            notifyText.innerHTML = "Cleared!";
        }
    }
    ajaxTime.open("POST", "notepadControl.php", true);
    ajaxTime.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    ajaxTime.send("txtFunk=clear");

    /*$.ajax({
        url: "notepadControl.php",
        data: clear,
        type: "post",
        success: function(output){
            alert (output);
        }
    })*/

    setTimeout(function(){
        orderCleared();
        window.location = "http://ift.tt/1EqAFzZ";
        location.reload();
    }, 5000);
}

function notifyConfirm(){   
    ajaxTime.onreadystatechange = function(){
        if (ajaxTime.readyState == 4 && ajaxTime.status == 200){
            notification.style.display = "flex";

            setTimeout(function(){
                    notifyBox.style.display = "none";
            }, 4000);

            notifyText.innerHTML = "Confirmed Orders";
        }
    }
    ajaxTime.open("POST", "notepadControl.php", true);
    ajaxTime.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    ajaxTime.send("txtFunk=confirm");

    setTimeout(function(){
        orderDisp();
        window.location = "http://ift.tt/1EqAFzZ";
    }, 5000);
}

HTML:

<div id="showOrders">
    <p class="whiteText" id="orderScroller">See Orders</p>
</div>

<div id="subbedOrders">
    <iframe id="orderList" src="orders.txt" ></iframe>
    <form method="post">
        <input type="button" id="clearOrders" method="post" name="clear" value="Clear Orders" />
        <input type="button" id="orderConfirm" method="post" name="confirm" value="Confirm Orders" />
    </form>

    <div id="notifyBox">
        <p id="notifyText" class="whiteText"></p>
    </div>
</div>

<script src="milk.js"></script>

In other words, I want something that will empty my text file without resubmitting any data or refreshing the whole page :). JQuery and your pet libray are all fine, so long as the final solution works. Obviously I'm using AJAX, since it's supposed to be the only way to do this. More secure things are preferred, so anything that keeps a most of the work server-side will make me happy. Thanks in advance!

How to open a file from WebAPI where in server accepts specific Header

I am trying to download a document from a webAPI. The URL I am trying to bind to a link, but url also takes Accept header.

How to pass in the Accept header along with the request?

I have seen this link but am not able to figure out how to set Header when binding webAPI URL to a link in html. (I would prefer not to use File downloader for now).

Ajax file upload progress

Well, I am trying to implement file upload with Ajax and Php in my local apache server.

strong text

     $('.uploadButton').click(function(){
                    var formData = new FormData($(this).closest('.fileUploadForm'));
                    $.ajax({
                        url: 'upload.php',  //Server script to process data
                        type: 'POST',
                        xhr: function() {  // Custom XMLHttpRequest
                            var myXhr = $.ajaxSettings.xhr();
                            if(myXhr.upload){ // Check if upload property exists
                                myXhr.upload.onprogress = function(e) {
                                    $('progress').attr({value:e.loaded,max:e.total});
                                    $(".progress-bar span").css('width',e.loaded);
                                };
                            }
                            return myXhr;
                        },
                        error: function(xhr,status,error)
                        {
                            //$('.progressBarDiv progress').hide();
                            console.log('Error '+xhr+"  "+status+"  "+error);
                        },
                        data: formData,
                        cache: false,
                        contentType: false,
                        processData: false
                    });

PHP CODE

  <?php

    $folder = "upload/";
    $path = $folder . basename( $_FILES['file']['name']); 

    if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
    echo "The file ".  basename( $_FILES['file']['name']). " has been uploaded";
    } else{
    echo "There was an error uploading the file, please try again!";
    }
   ?>

Error

<b>Notice</b>:  Undefined index: file in <b>C:\Users\gopir\Server\Apache24\ 
\htdocs\front-page\upload.php</b> on line <b>4</b><br /><br />
<b>Notice</b>:  Undefined index: file in <b>C:\Users\gopir\Server\Apache24 
\htdocs\front-page\upload.php</b> on line <b>6</b><br />
 There was an error uploading the file, please try again!   success

Line that caused error is:

  var formData = new FormData($(this).closest('.fileUploadForm'));

If i change this line to

 var formData = new FormData($('form')[0])

program works fine.

I can able to see the form data in the console by setting breakpoints in my js. I don't know how to solve this.

I am changing this to achieve multiple file upload functionality.

Please let me know how do i solve this issue. Thanks

HTML

  <form enctype="multipart/form-data" class="fileUploadForm" >
        <div class="uploadDiv"> 
            </div>
            <div class="progressUploadDiv">     
                <div class="uploadButton">Upload</div>
            </div>  
        </div>
    </form>

AngularJS: Custom directive doesn't get compiled

I want to disable a button while a factory AJAX request is running (after the button was clicked) in a generic way and I used this SO answer as a starting point on how to do that, but I can't get my custom directive click-disable to execute the controller method (using ng-click works fine).

I suspect my directives doesn't get "compiled" at page load, directives with simple templates also don't seem to work.

js/services.js:

var raspiSurveillanceServices= angular.module('raspiSurveillanceServices', ['ngResource']);

raspiSurveillanceServices.factory('Camera', ['$resource',
    function($resource) {
        return $resource('/api/cameras/:id');
    }]);

js/directives.js:

var raspiSurveillanceDirectives = angular.module('raspiSurveillanceDirectives', []);

raspiSurveillanceDirectives.directive('clickDisable', function() {
    return {
        restrict: 'A',
        scope: {
            clickDisable: '&'
        },
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.prop('disabled', true);

                scope.clickDisable().finally(function() {
                    element.prop('disabled', false);
                });
            });
        }
    };
});

js/controllers.js:

raspiSurveillanceControllers.controller('CameraListCtrl', ['$scope', 'Camera', function ($scope, Camera) {

    $scope.cameras = Camera.query();

    $scope.deleteCamera = function(camera) {
        return Camera.delete({ id: camera.id}).$promise.then(
            function(value) {
                // Remove item from array
                var index = $scope.cameras.indexOf(camera);
                $scope.cameras.splice(index, 1);
            },
            function(error) {
                alert("Delete failed");
            }
        )
    };

}]);

js/app.js:

var raspiSurveillanceApp = angular.module('raspiSurveillanceApp', [
  'raspiSurveillanceControllers',
  'raspiSurveillanceServices',
  'raspiSurveillanceDirectives',

  'xeditable'
]);

.blade.php:

<tr ng-repeat="camera in cameras">
    ...
    <button class="btn btn-danger" click-disable="deleteCamera(camera)">Delete</button>
</tr>
...
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-resource.min.js"></script>

<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/directives.js"></script>

Selecting a radio button when clicking an image

I want to select radio button when I click on his image but it's not working. This is what I've tried:

<ul id="options-31-list" class="options-list">
    <li>
        <a id="customoptions_image_0_0" class="mydata" title="" href="getImage/big/1/group_id/options/option_id/31/value_id/84/file/o2.jpg/" data="84">
            <img class="small-image-preview v-middle" title="" src="getImage/group_id/options/option_id/31/value_id/84/file/o2.jpg/">
        </a>
        <input id="options_31_2" class="radio validate-one-required-by-name product-custom-option" type="radio" data="84" value="84" name="options[31]" onclick="opConfig.reloadPrice();">
    </li>
    <li>
        <a id="customoptions_image_0_0" class="mydata" title="" href="getImage/big/1/group_id/options/option_id/31/value_id/85/file/vodafone.jpg/" data="85">
            <img class="small-image-preview v-middle" title="" src="getImage/group_id/options/option_id/31/value_id/85/file/vodafone.jpg/">
        </a>
        <input id="options_31_3" class="radio validate-one-required-by-name product-custom-option" type="radio" data="85" value="85" name="options[31]" onclick="opConfig.reloadPrice();">
    </li>
    <li>
        <a id="customoptions_image_0_0" class="mydata" title="" href="getImage/big/1/group_id/options/option_id/31/value_id/86/file/t-mobile.jpg/" data="86">
            <img class="small-image-preview v-middle" title="" src="getImage/group_id/options/option_id/31/value_id/86/file/t-mobile.jpg/">
        </a>
        <input id="options_31_4" class="radio validate-one-required-by-name product-custom-option" type="radio" data="86" value="86" name="options[31]" onclick="opConfig.reloadPrice();">
    </li>
</ul>

I have the same data="" attribute for both: for image and for input, is there any way to make the input (that radio) to be checked when I click on image?

Thank you

Load Javascript after AJAX-fetched HTML is fully loaded

I have a situation where the HTML part is loaded with AJAX into a DIV with ID="dynamic content" using main.js script. This script is situated inside the HEAD part of main.php and it goes like this:

$.ajax({
            url: 'content.php',
            success: function(output){

                $('#dynamic-content').html(output);
            }       
    });

The Javascript file responsible for controlling that content is situated in another JS file named secondary.js. This file is placed just before the closing of BODY again inside main.php.

main.php Document Structure:

<html>
  <head>
    <script type="text/javascript" src="js/main.js"></script>
  </head>

  <body>
    ....
    <div id="dynamic-content"></div>
    ....
    ....
    <script type="text/javascript" src="js/secondary.js"></script> 
   </body>
</html>

Sometimes the content of content.php is too large, and secondary.js file loads before the content is fully loaded. Hence some elements are not targeted and i have problems.

Is there a way for me to delay for 1-2 seconds the execution of secondary.js, just to make sure that the content is fully loaded?

ps: all above files are hosted on the same server

Thanks in advance.

Pass Stringbuilder message from Json [MVC-Controller]and render it in view

I am trying to pass a StringBuilder message as an extra data back to ajax call but I am failing to manipulate it in client side. Below is the way I append message to StringBuilder and pass it back.

StringBuilder retMessage=new StringBuilder();
retMessage.Clear().AppendLine("Successfully added the user!"); 
//Clear will done only on Success otherwise will append the different errorMessage using AppendLine
return Json(new { result = valid, message = retMessage });

On the ajax Success I tried retrieving it as below but with no success.

 success: function (data) {
              if (data.result) {
                    ResetForm('#frmChangePwd');
                    console.log(data.message);
              },
 }

Below are images showing how it is passed from server side and how it is obtained in client side!!

Server Side return

Server Side return

Client Side retrieval

Client Side retrieval

Can anyone tell me how to retrieve message in client side and display it in view?

How to pass a large json data from view to controller, and save it in the server?

My situation is, i have a file which is formate of .CSV, i use javascript to convert it into json, this is successful.

But in another view, i need this json data in the "data-source",

<div id="map" data-source="/Test/flickr_Test_view.csv"></div>

so i think i should pass this json data from view to controller in ajax, and save this data as a .json file in server, then i can succeed use it above

Can some body help me how to pass a large json data from view to controller? Thank you!

How to empty the GET values from a MySQL/jQuery ajax call

If you do an ajax call to retrieve info from a MySQL database and you time the function so it runs every X seconds, I am a bit confused about where do the GET values reside, in order to empty them.

I have this code in test.js:

var fill = function () {
    $.ajax({
    type: "GET",
    url: "refresh.php",
    dataType: "html",
    success: function( data ) {
    $( "#tb" ).append( data );
        setTimeout( fill, 5000);
        }
 });
 } ;

and in refresh.php I have the SQL query to retrieve the info. After the query, I setting the table like this:

    printf( "<tr><td>".$row['name'].
"</td><td>".$row['surname'].
"</td><td>".$row['phone'].
"</td><td>".$row['date'].
"</td></td></tr>");

How can I stop the table from populating the same row every 5 seconds? I can pass the $row['name'] values to regular php values if needed, but I don't fully get in which moment I should empty them.

Video uploader like Facebook video upload with progress bar

I'm developing a project like facebook for my client and for commercial purpose. I want to add video upload features like facebook video uploading features with progress bar. How will I do that? I have searched in google.com thousands time but I did not get exact idea or jquery plugins. anybody help me. advanced thanks.

formData doesn't work after getting the page with POST

I some a strange problem, when I acess to the page (with code to upload image) by GET method, everything works great. But when I access to the page with the POST method, server receive empty data.

Code:

/* ... */
var files = e.dataTransfer.files;
checkSize(files, function(s, n){
    if(s){
        var data = new FormData();
        data.append('_method', 'upload');

        $.each(files, function(k, v){
            data.append(k, v)
    });
    upload(el, data, m)
}

I think that the problem is in the upper code, buthere is the upload code:

$.ajax({
    url : $(el).parent().attr('action'),
    type: 'POST',
    data: data,
    cache: false,
    dataType:false,
    processData: false,
    contentType: false,
    success: function(data, textStatus, jqXHR){
        /* ... */
    },
    error: function(jqXHR, exception){
        /* ...*/
    }
});

Server is on nodeJs, so here is an result of receiving data after GET method:

body:
{ _method: 'upload' }
files:
{ '0':
   { fieldName: '0',
     originalFilename: 'LAYOUT.png',
     path: 'C:\\Users\\Ivan\\AppData\\Local\\Temp\\5776-1hdql6r.png',
     headers:
      { 'content-disposition': 'form-data; name="0"; filename="LAYOUT.png"',
        'content-type': 'image/png' },
     ws:
      { _writableState: [Object],
        writable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        path: 'C:\\Users\\Ivan\\AppData\\Local\\Temp\\5776-1hdql6r.png',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        pos: undefined,
        bytesWritten: 349600,
        closed: true },
     size: 349600,
     name: 'LAYOUT.png',
     type: 'image/png' } }

And here, data after POST method:

body:
{ req_type: '' }
files:
undefined

Conditional addClass not working for each elements with same class

Les say I have some buttons with same class. On page load I am checking some value using ajax for each button. Depending on returned value of ajax request I want to add some class to the buttons, but it is not working,

$(document).ready(function(){
    $('.add-remove-permissoion').each(function(){
        var child = $(this).val();
        var parent = $('#parent-name').text();
        $.get('my-url'}, function(data){
            if(data == 1){
                $(this).addClass('glyphicon glyphicon-ok');
            }else{
                $(this).addClass('emptybox-blank');
            }
        });
    });
});

I have checked that my ajax request is returning correct data. What is that I am doing wrong here?

pagination links don't display content of next set of results in PHP

I am working on a pagination script to limit the results of a database query returned. The problem is that when the next page link number is pressed, the user is just returned to the original screen with no results displaying. Any help welcome.

Here is the PHP script. Its long, wasn't sure to cut bits or just leave as is.

<?php
session_start();

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

?>

<html>

<head>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="http://ift.tt/1FHelXo">

  <!-- Optional theme -->
  <link rel="stylesheet" href="http://ift.tt/1GSvD1Z">

    <script src="http://ift.tt/1qRgvOJ"></script>

  <!-- Latest compiled and minified JavaScript -->
  <script src="http://ift.tt/19wK3Lg"></script>

  <!-- Include Modernizr in the head, before any other Javascript -->
  <script src="includes/js/modernizr-2.6.2.min.js"></script>

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

  <link href='http://ift.tt/1mbzEpL' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="bootstrap.css">

  <link rel="stylesheet" href="stylez.css">

  <script type="text/javaSript" src = "../jquery.js"></script>

    <script>
  function ajaxFunction(){
  var ajaxRequest;  // The variable that makes Ajax possible!

  try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
  } catch (e){
  // Internet Explorer Browsers
  try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  }catch (e) {
    try{
      ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e){
      // Something went wrong
      alert("Your browser broke!");
      return false;
      }
    }
  }

  // Create a function that will receive data 
  // sent from the server and will update
  // div section in the same page.
  ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('results_box');
      ajaxDisplay.innerHTML = ajaxRequest.responseText;
    }
  }

  // Now get the value from user and pass it to
  // server script.
  var gen = document.getElementById('gen').value;
  var datepicker = document.getElementById('datepicker').value;
  var tab = document.getElementById('tab').value;
  //var datepicker = document.getElementById('datepicker').value;
  var queryString = "?gen=" + gen ;
  queryString += "&datepicker=" + datepicker +"&tab=" + tab;
  ajaxRequest.open("GET", "main.php" + 
                              queryString, true);
  ajaxRequest.send(null); 
  }

  </script>

  <script>

  //-->
  </script>

  <script>
  $(function() {
    $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
  });
  </script>

  <body style="background-color:black">

    <nav class="navbar">
    <div id="custom-bootstrap-menu" class="navbar navbar-static-top" role="navigation">
      <div class="container-fluid">
        <div class="navbar-header"><a><img src="logo1.png" style="width:140px; height:50px" class="navbar-brand" href="index.html"></a>
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
            <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
          </button>
        </div>

        <div class="collapse navbar-collapse" id="myNavbar">
          <ul class="nav navbar-nav navbar-right">
            <li>
              <a href="/">london</a>
            </li>
            <li>
              <a href="/products">YORKSHIRE</a>
            </li>
            <li>
              <a href="/about-us">MIDLANDS</a>
            </li>
            <li>
              <a href="/contact">EAST ANGLIA</a>
            </li>
            <li>
              <a href="/contact">NEWCASTLE</a>
            </li>
            <li>
              <a href="/contact">SOUTH WEST</a>
            </li>
          </ul>
        </div>
    </div>
  </div>
</nav>

  <!-- Full Width Image Header with Logo -->
  <!-- Image backgrounds are set within the full-width-pics.css file. -->
  <header class="image-bg-fluid-height">
    <img class="img-responsive img-center" src="londonb.jpg" alt="">
    <img class="centered" src="lettering.png" style="height:200px; width:60%; margin-top:-300px;">
  </header>



  <div class="container-fluid" style="background-color:#68748D;">
    <br>
    <div class="row">
      <div class="col-md-3">
        <h2><p>Search Events</h2>
      </div>

        <div class="col-md-2">
          <ul class = "nav">              
            <li ><h4>Location:<br></h4>
              <select id='tab' style="background-color:white">
                <option value="London" "Manchester">Choose Location</option>
                <option value="London">London</option>
                <option value="Manchester">Manchester</option>
              </select>
            </li><br>
          </ul>
        </div>

          <div class="col-md-2">
            <ul class = "nav">
              <li><h4>Genre:<br><p></h4>
                <select id='gen' style="background-color:white;">
                  <option value ="">Select</option>
                  <option value="Dance">Dance</option>
                  <option value="Drum n Bass">Drum n Bass</option>
                  <option value="Indie">Indie</option>
                  <option value="Classical">Classical</option>
                  <option value="Opera">Opera</option>
                  <option value="Blues">Blues</option>
                  <option value="Rock">Rock</option>
                  <option value="Punk">Punk</option>
                  <option value="Metal">Metal</option>
                  <option value="Indie">Festivals</option>
                  <option value="Folk">Folk</option>
                  <option value="Acoustic">Acoustic</option>
                  <option value="Pop">Pop</option>
                  <option value="Soul">Soul</option>
                  <option value="Country">Country</option>
                  <option value="Latin">Latin</option>
                  <option value="Jazz">Jazz</option>
                  <option value="Punk">Punk</option>
                </select>
              </li><br>
            </ul>  
          </div>

          <div class="col-md-2">
            <ul class = "nav">  
              <li><h4>Choose Date:<br></h4>
                <input type = "text" id = "datepicker" size="10" style="background-color:white"><br><p>   
              </li>
            </ul>
          </div>

        <div class="col-md-2">
          <ul class = "nav">
            <li><h4>Submit</h4>
              <input type='button' style="background-color:white""color:black" width="80%" class="btn btn-group-sm" onclick='ajaxFunction()' value='Search 4 Live'/><br><p>
            </li>
          </ul>
        </div>
        <br>

    </div>

  </div>

  <br>

  <?php

  mysqli_select_db($con,"ajax");

  if (isset($_GET['gen'])){
    $gen = '%'.$_GET['gen'].'%';
  }

  if (isset($_GET['tab'])){
    $tab = $_GET['tab'];
  }

  if (isset($_GET['datepicker'])){
    $datepicker = $_GET['datepicker'];
  }

  $per_page = 6;

  if (isset($_GET['tab'])){

    $pages_query = mysqli_query($con, "SELECT * FROM $tab WHERE genre LIKE '$gen' AND dateForm = '$datepicker'");
    if(!$pages_query){
      printf("Error: %s\n", mysqli_error($con));
    exit();
    }
    $row = mysqli_num_rows($pages_query);
    $pages = ceil($row) / $per_page;
      $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
    $start = ($page - 1) * $per_page; 
      echo $row;

  $sql="SELECT * FROM $tab WHERE genre LIKE ? AND dateForm = ? LIMIT ?, ?";
  // Prepare, bind, and execute
  $stmt = mysqli_prepare($con,$sql);
  mysqli_stmt_bind_param($stmt, 'ssss', $gen, $datepicker, $start, $per_page);
  mysqli_stmt_execute($stmt);
  $result = mysqli_stmt_get_result($stmt);
  $row = mysqli_fetch_row($result);
  //$pages_query = mysqli_num_rows($result);
  //echo ("-----"),ceil($pages);


  echo "<table  class='table table-hover'><thead>
  <tr>
  <th><h3>Artist</th>
  <th><h3>Location</th>
  <th><h3>Date</th>
  <th><h3>Genre</th>
  <th><h3>Preview</th>
  </tr></thead>";

  ?>

  <?php

  while($row = mysqli_fetch_array($result)) {    
    echo "<tr>";
      echo "<td>" . $row['artist'] . "</td>";
      echo "<td> <b>Venue: </b>" . $row['venue'] . "<p><b>Location: </b>" . $row['location'] . "</td>";
      echo "<td>" . $row['datez'] . "</td>";
      echo "<td>" . $row['genre'] . "</td>";
      echo "<td>" . '<iframe width="100%" height="100" scrolling="no" frameborder="no" src="http://ift.tt/1bFBFZN' . $row['link'] . '&amp;color=000000&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false"></iframe>' . "</td>";
    echo "</tr>";
   } 

  echo "</table>";

  if ($pages >= 1){
    for($x=1; $x<=$pages;$x++){
      echo '<a href="?page='.$x.'">'.$x.'</a>';

    }
  }

}

  ?>

  <div id='results_box'></div>



  <?php



    mysqli_close($con);

  ?>


  </body>

</html>

AJAX Chat Box Scrolling Up Issue

Hi I am writing a chat website and I have a problem with the div containing the messages. In the CSS the div containing the messages has overflow: auto; to allow scroll bars. Now the problem is when ajax is fetching the messages through a PHP script that fetches the messages from the database, you cannot scroll up. The AJAX refreshMessages() function is set to update every second using window.setInterval(refreshMessages(), 1000);. This is what I want but when I scroll up to see previous messages, the scroll bar hits straight back down to the end of the chat due to the AJAX fetch function.

Any ideas of what the issue is?

AJAX Code:

//Fetch All Messages

var refreshMessages = function() {
 $.ajax({
   url: 'includes/messages.inc.php',
   type: 'GET',
   dataType: 'html'
 })

 .done(function( data ) {
    $('#messages').html( data );
    $('#messages').stop().animate({
       scrollTop: $("#messages")[0].scrollHeight
    }, 800);
 })

 .fail(function() {
    $('#messages').prepend('Error retrieving new messages..');
 });
}

EDIT:

I'm using this code but it isn't quite working, it pauses the function but then the function doesn't restart when the scroll bar goes back to the bottom. Help?

//Check If Last Message Is In Focus

var restarted = 0;

var checkFocus = function() {
  var container = $('.messages');
  var height = container.height();
  var scrollHeight = container[0].scrollHeight;
  var st = container.scrollTop();
  var sum = scrollHeight - height - 32;
  if(st >= sum) {
     console.log('focused'); //Testing Purposes
     if(restarted = 0) {
        window.setTimeout(refreshMessages(), 2000);
        restarted = 1;
     }
  } else {
    window.clearInterval(refreshMessages());
    restarted = 0;
  }
}

Pass the current row value of aid from form using ajax

I am working in wordpress and I want to fetch the updated value of aid field from form each time a submit button is pressed. There are two submit buttons and I want the id as per the clicked row

HTML Form(it is shown dynamically with php code)

foreach( $results as $result ) {
$form.= '<form id="voteform" action="" method="post">';
$form.= "<input id='aid' name='aid' type='text' value='$result->aid'>";

$form.=" <input class='star' class='star' id='star5'  type='submit'  name='star5' value='5'>";
$form.=" <input class='star' class='star' id='star6'  type='submit'  name='star5' value='5'></form";

jQuery

$(document).on("click",".star", function(e) {
    e.preventDefault();
var aidd = jQuery("#aid").val();
sentdata =({

            action: 'star',
            aid:aidd,

        })
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
         alert(aid);
            $("#myresult").html(res);

            return false;
        } //end of function
        ,
        'json');    }); //end inner function
}); //end main function

php code

add_action( 'wp_ajax_star', 'star' );
add_action( 'wp_ajax_nopriv_star', 'star');


function star()
{

    $aid = $_POST['aid'];
echo json_encode($aid);
die();
}

AJAX: encoding data obtained by ajax

I have a database with tables in UTF-8. Spring web application connects to a database at jdbc:mysql://localhost:3306/recr?zeroDateTimeBehavior=convertToNull&amp;characterEncoding=utf8&amp;characterSetResults=utf8 All java and jsp files in UTF-8. In header jsp files has a <%@ page contentType="text/html; charset=UTF-8" %>

The page is displayed correctly, but when received by the Ajax data from the server, they are displayed as ?????

javascript

$(document).ready(function() {
        $("#b2").click(function(){
              $.ajax({
                  type: "GET",
                  url: "/recr/getRegion2",
                  data: 'id=3159',
                  contentType: "application/json; charset=UTF-8",
                  dataType: "json",
                  success: function (data) {
                        //var json = jQuery.parseJSON(data);
                        for(var x in data){
                            $('#region').append($('<option>').text(data[x]).attr('value', x));


                            }

                        alert("Data: " + data);
                  },
                  error: function (errormessage) {

                    alert("error" + errormessage);

                  }
              });

Controller

@RequestMapping(value = "/getRegion2", method = RequestMethod.GET)
public @ResponseBody String getRegion2(@RequestParam("id") long id) throws Exception {
    System.out.println("пришло id : " + id);
    List<Region> regions = Facade.getRegionDao(dataSource).getAllRegionsByCountry(id);
    String res = JsonTransformer.transformRegionList(regions);
    return res;

}

What could be the problem?

AJAX calls within MVC and Identity Server

I have been playing with Thinktecture IdentityServer3 and am keen to use it as the product looks great. However, I don't fully understand how to accomplish my flow which is probably fairly common:

  • Create Identity Server using Implicit flow
  • Setup an MVC web site
  • Setup a separate Web API

So far so good, as demonstrated in the examples on the site. I now wish to call the API using AJAX calls directly but for this i need an access token. It seems like a large overhead to have to route these through the MVC site itself (again, in the examples).

How can I accomplish this flow? Would it essentially blend the MVC and Javascript Client samples or is there a smoother way so the user only has to sign in once? Perhaps send the access token in a hidden field but then how would it renew?

Any help on understanding this would be great.

auto suggest search box using php-ajax

i tried a downloaded code for auto-suggest search box but it didn't work..can someone please help me :( it does not display anything from my database..I'm still new in this programming language especially in using ajax and javascript... :( here's my codes:

dbcon2.php

<?php 

$con2['host'] = 'localhost';
$con2['user'] = 'root';
$con2['pass'] = 'thirteen';
$con2['db'] = 'pis';
$sel2 = mysql_connect($con2['host'], $con2['user'], $con2['pass']);
mysql_select_db($con2['db'], $sel2);
mysql_set_charset("utf-8");

$datab2 = $con2['db'];?>

set_creditlimit.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
<html xmlns="http://ift.tt/lH0Osb">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Autocomplete search using php, mysql and ajax</title>
<link rel="stylesheet" type="text/css" href="assets/css/custom.css">
<script type="text/javascript" src="assets/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
    $(function(){
        $(".search").keyup(function()
        {
            var searchid = $(this).val();
            var dataString = 'search='+ searchid;
            if (searchid!='') 
                {
                    $.ajax({
                        type: "POST",
                        url: "search.php",
                        data: dataString,
                        cache: false,
                        success: function(html)
                        {
                            $("#result").html(html).show();
                        }
                    });
                }return false;
        });

        jQuery("#result").live("click", function(e){
            var $clicked = $(e.target);
            var $name = $clicked.find('.name').html();
            var decoded = $("</div>").html($name).text();
            $('#searchid').val(decoded);
        });

        jQuery(document).live("click", function(e){
            var $clicked = $(e.target);
            if (! $clicked.hasClass("search")) {
                jQuery("#result").fadeOut();
            }
        });

        $('#searchid').click(function(){
            jQuery("#result").fadeIn();
        });
    });
</script>
</head>
<body>
<div id="page-wrapper">
    <div id="page-inner">
        <div class="row">
            <div class="col-md-12">
                <h2>ACL</h2>
            </div> <!-- <div class="col-md-12"> -->
        </div> <!-- <div class="row"> -->

        <hr />
        <div class="row">
            <div class="col-md-12">
                <!-- Start of Form -->
                <div class="panel panel-success">
                    <div class="panel-heading">
                         Set-up Allowable Credit Limit
                    </div> <!-- <div class="panel-heading"> -->
                    <!-- End of Heading -->
                    <!-- Start of Body -->
                    <div class="panel-body">
                        <form class="form-horizontal">
                            <div class="row">
                                <div class="col-md-6 col-md-offset-3">
                                    <label>Search Employee:</label>
                                    <input type="text" id="searchid" placeholder="Search Employee" class="search">
                                </div>
                                <div id="result"></div>
                            </div>
                            <br />

                            <!-- ------------- -->

                            <div class="row">
                                <div class="col-md-6 col-md-offset-3">
                                    <label>Position:</label>
                                    <input class="form-control" disabled>
                                </div>
                            </div>
                            <br />

                            <!-- ------------- -->

                            <div class="row">
                                <div class="col-md-6 col-md-offset-3">
                                    <label>Department:</label>
                                    <input class="form-control" disabled>
                                </div>
                            </div>
                            <br />

                            <!-- ------------- -->

                            <div class="row">
                                <div class="col-md-6 col-md-offset-3">
                                    <label>Business Unit:</label>
                                    <input class="form-control" disabled>
                                </div>
                            </div>
                            <br />

                            <!-- ------------- -->

                            <div class="row">
                                <div class="col-md-6 col-md-offset-3">
                                    <label>Allowed Credit Limit:</label>
                                    <input class="form-control">
                                </div>
                            </div>
                            <br />
                            <br />

                            <!-- ------------- -->

                            <div class="control-group">
                                <div class="controls">
                                    <center>
                                        <button class="btn btn-success btn-lg"><i class="glyphicon glyphicon-hand-right fa-1x">&nbsp;Submit</i></button>
                                    </center>
                                </div>
                            </div>

                        </form>
                    </div> <!-- <div class="panel-body"> -->
                </div> <!-- <div class="panel panel-success"> -->
            </div> <!-- <div class="col-md-12"> -->
        </div> <!-- <div class="row"> -->

    </div> <!-- <div id="page-inner"> -->
</div> <!-- <div id="page-wrapper"> -->
</body>
</html>

search.php

<?php

include('dbcon2.php');
if ($_POST) 
{
$q = $_POST['search'];
$sql_res = mysql_query("SELECT emp_id, name from employee3 where emp_id like '%$q%' or name like '%$q%' order by emp_id LIMIT 5 ");
while ($row = mysql_fetch_array($sql_res)) 
{
$emp_id = $row['emp_id'];
$name = $row['name'];
$b_emp_id = '<strong>'.$q.'</strong>';
$b_name = '<strong>'.$q.'</strong>';
$fina_emp_id = str_ireplace($q, $b_emp_id, $emp_id);
$final_name = str_ireplace($q, $b_name, $name);
?>
<div class="show" align="left">
    <span class="name"><?php echo $fina_emp_id; ?></span>
</div>
<?php
}
} 
?>

How to insert data into database using a custom php MVC with ajax

I want to store data into database.

I tried this:

In the View I created this form:

<form id="addData" action="<?php echo URL ?>controles/addControl" method="POST">
    <input type="text" name="text1">
    <input type="text" name="text2">
    <input type="text" name="text3">
    <input type="submit" name="Add">
</form>

Then I created a Model

controles_model.php

public function addControl(){
    $text1  = $POST['text1'];
    $text2  = $POST['text2'];               
    $text3  = $POST['text3'];

    $stmt = $this->db->prepare("INSERT INTO `controles` (field1, field2, field3 ) VALUES(?,?,?)");
    $stmt->execute(array($text1,$text2,$text3));

    if($stmt == true){
        return "good";
    }else{
        return "wrong";
    }
}

Then I created a Controller:

controles.php

class Controles extends Controller {    
    function __construct(){
        parent::__construct();
    }
    public function index(){        
        $this->view->render('controles/index');
    }
    function addControl(){
        $this->model->addControl();
    }
}

and finally, for the JS file I created this:

$("#addControl").on('submit', function(e){
    e.preventDefault();

    var url     = $(this).attr('action');
    var data    = $(this).serialize();

    $.post(url, data, function(response) {
        if(response == "good"){
            $("#insertedSuccessfully").show();
        }else if(response == "wrong"){
            $("#notInserted").show();
        }   
    });
});

All this doesn't work. How can I fix it?

NB: the database connection is OK, it work fine sine I can retreive data from database.

Passing different parameters to ajax based on the button that has been clicked

I have the following html form:

<form class="center" id="myform">
<p>
    <input id="email" name="email" type="email" class="textox email" title="" placeholder="your@email.com" required>
</p>
    <textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
<div class="terms">
        <input type="checkbox" class="required" value="None" id="terms" name="terms">I accept terms</input>
    </div>
</p>
<input type="submit" id="sendfeedback" value="now" disabled/>
    <input id="datetimepicker" type="text" readonly="readonly">
        <input type="submit" id="postmelater" value="send" disabled/>
</form>

And as you can see above, I have a form with two buttons. The logic behind it works like that, that when I want to put text to database with current timestamp - I choose button sendfeedback. However, there's also a possibility of adding the feedback with chosen timestamp, that is happening when user choses the date from datetimepicker and hits postmelater. Now, the ajax code for that looks like this:

$(document).ready(function () {

$('#myform').validate({// initialize the plugin
    errorElement: 'div',
    rules: {
        email: {
            required: true,
            email: true
        },
        slogan: {
            required: true,
            minlength: 2
        },
        terms: {
            required: true,
            maxlength: 2
        }
    },
    submitHandler: function (form) { // for demo
        alert('valid form submitted'); // for demo
        var mail = $("#email").val(); //mg
        var text = $("#textarea").val();
        var date = 0;
        var stand = 1;
        $.ajax({
            url: 'savedatanow.php'
            type: "POST",
            data: {
                mail: mail,
                text: text,
                date: date,
                stand: stand

            },
            success: function(response)
            {

                alert(response);
            }
        });

    }
});
$('#myform').find('input, textarea').on('change', function () {
    var btn = $('#myform').find('input[type=submit]');
    if ($('#myform').valid()) {
        btn.removeAttr('disabled');
    } else {
        btn.attr('disabled', 'disabled');
    }
});
});

There's a validation process attached to the fields and so far - only support for the first button. How can I add a support for 2nd button, and in case when user clicks it - also pass the datetime attribute to ajax? Can I distinguish them somehow in Ajax? Thanks!

jquery ajax beforesend wait before sending

I am trying to use settimeout in the ajaxsetup beforesend function, but what seems to happen is the ajax is sent and the wait function is called after the timeout. I want to stop the requests from sending for the timeout period

jQuery.ajaxSetup({
    beforeSend: function(){
        setTimeout(continueExecution,1000)

        return true;
    }
});

Can someone suggest me a way to stop the requests from being sent from ajaxsetup

C# MVC: displaying list items with ajax

I'm trying to display list items with AJAX. First, when you go into the page, you will see the first item of the list. After clicking "Next", then AJAX will refresh its div with the next item in the list.

Controller

public ActionResult Index()
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView(_attractionList.ElementAt(1)); // next element in the list
            }

            return View(_attractionList.First());
        }

View

@model EasyTripNow.Models.Attraction

@{
    ViewBag.Title = "Index";
}

    @Html.Partial("_Attraction", Model)

    @using (Ajax.BeginForm(
        new AjaxOptions()
        {
            HttpMethod = "get",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "newAttraction"
        }))
    {
        <input type="submit" value="Next"/>
    }

Attraction Partial view:

<div id="newAttraction">
    <h4>Attraction</h4>
    @Html.EditorForModel(Model)
    <p>
        @Html.ActionLink("Edit", "Edit", new {id = Model.ID}) |
        @Html.ActionLink("Back to List", "Index")
    </p>
</div>

Can't think of a good way to do it.

Any suggestions?

Translate a word using sql database in vn.net and ajax

Can anyone guide me how to replace a word from sql using vb and ajax with clicking a button?

I tried this backend code:

Using da As New SqlDataAdapter
                con.Open()
                cmd.CommandText = "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';"
                da.SelectCommand = cmd
                Dim dt As New DataTable
                da.Fill(dt)
                Dim WordValue As String = dt.Rows(0).Item(0)
  End Using

and in front end to display the word:

<%# Eval("WordValue")%>

My ajax:

$.ajax({
        type: "POST",
        cache: false,
        url: "http://ift.tt/1JxB6gu",
        data: {},
        success: alert("success"),
        error: alert("error")
    });

Buttons to translate:

 <form runat="server">
  <asp:RadioButtonList ID="change_language" runat="server"  AutoPostBack="True" 
        onselectedindexchanged="change_language_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="english">English</asp:ListItem> 
<asp:ListItem Value="malay">Malay</asp:ListItem>
        </asp:RadioButtonList>
 </form>

Updated value of form item fetched with ajax

I am working in wordpress and I am using an ajax call to return aid field. I have a form in for loop and there are multiple submit buttons. I want the updated value of aidd field returned. aidd always return the first clicked value

jQuery(function ($) {
        $(document).on("click",".star", function(e) {
        e.preventDefault();

        var aid = jQuery("#aid").val();


        //////////////////////////////////
       alert(aidd);
             var sentdata =({

                action: 'star',
                    id:aid
            })
    var element = $(this);
     $.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
    alert(id);
                $(element).siblings("#hero").html(res);
            } //end of function
            ,
            'json');    }); //end inner function
    });

php (just pasting the form php code )

$form.= '<form id="voteform" action="" method="post">';
    $form.='<div>';

    $form.= "<input id='aid' name='aid' type='text' value='$result->aid'>";
     ///////////////
    $form.="<input class='star' id='star1' type='image' type='submit' name='star5' src='http://localhost:8080/test/wp-content/uploads/2015/05/star0.png' value='1' style='border:0px!important;'>";
    $form.="<input class='star' id='star2' type='image' type='submit' name='star5' src='http://localhost:8080/test/wp-content/uploads/2015/05/star0.png' value='2' style='border:0px!important;'>";
    $form.="<input class='star' id='star3' type='image' type='submit' name='star5' src='http://localhost:8080/test/wp-content/uploads/2015/05/star0.png' value='3' style='border:0px!important;'>";
    $form.="<input class='star' id='star4' type='image' type='submit' name='star5' src='http://localhost:8080/test/wp-content/uploads/2015/05/star0.png' value='4' style='border:0px!important;'>";
    $form.="<input class='star' class='star' id='star5'  type='image' type='submit'  name='star5' src='http://localhost:8080/test/wp-content/uploads/2015/05/star0.png' value='5' style='border:0px!important;'>";

    $form.='<input class="star" name="star5" src="http://localhost:8080/test/wp-content/uploads/2015/05/star0.png" type="image" type="submit" value="6" /></form>';

Resulting php function

add_action( 'wp_ajax_star', 'star' );
add_action( 'wp_ajax_nopriv_star', 'star');


function star()
{


    $aid = $_POST['id'];
    echo json_encode ($aid);
    die();
}

how to retrieve query_vars by sending custom url to Wordpress by Ajax

i am working on a new wordpress theme that will convert a wordpress site to a SPA (single page application) .

This theme works by JSON REST API and Backbone.Marionette.

I use backbone.Marionette and jquery for client-side action. but i have a problem by wordpress links (pages ,posts , custom links in post contents)

how can i setup a structure on my theme to convert all links to query_vars without sending links by http to server .

must i use

$wp_rewrite->rewrite_rules;

and use the rules for my Appliction.AppRouter.

thanks a lot

Calling JSON and data retrieval working in browser but not in Cordova emulator or mobile

I am building a mobile web app using html5, there I am fetching the data from my WCF rest serice. Problem is it's working fine in browser, when converted in to app using Apache Cordova it's not working.

I'm getting http_request.readyState :4 and http_request.status :0 instead of 200. I thought it's a problem with cross domain issue so used ajax instead of Java function and enabled CORS in web.config of WCF still problem persists

Can anyone help out please?

Thanks in advance

Vikram

PS : when using ajax function its getting into error function but displaying a error message success:200, don't what it means

$.ajax({
                dataType: 'jsonp',
                type: "GET",
                url: "http://dev_test_srv/RestServiceImpl.svc/json/123?callback=?",
                success: function (data) {
                    alert(123);
                    alert("working");
                },
                error: function (error) {
                    alert(error.statusText + "-" + error.status);
                }
});

var data_file = "http://dev_test_srv/RestServiceImpl.svc/Employees/" + id + "/" + pwd;
alert(data_file);

var http_request = new XMLHttpRequest();

try {
                // Opera 8.0+, Firefox, Chrome, Safari
                http_request = new XMLHttpRequest();
} catch (e) {
                // Internet Explorer Browsers
                try {
                    http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
                    try {
                        http_request = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {
                        // Something went wrong
                        alert("Your browser broke!");
                        return false;
                    }
                }
}

http_request.onreadystatechange = function () {
                alert(http_request.readyState + '--' + http_request.status);
                if (http_request.readyState == 4 && http_request.status == 200) {
                    var stringouptut = http_request.responseText;
                    var replacedstring = stringouptut.replace(/\\/g, "");
                    var newresult = "{ \"Data\": " + replacedstring.substring(replacedstring.indexOf("["));
                    var final = newresult.substring(0, newresult.length - 2) + " " + " }";

                    final = JSON.parse(final);

                    if (final.Data.length > 0) {

                        if (final.Data[0].status == "Valid") {

                            localStorage.UserId = id;

                            window.location = "doctors.html";
                        }
                        else {
                            document.getElementById("lblerror").innerHTML = "Invalid Employee ID/Password";
                        }

                    }
                }
            }
            http_request.open("GET", data_file, true);
            http_request.send();

Config settings in web.config :

<httpProtocol>
    <customHeaders> 
         <add name="Access-Control-Allow-Origin" value="*"/>
         <add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>
         <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />                             <add name="Access-Control-Max-Age" value="1728000" />
    </customHeaders> 
</httpProtocol>

Ajax GET with Reagent

I am doing an Ajax GET from my Reagent application, to load some stuff from the database.

I am not entirely sure what is the best way of getting the result of such ajax call to my page, considering that if I put it in an atom, then Reagent automatically re-renders a component when an atom is dereferenced, which means I get an infinite sequence of ajax calls.

For some code,

(def matches (atom nil))

(defn render-matches [ms]
  (reset! matches (into [:ul] (map (fn [m] ^{:key m}[:li m])
                                   (walk/keywordize-keys (t/read (t/reader :json) ms)))))

This function basically creates a [:ul [:li "Stuff here"] [:li "And here"]]

Which i would like displayed on my page, which now has the following code.

(defn standings-page []
  (GET "/list-matches"
       {:handler render-matches})
  @matches)

database error while fetching value from table

Hi i am using ajax for fetching values from database.My connection with database is ok. But while i am trying to show the result its showing me a an error. How can i solve this?? TIA

my config file:

<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'steptwor_sscamera');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();

ajax.php :

<?php

require_once 'config.php';
if(!empty($_POST['type'])){
    $type = $_POST['type'];
    $name = $_POST['name_startsWith'];
    $query = "SELECT category_name, product_name, amount FROM v_product_list UPPER($type) LIKE '".strtoupper($name)."%'";
    $result = mysqli_query($con, $query);
    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row['category_name'].'|'.$row['product_name'].'|'.$row['amount'];
        array_push($data, $name);
    }   
    echo json_encode($data);exit;
}

erro:

<br />
<b>Warning</b>:  mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in <b>F
:\xampp\htdocs\sscamera\ajax.php</b> on line <b>10</b><br />
[]

vendredi 8 mai 2015

Rails: AJAX Form not passing parameter on heroku but working locally

I'm unable to get a AJAX form to work on Heroku even though it works locally. you can check out the heroku app here -

http://ift.tt/1Kt9kll

(The form is the new subreddit form located on the right of the screen)

The form code in the view (its a partial) -

<form class="form-inline" action="/subreddits" accept-charset="UTF-8" data-remote="true" method="post">
<div class="form-group">
    <input class="input-small" name="utf8" type="hidden" value="✓">
</div>
<div class="form-group sr-title">
    <input class="form-control input-small subreddit_title_field" placeholder="Create new subreddit" type="text" name="subreddit[title]" id="subreddit_title">
</div> <button type="submit" name="commit" class="btn btn-default new-subreddit">Submit</button>

the code in the respective controller -

def create
    p params[:subreddit_title]
    @subreddit = Subreddit.new(title: params[:subreddit_title].downcase)
    respond_to do |format|
      if @subreddit.save
        format.js { render 'create.js.erb' }
      else
        @error = @subreddit.errors.full_messages.to_sentence
        format.js { render 'error.js.erb' }
      end
    end
  end

the javascript application code snippet (in application.js)-

$('.new-subreddit').on("click", function(e) {
            e.preventDefault();
            var form_data = $('.subreddit_title_field').val();
            var values = {
                subreddit_title: form_data,
            }
            var ajaxRequest = $.ajax({
                url: '/subreddits',
                type: 'POST', // GET, PUT, DELETE
                data: values,
            });
   });

the output locally for "bridges" as a form input (which works)-

tarted POST "/subreddits" for ::1 at 2015-05-09 11:55:52 +0530 ActiveRecord::SchemaMigration Load (6.3ms) SELECT "schema_migrations".* FROM "schema_migrations" Processing by SubredditsController#create as / Parameters: {"subreddit_title"=>"bridges"} "bridges" (0.1ms) BEGIN Subreddit Exists (0.9ms) SELECT 1 AS one FROM "subreddits" WHERE "subreddits"."title" = 'bridges' LIMIT 1 SQL (0.4ms) INSERT INTO "subreddits" ("title", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["title", "bridges"], ["created_at", "2015-05-09 06:25:53.054220"], ["updated_at", "2015-05-09 06:25:53.054220"]] (12.3ms) COMMIT Rendered subreddits/create.js.erb (2.4ms) Completed 200 OK in 93ms (Views: 20.4ms | ActiveRecord: 23.4ms)

the output from heroku logs -

2015-05-09T06:02:56.196766+00:00 app[web.1]: Started POST "/subreddits" for 180.151.86.227 at 2015-05-09 06:02:56 +0000 2015-05-09T06:02:56.200751+00:00 app[web.1]: Processing by SubredditsController#create as / 2015-05-09T06:02:56.203206+00:00 app[web.1]: 2015-05-09T06:02:56.203210+00:00 app[web.1]: NoMethodError (undefined method downcase' for nil:NilClass): 2015-05-09T06:02:56.203212+00:00 app[web.1]: app/controllers/subreddits_controller.rb:8:increate'

CodeIgniter - Ajax Json call to controller not working

I am current using CodeIgniter 2.2.2 I have the following controller code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class switchLang extends CI_Controller {
    public function __construct()
    {
        parent::__construct();

                $this->load->helper('url');
    }
    public function changeLang()
    {
            log_message('debug', 'INSIDE');
            //echo "test";

            $data = array("STATUS"=>"true");
            //echo "HI";
            echo json_encode($data) ;   
    }

    public function index(){
        }   
}

And inside my view I have the following ajax call:

<script  type="text/javascript">
            $(document).ready(function() {      
                                var base_url = '<?php echo site_url('switchLang/changeLang');?>';

                                $('#lang').click(function(event) {
                                        console.log(5 + 6);
                                        $.ajax({
                    'async': false,
                    'url' : base_url,
                    'type' : 'POST', 
                    'dataType': 'json',
                    'data' : 'data',
                    'success' : function(data){ 
                                console.log(data);
                                 if(data){
                                    location.reload(); 
                                }
                             }
                                    });

                                });
                        });
</script>

I am trying to reload page on success jax call. However I am getting only the following response in my Chrome debugger and nothing happens.

enter image description here

What exactly is mock post and how come my ajax isn't calling my controller function? Note: But when I try manually typing url inside my browser((myhostname)/switchLang/changeLang), my controller seems to be working perfectly.

Use JSON Variable in Laravel to Update Table

I'm trying to send a JSON post request through ajax to Laraval to update a table. I'm receiving a 405 Method Not Allowed. I'm trying to use a variable to update that column in the table. I am using Laravel 4.2

My javascript code is...

var stylist = $("#stylist").val(); $.ajax({ type:"post", dataType: 'json', data: { firstName:firstName, lastName:lastName, phoneNumber:phoneNumber, date:date, timeslot: timeslot, stylist: stylist } });

My larval code is...

` if(Request::ajax()){

$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$phoneNumber = Input::get('phoneNumber');
$date = Input::get('date');
$time = Input::get('timeslot');
$stylist = Input::get('stylist');

$checkClient = DB::table('users')->where('firstName','=',$firstName)->where('lastName','=',$lastName)->where('phoneNumber','=',$phoneNumber)->pluck('id');

if($checkClient){
        $setBooking = DB::table('calendar')->where('dt','=',$date)->where('timeslot','=',$time)
                             ->update(array($stylist=>1,'clientID'=>$checkClient));
}
else {
        $enterNewClientId = DB::table('users')->insertGetId(array('firstName'=>$firstName, 'lastName'=>$lastName, 'phoneNumber'=>$phoneNumber,'role'=>0));
        $setNewBooking = DB::table('calendar')->where('dt','=',$date)->where('timeslot','=',$time)
                             ->update(array($stylist=>1,'clientID'=>$enterNewClientId));
}
}

I believe my problem is possibly using the variable in the update array.

Twitter BootStrap Confirmation not working for dynamically generated elements

I am using DataTable's with dynamic content generated on page load. In table I have used bootstrap confirmation. To load it below script.

$( document ).ajaxStop(function() {
    $(document).find('[data-toggle="confirmation"]').confirmation();
});

It opens confirmation box, but when clicking on "Yes" or "No" , it's not working.

This is not working

I have below code to detect 'Confirmed' event.

$(document).ready(function(){
    $(document).find('.delete-record').on('confirmed.bs.confirmation', function() {
        var thisEl = $(this);
        deleteForm($(this).attr('data-delid'));
    });
});

This is working

$(document).ajaxStop(function(){
    $(document).find('.delete-record').on('confirmed.bs.confirmation', function() {
        var thisEl = $(this);
        deleteForm($(this).attr('data-delid'));
    });
});

What's wrong with document.ready ?

enter image description here

Edit :

I have same code with document.ready working on other page, but there is no DataTable, it's HTML DIV structure.

Call a Wordpress shortcode with AJAX

I have a shortcode in Wordpress which I want to call it with jQuery with the click of a button. I read a few websites and tutorials, but I cannot figure exactly what happen.

I put this on function.php:

add_action( 'init', function() { 
  ps_register_shortcode_ajax( 'ps_get_survey_form', 'ps_get_survey_form' ); 
} );

function ps_register_shortcode_ajax( $callable, $action ) {

  if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
    return;

  call_user_func( $callable );
}

function ps_get_survey_form() {
    echo do_shortcode( '[dopbsp id=6 lang=el]' );
    die(); 
} 

And this on the page-template.php I use:

<button id="testonclick" onclick="test()"></button>

<div id="testresults"></div>

<script>

function test() {
    jQuery.ajax({
        url: "http://localhost/myweb" + "/wp-admin/admin-ajax.php",
        data : {action: 'ps_get_survey_form'},
        success: function(results){
            jQuery("#testresults").html(results)
        },
        error: function(errorThrown){console.log(errorThrown);}
    });// end of ajax
}
</script>

However, the results is 0. Any idea what happened wrong?