mercredi 6 mai 2015

Send value from controller with ajax Codeigniter

i have javascript like this

$(document).ready(function(){
    $("input[type='checkbox']").change(function(){
        var menu_id = this.value;
        if(this.checked) var statusvalue = "On";
        else var statusvalue = "Off";
        $.ajax({
            type    : "POST",
            url     : "admin/menu/editstatus",
            data    : "id=" + menu_id + "&value=" + statusvalue,
            success : function(data){
                $("#testing").html(data);
            }
        });
    });
});

and my controller named menu and have function editstatus()

public function editstatus()
{
    $data = "asd";
    echo $data;
}

but textbox with id testing not writen anything

Saving data with ajax and json

I am working on a project that I didn't start and I have an input that is function is to save the data to the data base. The input leaves to this function (SaveData) and it isn't working. I really don't understand much from ajax and json, so could anyone please see what's wrong with this?

The function is this:

 function SaveData() {
     var columns = [];

     $("#FeaturedContent_m_visible_cols li").each(function (i, elem) {
        columns[i] = $(elem).attr("colid");
     });

     $.ajax({
        async: false,
        type: "POST",
        url: "http://ift.tt/1EPQ0gY",
        data: "{ 'jsonData': [" + JSON.stringify(columns) + "] }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
        },
        error: function (response) {
           alert(jQuery.parseJSON(response.responseText).Message);
        }
     });

The SaveConfiguration method is this:

[System.Web.Services.WebMethod]
 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
  public static string SaveConfiguration(dynamic jsonData)
{
 Object[] column = (Object[])jsonData[0];
  string   col_id;
  int      i;

  for (i=0; i<column.Length; i++) {
     col_id = (string)column[i];
  }

  SaveTableConfiguration();

  return "";
  }

And the SaveTableConfiguration:

 public void SaveTableConfiguration(int list_id, List<TableHeader> lista)
  {
    int           i;
    TableHeader   row;
    SetListConfig set_lconfig = new SetListConfig(m_connection, m_language);

set_lconfig.LoadRecordset("LC_LISTID=" + list_id.ToString(),    m_transaction);
     while (!set_lconfig.IsEOF()) {
        set_lconfig.m_LC_EDITABLE = 0;
        set_lconfig.Update();

        set_lconfig.MoveNext();
     }

     for (i=0; i<lista.Count;i++) {
        row=lista[i];

set_lconfig.LoadRecordset("LC_LISTID=" + list_id.ToString() + " AND                LC_COLTBL='" + row.header_col + "'", m_transaction);
        if (set_lconfig.IsEOF()) {
           set_lconfig.m_LC_EDITABLE = 1;
           set_lconfig.m_LC_ORDER = i+1;
           set_lconfig.Update();
        }
     }
  }

Thanks Once more! =)

How to pass mysql result as as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON. ajax2.php

$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
    $statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
 // $row = $statement->fetchAll(PDO::FETCH_ASSOC);
 while( $row = $statement->fetch())
 {
     echo $row['Name'];//How to show this in the html page?
      echo $row['PostUUID'];//How to show this in the html page?
      $row2[]=$row;
 }
    echo json_encode($row2);

How to pass the above query result to display in the html page via ajax below?

my ajax

$("form").on("submit",function() {

    var data = {
      "action": "test"
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "ajax2.php", //Relative or absolute path to response.php file
      data: data,
      success: function(data) {
          //how to retrieve the php mysql result here?
        console.log(data);// this shows nothing in console,I wonder why?
      }
    });
    return false;

});

JQuery ajax post function is executed at the end of javascript

i have a problem with validating if the username is already taken. I am trying to find out if the username already exists using the "post" method of jquery. But when executing this function, the script is alway jumping to the end of the function and is doing the rest of the script first before executing the "post" command. Could you please review my code and help me?

$("#submit").click(function () {

    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    var passwort = document.getElementById("passwort").value;
    var passwort2 = document.getElementById("passwort2").value;
    var validate = false;

    checkUsername();

    if (validate == true) {
        $.post("Login/register.php", {

            username: username,
            email: email,
            passwort: passwort,
            passwort2: passwort2,
        }, function (info) {
            $("#errorBox").empty();
            $("#errorBox").html(info);
        });

    } else {
        $('#register').submit(function () {
            return false;
        });
    }

    function checkUsername() {
        username = document.getElementById("username").value;
        // username = replaceUmlauts(username);
        if (username.length > 0) {
            document.getElementById("username").style.borderColor = "";
            // document.getElementById("errorBox").innerHTML =
            // "";
            validate = true;
            checkAvailability();
            return false;
        } else {
            document.getElementById("username").style.borderColor = "red";
            document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
            // alert('Username must be longer than one sign');
            validate = false;
            return false;
        }
    }

    function checkAvailability() {
        $.post(
            "Login/checkusername.php", {
                username: username
            },
            function (result) {
                // if the result is 1
                if (result == 1) {
                    // show that the username is
                    // available
                    document
                        .getElementById("errorBox").innerHTML = "";
                    return false;
                } else {
                    // show that the username is NOT
                    // available
                    document
                        .getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
                    document
                        .getElementById("username").style.borderColor = "red";
                    validate = false;
                    return false;
                }
            });

    }
    return false;

});

how to display image after upload in Symfony2

i have a register form (based on FOSUserBundle) in my Symfony2 application. A user can upload an avatar for its profile before submitting the form. I want display its picture just after upload in ajax . How can i do that?

Best framework to develop java web based application

I want to develop a social networking site like facebook using java technology. But i am confused that which framework i should use because there are many frameworks in java.

I want to develop in few time and fast, maintainable application which will held a lots of data.And i will use javascript and ajax in that application.

So please suggest me the best framework in java with their advantages and drawbacks.And also suggest me the best database with that framework.

Thanx in advance

AJAX function is not working by scroll

Using AJAX for endless scroll. Content loads only first time, but does't load by scroll.

What is wrong?

jQuery:

function loadFeed() {
    $.ajax({
        url: 'loadmore.php',
        dataType: 'html',
        success: function (data) {
            $("#posts").append('<div class="havanagila"></div>');
            $('#posts').html(data);
        }
    });
}

loadFeed();
$(window).scroll(function () {
    var windowScroll = $(window).scrollTop();
    var windowHeight = $(window).height();
    var documentHeight = $(document).height();

    if ((windowScroll + windowHeight) == documentHeight) {
        loadFeed();
    }
});

loadmore.php:

<?php 
session_start();

if ( isset( $_SESSION['login'] ) ) {

    $login    = $_SESSION['login'];
    $id=$_SESSION['id'];

    $username="root";
    $password="root";
    $hostname = "localhost";
    $dbname= "kotik";


    function testdb_connect ($hostname, $username, $password){
        $dbh = new PDO("mysql:host=$hostname;dbname=kotik", $username, $password);
        return $dbh;
    }


    try {
        $dbh = testdb_connect ($hostname, $username, $password);

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

}

?>

<?php                                                              

$title_select_query= $dbh -> prepare("SELECT title FROM books WHERE id = :id ORDER BY date DESC");
$title_select_query ->execute(array(':id' => $id));
$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

?>

Post with AngularJS doesn't work

I would like to send a post request to my API. It works with jQuery :

<script src="http://ift.tt/1yCEpkO"></script>
<script>
  $.ajax({
  type: "POST",
  url: "api.php?option=inscription",
  data: {lol : "mess"}
});
</script>

But it doesn't with AngularJS :

<script src="http://ift.tt/1DTrZWe">    </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>

If someone can help me. Thank you !

UPDATE : Thank for your answers, I wanted to simplify but it wasn't clear anymore. So with your help, this is my new code, and the problem is the same. The data in the backend is empty ;

frontend :

<html ng-app="myApp">
<script src="http://ift.tt/1DTrZWe">   </script>

<div ng-controller="MainCtrl"></div>
{{data}}

<script>
var app = angular.module('myApp', []);

app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {

    var back =  $http.post(dataUrl, dataTobePosted);

    back.success(function(data){
      console.log(data);
      return data;
    }).error(function(data, status, headers, config) {
      return status;
});
    }
});

app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
    var dataTobePosted = {"lol": "mess"};

    $scope.data = SomeService.readData(url, dataTobePosted);
}

$scope.readData('api.php?option=inscription');
});
</script>
</html>

Is it possible to make ajax call from .ascx page. here is my code please review

This is from .ascx page, here i am calling .autocomplete inside this i am colling ajax call. please help.

                            $("#txtUsers").autocomplete({
                                        //source: availableTags
                                        source: function (request, response) {
                                            //Pass the selected country to the query manager to limit the selection to 1 country
                                            $.ajax({
                                                url: 'http://ift.tt/1F5oJKK',
                                                data: '{Name:' + $('#txtUsers').val() + '}',
                                                type: 'POST', // a jQuery ajax POST transmits in querystring format (key=value&key1=value1) in utf-8
                                                dataType: 'json', //return data in json format
                                                success: function (data) {
                                                    response($.map(data, function (item) {
                                                        return {
                                                            label: item.stateName,
                                                            value: item.name
                                                            //abbrev: item.stateAbbrev
                                                        };
                                                    }));
                                                }
                                            });
                                        }
                                    });

on .cs page:

[WebMethod]
public static string GetNames(string Name)
{
    return "";
}

Why am I receiving with this AJAX script the status 404?

I got into AJAX and am using the MAMP web server and trying to implement a simple script which should show me whether this is working. I tried tracking down the problem by using the status property of XMLHttpRequest(); I found out that it was a problem of type 404 (Page not found) and this is astonishing as I am using JSON file to handle the script which is in the same directory as my ajax script.

Here is the AJAX script:

var xhr = new XMLHttpRequest();
xhr.onload = function() {

if (xhr.status === 200) {

    alert("Good");
}

else if(xhr.status === 304)
{
    alert("304");

}


else if(xhr.status === 404)
{
    alert("404");
} 

else
{
    alert("500");
}
xhr.open("GET", 'json.json', true);
xhr.send(null);

And here my file json.json:

{
"events" :
[
    {
        "location" : "San Francisco, CA"
    }

]
}

This is really frustrating. Thanks in advance,

Raul Rao

CGridView Filter duplicate Ajax requests when using Tabs

In my web application I use tabs and load part of the views per Ajax. So it's possible, that I do load the same CGridView multiple times without reloading the page. If that occurs I become duplicate Ajax requests if I use CGridView Filters.

The filters and requests are standard. Following images show those simple filter and 10 x times GET requests if type the search value once.

simple filter duplicate ajax requests

Here is the code of Tabs-widget I use:

$this->widget('bootstrap.widgets.TbTabs', array(
'id' => 'thirdPartyCatTabs',
'title' => Translate::t('project', 'Categories'),
'type' => 'tabs',
'placement' => 'top',
'events' => array(
    'shown' => 'js:loadContent'
),
'tabs' => array(
    array(
        'id' => 'standardCat',
        'label' => Translate::t('project', 'Standard Categories'),
        'linkOptions' => array(
            'data-tab-url' => Yii::app()->createUrl('/thirdParty/settings/thirdPartyCategoryStandard'),
        ),
    ),
    array(
        'id' => 'standardCatMap',
        'label' => Translate::t('project', 'Standard Category-Mapping'),
        'linkOptions' => array(
            'data-tab-url' => Yii::app()->createUrl('/thirdParty/settings/showCategoryMapTab'),
        ),
    ),
)
));

I guess I have to use uniqid() at some place, but can't figure out where. Thanks.

Binding value to select in angular js across 2 controllers

Working with angularJS I am trying to figure out a way to bind the value of a select element under the scope of controller A to use it as an argument for an ng-click call [getQuizByCampID() Function] under the scope of controller B.

My first idea was to use jquery, but I have read in the link below that using jquery is not recommended when starting with angularJS.

"Thinking in AngularJS" if I have a jQuery background?

I also read in the link below that this is performed using ng-model, the only problem is that that the example provided is all under the same controller. and Binding value to input in Angular JS

What is the angularJS way to get the value of the select element under controller A into the function call in the select under controller B?

Price.html view

  <div class="col-sm-3" ng-controller="campCtrl"> **Controller A** 
       <select  id="selCampID" class="form-control" ng-model="campInput" >
            <option ng-repeat="camp in campaigns" value="{{camp.camp_id}}">{{camp.camp_name}}</option>  
        </select>
  </div>

   <div class="col-sm-3" ng-controller="quizCtrl">  **Controller B**
        <select   ng-click="getQuizByCampID($('#selCampID').val())" class="form-control" ng-model="quizInput">
             <option ng-controller="quizCtrl" ng-repeat="quiz in quizzesById" value="{{quiz.quiz_id}}">{{quiz.quiz_name}}</option>  
         </select>
    </div>

App.js

var app= angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/price', {templateUrl: 'partials/price.html', controller: 'priceCtrl'});
}]);

$routeProvider.when('/price', {templateUrl: 'partials/price.html', controller: 'priceCtrl'});

Quiz Controller

'use strict';

app.controller('quizCtrl', ['$scope','$http','loginService', function($scope,$http,loginService){
$scope.txt='Quiz';
$scope.logout=function(){
    loginService.logout();
}
getQuiz(); // Load all available campaigns 
function getQuiz(campID){  
    $http.post("js/ajax/getQuiz.php").success(function(data){
    $scope.quizzes = data;
    //console.log(data);
   });
};
  $scope.getQuizByCampID = function (campid) {
  alert(campid);
$http.post("js/ajax/getQuiz.php?campid="+campid).success(function(data){
    $scope.quizzesById = data;
    $scope.QuizInput = "";
  });
  };

    $scope.addQuiz = function (quizid, quizname, campid) { 
  console.log(quizid + quizname + campid);   
  $http.post("js/ajax/addQuiz.php?quizid="+quizid+"&quizname="+quizname+"&campid="+campid).success(function(data){

  getQuiz();
  $scope.QuizInput = "";
});
  };

}])

PDO query with multiple condition to be passed as JSON via ajax [duplicate]

This question already has an answer here:

This is how my JSON string is like:

$return='{"sub":{"4":"","5":""},"postcode":"89098","slider1":"230","action":"test"}';

This is how I get the values from JSON string :

$a=$data['sub'];

foreach($a as $v=>$k) 
  {

    $key[]=$v;

  }
 $key2=implode(',',$key);

 $postcode=$data['postcode'];
 $rate=$data['slider1'];

This is my query:

 $statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND postcode=:postcode2 AND rate=:rate2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode,':rate2'=>$rate));



$row = $statement->fetchAll(PDO::FETCH_ASSOC);

I'm unable to pass anything to the HTML page from the php script via AJAX as json right now.

Question 1) How do I form the query with 3 condition:

condition 1= subjects are filtered by $key

condition 2=postcode is filtered by $postcode

condition 3=rate is filtered by $rate

Question 2) I wish to pass this as JSON to the HTML page to be displayed there.SO how do I pass from this php script?

Currently I'm passing like echo json_encode($row);

My AJAX

$("form").on("submit",function() {

  var data = {
  "action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
  type: "POST",
  dataType: "json",
  url: "ajax2.php", //Relative or absolute path to response.php file
  data: data,
  success: function(data) {
       var id = data[0];              //get id
    var vname = data[1]; 
    $(".the-return").html(
      "Subject: " + id
    );

    alert("Form submitted successfully.\nReturned json: " + data+"vname= "+vname);
  }
});
return false;  
});

jQuery setRequestHeader Authorization

I'm trying to authorise an AJAX query based on this code:

...
beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'BEARER ' + access_token); },
...

All work fine so far! But there are multiple ajax requests and the request header / the access token is not send each time (Every second or third time).

The first Request-Header looks like this:

  • Accept application/json, text/javascript, /; q=0.01
  • Referer URL.com
  • X-Requested-With XMLHttpRequest
  • User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS...
  • Authorization BEARER 00000000000

all work fine! But the next request:

  • application/json, text/javascript, /; q=0.01
  • Accept-Language en-us
  • Accept-Encoding gzip, deflate
  • Referer URL.com
  • User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS...
  • X-Requested-With XMLHttpRequest

Does anybody know whats going on here?

highstock chart when loading via ajax has jerky behavior

I'm using HighStock api and setExtremes callback to load data from server.

When I change the extremes, the whole chart just jerks to some values (x axis changes so do the lines) until the data is returned from the server.

It looks highly unprofessional, as if an error corrected on runtime.

Any change the 'loading' comes and then the new data comes smoothly?

here's the fiddle

if !is_code_accompanied
  stack_overflow = doesnt_let_me_post()
end

How's 504 response header handled in ajax request in jquery?

I have an ajax call from client, that looks like that:

$.ajax({
            'url': '/converter/ajax-make-corrections/',
            'data': {

                corrections: JSON.stringify(globalCorrrectionsObject)
            },
            type: 'POST',
            success: function(data) {

            }
        })

This action send pretty big file to server to do some server job. The trouble is that there is timelimit on server - 30 minutes. After that server closes a connection with 504 errror (here is what I see in nginx access log file):

[06/May/2015:09:13:33 +0300] "POST /converter/ajax-make-corrections/ HTTP/1.1" 504

and at the same tim in nginx error.log file

*1799741 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 

There is no errors in apache log.

And here is what happened: action from browser was restarted 9 times exactly 30 minutes after each other. Since action in browser can not be start manually second time with same data, my best guess is that $.ajax action was restarting itself after getting 504 response. Is it possible? How $.ajax handles 504 response? Will it restart itself sending same data again?

Having an Issue In Using Angular Js with DNN7

I have created a user defined controller and than add a module in dnn7(Having resource of my user defined controller) and created a page in dnn7 and than access my newly created Module on it.But It shows me my HTML Page only means Submit button is not working and in Grid as well it's just showing me the name of fields.

For Ex:-

function EmpCtrl($scope) {
    $scope.getEmployee = function () {
        $.ajax({
            type: "POST",
            url: "http://ift.tt/1dMBcXF",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                 $scope.Emp = msg.d;
            }
        });
    };

 $scope.save = function () {
        $.ajax({
            type: "POST",
            url: "http://ift.tt/1dMBfTa",
            data: "{'empID':'" + $("#txtEmpID").val() + "','firstName':'" + $("#txtEmpFirstName").val() + "','lastName':'" + $("#txtEmpLastName").val() + "','address':'" + $("#txtEmpAddress").val() + "','city':'" + $("#txtCity").val() + "','pincode':'" + $("#txtPinCode").val() + "','state':'" + $("#txtState").val() + "','country':'" + $("#txtCountry").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) { 
                alert(msg.d);
            },
            error: function (msg) {
                alert(msg.d);
            }
        });
    };

<body>
    <form id="form1" ng-app="MyApp" ng-controller="EmpCtrl" ng-submit="save() ">
        <div style="text-align: center;">
            <img alt="" src="banner.jpg" />
        </div>
        <br />
        <div style="font-family: Verdana; font-size: 12px; margin-left: 450px;">
            <table>
                <tr>
                    <td style="text-align: right;"></td>
                    <td>
                        <input type="hidden" id="txtEmpID" value="0" ng-model="EmpID" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">First Name :
                    </td>
                    <td>
                        <input type="text" id="txtEmpFirstName" ng-model="EmpFirstName" autocomplete="off" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">Last Name :
                    </td>
                    <td>
                        <input type="text" id="txtEmpLastName" ng-model="EmpLastName" autocomplete="off" />
                    </td>
                </tr>

                <tr>
                    <td style="text-align: right;">Address :
                    </td>
                    <td>
                        <textarea id="txtEmpAddress" cols="20" rows="2" ng-model="EmpAddress"></textarea>
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">City :
                    </td>
                    <td>
                        <input type="text" id="txtCity" ng-model="EmpCity" autocomplete="off" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">Pin Code :
                    </td>
                    <td>
                        <input type="text" placeholder="Enter Digits Only" id="txtPinCode" ng-model="EmpPincode" autocomplete="off" onkeypress="return isNumber(event)" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">State :
                    </td>

                    <td>
                        <input type="text" id="txtState" ng-model="EmpState" autocomplete="off" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">Country :
                    </td>
                    <td>
                        <input type="text" id="txtCountry" ng-model="country" autocomplete="off" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align: center;">
                        <input type="submit" id="btnSubmit" value="Submit" />
                    </td>


                </tr>


            </table>


        </div>
        <hr />
    </form>
    <div class="container" ng-controller="EmpCtrl" data-ng-init="getEmployee()">
        <div>
            <input type="button" id="btnFetch" value="Fetch" ng-click="getEmployee()" />
        </div>
        <table border="1" style="text-align: center; margin-left: 410px;">
            <tr>
                <td>ID
                </td>
                <td>First Name
                </td>
                <td>Last Name
                </td>
                <td>Address
                </td>
                <td>City
                </td>
                <td>Pincode
                </td>
                <td>State
                </td>
                <td>Country
                </td>
                <td>Use 
                     Action
                </td>

            </tr>
            <tr ng-repeat="record in Emp">
                <td>{{record.ID}}
                </td>
                <td>{{record.FirstName}}
                </td>
                <td>{{record.LastName}}
                </td>
                <td>{{record.Address}}
                </td>
                <td>{{record.City}}
                </td>
                <td>{{record.Pincode}}
                </td>
                <td>{{record.State}}
                </td>
                <td>{{record.Country}}
                </td>
                <td><a ng-click="editEmployee(record.ID)">Edit</a></td>
                <td><a ng-click="deleteEmployee(record.ID)">Delete</a></td>
            </tr>
        </table>
    </div>
</body>
</html>

 [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string InsertEmployee(int empID, string firstName, string lastName, string address, string city, string pincode, string state, string country)
        {
            string connection = @"Data Source=dbpath;Initial Catalog=AngularJS;User Id=sa;Password=sa@123;";
            SqlConnection con = new SqlConnection(connection);
            SqlCommand cmd;
            string msg = "";
            try
            {
                con.Open();
                cmd = con.CreateCommand();
                if (empID == 0)
                {
                    cmd.CommandText = "INSERT INTO Emp_Details(FirstName,LastName,Address,City,Pincode,State,Country) VALUES(@FirstName,@LastName,@Address,@City,@Pincode,@State,@Country)";
                    msg = "Record Inserted Successfully";
                }
                else
                {
                    cmd.CommandText = "update  Emp_Details set FirstName =@FirstName,LastName=@LastName,Address=@Address,City=@City,Pincode=@Pincode,State=@State,Country=@Country where ID=" + empID;
                    msg = "Record updated Successfully";
                }
                cmd.Parameters.AddWithValue("@FirstName", firstName);
                cmd.Parameters.AddWithValue("@LastName", lastName);
                cmd.Parameters.AddWithValue("@Address", address);
                cmd.Parameters.AddWithValue("@City", city);
                cmd.Parameters.AddWithValue("@Pincode", Convert.ToInt32(pincode));
                cmd.Parameters.AddWithValue("@State", state);
                cmd.Parameters.AddWithValue("@Country", country);
                cmd.ExecuteNonQuery();
                return msg;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }

            }
        }

<Cs Code>

DNN Output Image

As you can see in the above image it's not fetching any data it's just printing my field description.

Use ajax to refresh page without reload, and in this pages use POST / GET

There are 3 sides, which I'm using Ajax to avoid having to reload the page to refresh. This 3 side content, and js :

Content:

<ul id="nav">
<li><a href="ajax_adat.php?id=8&epul=0">Adatok</a></li>
<li><a href="piac_vasarlas.php?id=8&epul=0">Kereskedelem</a></li>
<li><a href="piac_egyseg_gyartas.php?id=8&epul=0">Egység gyártás</a></li>

Js:

$(document).ready(function () {

$('ul#nav li a').click(function(){
    var page = $(this).attr('href');
    $('#content').load('../views/' + page );
    return false;
});});

All three pages would like to use POST and GET. For example what i like to use: The egyseg_gyartas.php?id=8&epul=0 look like:

...<input type=\"number\" name=\"v_vesz\" min=\"0\" max=\"".$hany["$v[$i]"]["epitheto"]."\" step=\"1\">...
<form action="<?php echo $_SERVER['PHP_SELF'], '?id=' . $id . '&epul=' . $lenneEpulet . '&Pgyart';?>" method="post">
    <input type="submit" name="egyseg_vasarlas" value="Küldés" style="float: left">
    <input type="Button" value="Vissza" onclick="$:location.href='../views/jatek.php'" style="float: left; margin-left: 10px">
</form>

For example the POST :

if( isset($_POST['egyseg_vasarlas']) )
{
    x = $_GET['v_vesz']
    ..... 
}

So how can i use POST if i use this refreshed pages without reload ? In the POST usually have to change the variables which will build on that page . For example, you can buy a wagon ( game ), and if you bought it , int the POST i need to change, now he cant buy 2 wagon, only 1, and i use php functions in POST, etc... .

Primefaces Command Button Ajax Works Only Once

I have the following command button which enters only once in the saveData method:

<p:commandButton id="saveBtn" 
    value="#{messages['um3.common.label.save']}"            
    actionListener="#{advisorBean.saveData}"            
    disabled="#{advisorBean.disabledSave}">             
    <f:param name="positionId" value="#{advisorBean.positionId}" />
</p:commandButton>

Here is the saveDate method signature: public void saveData().

Also, the page containing the button is inserted into a layout and the button sits in a primefaces panel.

Layout Page:

<h:body>
    <p:layout fullPage="true">
       <p:layoutUnit>
            <ui:insert name="footer">

Button Page:

<ui:define name="footer">
            <p:panel id="footer">
                <p:commandButton id="saveBtn" ...

Could you please advise?

Andrei

Open a particular accordion div after ajax call

I am submitting some values to database through ajax and i want to reload and open a particular accordion div after ajax call.

This is what i was trying and it doesn't work=

'success' : function(data){
                    $("#divId").html(data);

                     $("#divId").load(window.location + "#divId");
                       $("#accordion").accordion("option", "active", $("#activeDiv").index("#accordion div"));

            }

HTML code is here:

<div  id="accordion">
 <h3>heading 1</h3>
 <div id="activeDiv">
   <p>kksksksksk</p>
 </div>
 <h3>heading 2</h3>
 <div id="activeDiv1">
   <p>kksksksksk</p>
 </div>
 <h3>heading 3</h3>
 <div id="activeDiv2">
   <p>kksksksksk</p>
 </div>
</div>

not loading the content of a remote file

I have a file edit.blade.php. I want to load content in a div with load ajax

@if(Auth::check() && Auth::user()->admin)
@section('modal_body')
      @if($errors->any())
        <div class='alert alert-danger'>
            <a href="#" class="close" data-dismiss="alert">&times;</a>
            @foreach($errors->all() as $error)
                {{ $error }} <br/>
            @endforeach
        </div>
        @endif
    {{ Form::open(array('id' =>'formuser-create', 'role' => 'form', 'class' => 'form-horizontal')) }}
            <div class="form-group">
                {{ Form::label('user', 'Nombre de usuario', array('class' => 'col-md-4 control-label')) }}
                <div class="col-md-5">
                    {{ Form::text('user','', array('placeholder' => 'Introduce la contraseña...', 'class' => 'form-control input-md')) }} 
                    <div id="user_error"></div>
                </div>
            </div>
            <div class="form-group">
                {{ Form::label('email', 'Email', array('class' => 'col-md-4 control-label')) }}
                <div class="col-md-5">
                    {{ Form::text('email','', array('placeholder' => 'Introduce el email...', 'class' => 'form-control input-md')) }} 
                    <div id="email_error"></div>
                </div>
            </div>
            <div class="form-group">
                {{ Form::label('es_admin', '¿Es administrador?', array('class' => 'col-md-4 control-label')) }}
                <div class="col-md-5">
                    {{ Form::checkbox('es_admin','1') }}
                </div>
            </div>
@stop

I want to load the content in a div, but not get loading

enter image description here

Here my file where I call load, but I get how response status 404 not found

 var modal_title = $(this).find('.modal-title');
       var modal_body = $(this).find('.modal-body');
       //var modal_footer = $(this).find('.modal-footer');

       switch(accion)
       {
            case 'create':
               modal_title.html('<i class="fa fa-user-plus"></i> Nuevo usuario');   
               break;
            case 'edit':
               modal_title.html('<i class="fa fa-pencil fa-fw"></i> Editar usuario');
               modal_body.load('includes/edit.blade.php');
               break;

The error throwed is:

Failed to load resource: the server responded with a status of 404 (Not Found)

Design : One AJAX Call or multiple AJAX calls to get list of details

I have a use case where i want to fetch card details, I have 2 REST APIs

/user/{id}/getCards // gives list of cards for that user

In Back-end this is how it works, i make a call to one service which gives me list of cardIds, then i make another call to fetch card details for each cardId and return a list of cardDetails in json response.

/user/{id}/getCard/{cardId} // gives one card's detail with cardId for that user

In Back-end this is how it works, i make a call to second service passing cardId and json response contains only details of one card.

Given that i have CardIds already with me on page load, What is the best approach to follow.

Approach 1: Make only one call and get all cards and show in UI at once. It will cause me 2 calls in backend.

Approach 2: Iterate in javascript and make multiple AJAX calls one bye one (can be done async) and fetch one by one card details and show in UI. What if any call fails.

How to make nextPage button in javascript?

I want to make nextPage, prevPage button like below

below is my code

function getYoutubeList(boardname, index) {                                                                                                                                      
  $.ajax({                                                                                                                                                                       
    url:"/" + boardname + "/" + index,                                                                                                                                     
    method:'GET',                                                                                                                                                                
    dataType:'json'                                                                                                                                                              
  }).done(function(json, textStatus){                                                                                                                                                                                                                
    $('.container').append($('<div>', {style:"position:absolute;", class:"page_container"}));                                                                                    
    $('.page_container').append($('<div>').append($('<button>', {id:"shf_prev_btn", onclick:"prevPage()"}).text("prev")));                                                         
    $('.page_container').append($('<div>').append($('<span>', {id:"shf_page", role:"button"}).text(index)));                                                                     
    $('.page_container').append($('<div>').append($('<button>', {id:"shf_next_btn", onclick:"nextPage()"}).text("next")));

I want to make like this if button is clicked, nextPage(), prevPage() is called then page index is changed if nextPage(), index + 1 if prevPage(), index -1

also, else opinion is okay, I just want to make nextPage, prevPage button.

How to use JS in multi textbox

Here is my javascript code. I want to use this code multi time in multi textbox can anyone help me?

<--<script type='text/javascript'>
    function totalise()
    {    
        var quantity   = window.document.getElementById('quantity').value;
         var price   = window.document.getElementById('price').value;
        var result = tprice;
        result.value = price * quantity;
    }
</script>-->

AjaxFormComponentUpdatingBehavior onkeypress

I have a list of items, above which there is an input fields.
The input field is a filter, it should filter the list based on the text you key in to the input field.

For example : If you type "th", it should filter the list so that all the items should start with "th".

For this I am using AjaxFormComponentUpadingBehavior("onkeypress").
But this does not seem to be working they way it should.
When I key in something it clears up that and takes the cursor to the first letter of the input field.

I have tried onkeyup and onkeydown, and all of them act the same way.
For now I am doing the filter on a link click which works, but I want it to be as seamless as onkeypress.

Is there a way to achieve this? I am using wicket 1.4.x

CKEDITOR How do I send HTML data via json

I am trying to save my CKEDITOR data back to my CMS via ajax/json. However if there is binary inlined in the data (e.g. pasted image) the ajax fails. It seems I have trouble with special characters like \, ", etc.

I cannot find an encode/escape method that works which will escape all the HTML from the CKEditor.getData before I submit it via json.

mardi 5 mai 2015

pass specific element of array to ajax in joomla 3 module

I'm sure this is really simple but I have been trying to get this for ages. I have a foreach loop which iterates over an array of objects and displays them in an html table with a submit button which when clicked makes an ajax call to display some data in the same page.

This all works fine except it only passes the value of the last object from the array in the foreach loop instead of the value as displayed in that table row. I have tried to use a counter or to set and id for the but unsure how to get that specific value and pass it through.

Here is what is in my code:

<?php 
// No direct access
defined('_JEXEC') or die; ?>

<div class="status shelterbuddydog" >
<table class="profile_table">
   <?php foreach ($animalDetails as $profile):?>
    <tr>
        <td><?php echo $profile->photo;?></td>
        <td><span class="profile">Name:<?php echo $profile->name;?></span><br/>
            <span class="profile">Sex: <?php echo $profile->sex;?></span></<br/>
            <span class="profile">Age: <?php echo $profile->age;?></span><br/>
            <span class="profile">Breed: <?php echo $profile->breed;?></span><br/>
            <span class="profile">Animal Id: <?php echo$profile->animalId;?></span><br/>
            <span class="profile">Location: <?php echo $profile->shelter;?></span><br/>
            <?php $profile->summary;?>
            <input type="submit" id="summary" name="summary" value="VIEW MY PROFILE">
            </input></td>
    </tr>
    <?php endforeach;

</table>
<?php 
// Instantiate global document object

$doc = JFactory::getDocument();

$js = <<<JS

(function ($) {
 $(document).on('click', '#summary', function () {

    var profileSummary = {};
        profileSummary['photo'] = '$profile->photo';
        profileSummary['name'] =  "$profile->name";
        profileSummary['sex']  = "$profile->sex";
        profileSummary['age']  =  "$profile->age";
        profileSummary['breed']  = "$profile->breed";
        profileSummary['shelter']  = "$profile->shelter";
        profileSummary['animalId']  =  "$profile->animalId";
        profileSummary['summary'] =  "$profile->summary";

        request = {
                'option' : 'com_ajax',
                'module' : 'shelterbuddydog',
                'data'   : profileSummary,
                'format' : 'raw'
            };
    $.ajax({
        type   : 'GET',
        data   : request,
        success: function (response) {
            $('.status').html(response);
        }
    });
    return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);    
?>
</div>

Thanks for any help with this.

web pages with a lot of AJAX calls performance

My project is a web mobile app that uses a lot of AJAX calls to the server, to refresh and retrieve data, I'm using php scripts to get data from the server.

I noticed, and also users told me, that sometimes the application performance is very slow. I believe that it's because of the AJAX calls, I checked my server and it doesn't has any performance problems when this problem occurs.

It is very strange, because when the problem occurs, the application send AJAX request to the server and get stuck until the timeout error appear, and when sending it again, it performs perfectly and give an answer in less than a second.

I checked similar issues, and i saw that using php sessions can create file lock and every request needs to wait until the previous ends. This issue cancel the AJAX asynchronous process. I am not using sessions but maybe my case is the same and the php scripts perform file lock or other type of locking and cancel the asynchronous.

Anyone has any idea how can I solve this?

Thanks.

CORS support in NodeJS not working in Chrome

I'm using CORS in nodejs script as:

var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());

I'm using an AJAX request to fetch JSON data from another domain.

This works fine for all browsers namely, Mozilla Firefox and Safari. However, it does not work in case of Google Chrome. What am I doing wrong?

How to post data from a php file to another php file to add the data to database without using ajax

I have a php file (todo.php & todo.js) which collects some data from user and uses ajax to post the collected data to another php file (add.php) to be added to database . My issue is that I don't want to use ajax to post the data to the second php file (add.php). How do I change this. I have extracted the codes and shown below

//todo.js is called from todo.php to validate new todoEntry

function addToDo(){
    var descField = document.getElementById('nDesc');
    var percField = document.getElementById('nPerc');

    if( !validateField(descField) ){
        alert("Description " + errorMessage);
        return;
    }
    if( !validatePercentField(percField) ){
        alert("Percentage " + errorMessage);
        return;
    }

    //use ajax to post new entries to add.php which will add them
    ajaxCall(encodeURI('add.php?description=' + descField.value  
           + '&percentage=' + percField.value), function(response){
        if( response.status == 200 ){
            if( response.responseText.toString().indexOf
        ("success") != -1 ){
                //clear values
                descField.value = "";
                percField.value = "";

                //refresh table
                fetchToDo();
            }
            else
                alert(response.responseText);
        }
    });
    }

     From add.php:
    <?php
    session_start();

    if( !isset($_SESSION['username']) ){
        die("Your Session has expired. Please re-login to continue");
    }

    //get required data
    $description = trim(isset($_GET['description']) ? urldecode($_GET   
        ['description']) : "");
    $percentage = trim(isset($_GET['percentage']) ? urldecode($_GET
        ['percentage']) : "");

    //validate data
    if( empty($description) || empty($percentage) ){
        die("All fields are required!");
    }

    //connect to database
    include('connect.php');

    //insert data
    $stmt = $mysqli->prepare("INSERT INTO todo_entry VALUES (NULL, ?, NOW 
        (), NOW(), ?, ?)");
    $stmt->bind_param("ssi", $_SESSION['username'], $description,
         $percentage);
    $stmt->execute();

    if( $stmt->affected_rows > 0 ){
        $stmt->close();
        echo "success";
    }
    else{
        echo "An Error Occured: " . $stmt->error;
        $stmt->close();
    }

    //close database
    $mysqli->close();
    ?>

How to plot line chart using chart.js with ajax?

I am trying to plot a line chart using chart.js with AJAX but not successful yet. The chart is plotting very fine on normal form submission and window onload event but when I use AJAX I am not able to plot it. Actually I don't know how to achieve it when the data comes from server after ajax call.

HTML:

<form method="post" action="" id="order_form">
<label for="selogtype">Graph Type:</label>
<select name="selogtype" id="selogtype">
<option value="total_order_value">Total Order Value</option>
<option value="total_order_qty">Total Order Quantity</option>
<option value="avg_order_value">Average Order Value</option>
<option value="avg_order_qty">Average Order Quantity</option>
</select>
<br /><br />
<label for="radodays">Duration:</label>
<input type="radio" name="radoduration" id="radodays" value="days" checked='checked' /><label for="radodays">Days</label>
<input type="radio" name="radoduration" id="radodates" value="dates" /><label for="radodates">Date Range</label>
<div id="div_odays">
<select name="seloduration">
<option value="week">Last 7 Days</option>
<option value="month">Last 30 Days</option>
<option value="curweek">Current Week</option>
<option value="curmonth">Current Month</option>
</select>
</div>
<div id="div_odate">
<span class="spanodate">Start Date:</span> <input type="text" name="txtosdate" id="txtosdate" value="" />&nbsp;&nbsp;&nbsp;
<span class="spanodate">End Date:</span> <input type="text" name="txtoedate" id="txtoedate" value="" />
</div>
<input type="submit" name="btnorderchart" id="btnorderchart" value="Draw Chart" />
</form>
<div id="outer_ocanvas" style="margin-top:25px;">
<canvas id="ocanvas" height="400" width="800"></canvas>
</div>

JS:

// ajax part of chart //
// order //
$("#order_form").submit(function(){
var btnorderchart = $("#btnorderchart").attr("name") + "=" + $("#btnorderchart").val();
    $.ajax({
        beforeSend: function(){ sendRequest("outer_ocanvas"); },
        cache: false,
        type: "POST",
        dataType: "json",
        url: "ajax/chart.php",
        data: $(this).serialize() + "&" + btnorderchart,
        success: function(data){
            //alert(data.labels);
            //alert(data.points);

        var lineChartData = {
            labels : "[" +  data.labels + "]",
            datasets : [
                {
                    label: "Recent Orders",
                    fillColor : "rgba(150,150,245,0.2)",
                    strokeColor : "rgba(0,0,255,1)",
                    pointColor : "rgba(220,220,220,1)",
                    pointStrokeColor : "#fff",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(220,220,220,1)",
                    data : "[" +  data.points + "]",
                }
            ]

        }

        var ctx = document.getElementById("ocanvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: false
        });
        },
    });
return false;
});

In AJAX file chart.php (remote server file), I am sending the data through

    echo json_encode(array('labels' => $labels, 'points' => $points));

The data comes in correct format what we require in chart.js but I guess the below is the part which have something wrong:

        var ctx = document.getElementById("ocanvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: false
        });
        },

Because in normal way on page loading after form submission, we usually draw the chart by

window.onload = function(){
        var ctx = document.getElementById("ocanvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: false
        });

}

But in AJAX, i don't know how to do it after successful response from server.

EDIT:

After applying some solution given by some users on this website, my latest updated code in a standalone file is:

index.html:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX JSON Chart</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript">
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
    labels : ["January","February","March","April","May","June","July"],
    datasets : [
        {
            label: "My First dataset",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        }
    ]

}

window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
    responsive: false
});
}

// ajax part of chart //
$(document).ready(function(e) {
    $("#frm1").submit(function(){
var canvas = document.getElementById('canvas');
   ctx = canvas.getContext('2d');

 //  ctx = $('#canvas').get(0).getContext("2d");

    var btnchart = $("#btnchart").attr("name") + "=" + $("#btnchart").val();
        $.ajax({
            //beforeSend: function(){ sendRequest("canvas"); },
            cache: false,
            type: "POST",
            dataType: "json",
            url: "ajax/chart.php",
            data: $(this).serialize() + "&" + btnchart,
            success: function(data){
                //alert(data.labels);
                //alert(data.points);
                renderGraph(data.labels, data.points, ctx);
            },
        });
    return false;
    });
});

var renderGraph = function (labels, points, ctx) {
       // var ctx = $("#canvas")[0].getContext("2d");

        var lineChartData = {
                        labels: "[" +  labels + "]",
                        datasets: [
                            {
                                label: "Recent Orders",
                                fillColor: "rgba(220,220,220,0.2)",
                                strokeColor: "rgba(220,220,220,1)",
                                pointColor: "rgba(220,220,220,1)",
                                pointStrokeColor: "#fff",
                                pointHighlightFill: "#fff",
                                pointHighlightStroke: "rgba(220,220,220,1)",
                                data: "[" +  points + "]", 
                            }
                        ]
                    };


        var myChart = new Chart(ctx)
                                .Line(lineChartData, {
                                        responsive: false,
                                        animation: false
                                        });
                                        //myChart.update(lineChartData);

    }

function sendRequest(id)
{
    $("#"+id).html('<div style="width:100px; margin:0 auto;"><img id="loader-img" alt="" src="images/preloader.gif" width="100" height="100" /></div>');
}


</script>
</head>
<body>
<div style="width:30%">
    <div>
        <canvas id="canvas" height="450" width="960"></canvas>
    </div>
</div>
<form id="frm1" name="frm1" method="post" action="">
<input type="submit" name="btnchart" id="btnchart" value="Draw Chart" />
</form>
</body>
</html>

chart.php:

<?php
$labels = array('29 April 2015', '30 April 2015', '1 May 2015', '2 May 2015', '3 May 2015', '4 May 2015', '5 May 2015');
$points = array('100', '250', '10', '35', '73', '0', '25');
echo json_encode(array('labels' => $labels, 'points' => $points));
?>

On first time page loads, the output is:

enter image description here

After clicking button "Draw Chart", the output comes through AJAX is:

enter image description here

But when i hover my mouse over the image, it automatically converts into first image. Strange!!!

Validate and submit form without refreshing the page

I'm validating a form using Validate.js and submitting form values to third party app "Marketo" using their API. The submission happens after validation the form, As you see in the code there's no $.post or $.ajax method, Returning false also doesn't change anything, page still refresh after form submission,

e.preventDefault(); --> Doesn't help as well

  $("#contact_form").validate({


            rules: {
                txtfname: {
                    required: true,
                },
                txtlname: "required",

                txtPhone: {
                    required: true,
                    number:true
                },
                txtemail: "required",
            },
            messages: {
                txtfname: {
                    required: "Please enter your name",
                },
                txtlname: {
                    required: "Please enter your last name"
                },
                phone: {
                    required: "Please enter your phone number",
                    number: "Please enter valid phone number."
                },
                txtemail: {
                    required: "Please enter your email address."
                }
            },
            submitHandler: function(form) {

                paramsForm = form;
                // do other things for a valid form
                var fillFields = marketoMap;

                $.each(marketoMap, function(index, value) {
                    fillFields[index] = $('[name="' + value + '"]', form).val()
                });

                marketoForm.vals(fillFields);
                marketoForm.submit();

                return true;

            }

        });

fetching data from a different website's database

I have a specific website that you could search for specific data - like if you put in a name and address it will give you more info about that person.

Now, I'm interested in a specific type of result - for example - I want that site to give me every person that lives in this and that neighborhood and is between 30 and 40 years old etc etc... (that site doesn't give me the option to search for any keyword of any sort - just a specific name one at a time..)

Is it possible to create such a programm with absolutely no access to the code?

If yes, What would it take to acheive it?

I appreciate your response!

Thank you!!

Intercepting AJAX Requests freezes tab

I've lookup how to intercept an AJAX call and found the same code on multiple different threads: here and here, for instance.

I've modified the code like so:

(function(open) {
    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
        console.log("URL: ", url);
        open.call(this, method, url, async, user, pass);
    };
})(XMLHttpRequest.prototype.open);

All I'm trying to do is log the URLs of the AJAX requests on a given page.

Unfortunately, once I inject this code into Facebook, the entire screen freezes. It works on all other websites. Why is this messing up on Facebook?

Non-ajax POST fails to include select options populated by ajax

I have a normal form in which there is a hidden input that is fixed at page load, another hidden input that is dynamic, and two dynamic select boxes with design copied from http://ift.tt/1dLR50g :

<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<link href="/favicon.ico" type="image/x-icon" rel="icon"/><link href="/favicon.ico" type="image/x-icon" rel="shortcut icon"/>
<link rel="stylesheet" href="/css/itnrs.css"/>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"/><link rel="stylesheet" href="http://ift.tt/1ADi0R1"/>    <script src="http://ift.tt/wV40hO"></script><script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script><script src="http://ift.tt/1ADhYIN"></script><script>
//<![CDATA[
$(document).ready(function() {
$('#btn-add').click(function(){
    $('#select-from option:selected').each( function() {
            $('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        $(this).remove();
    });
});
$('#btn-remove').click(function(){
    $('#select-to option:selected').each( function() {
        $('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        $(this).remove();
    });
});
$('#btn-up').bind('click', function() {
    $('#select-to option:selected').each( function() {
        var newPos = $('#select-to option').index(this) - 1;
        if (newPos > -1) {
            $('#select-to option').eq(newPos).before("<option value='"+$(this).val()+"' selected='selected'>"+$(this).text()+"</option>");
            $(this).remove();
        }
    });
});
$('#btn-down').bind('click', function() {
    var countOptions = $('#select-to option').size();
    $('#select-to option:selected').each( function() {
        var newPos = $('#select-to option').index(this) + 1;
        if (newPos < countOptions) {
            $('#select-to option').eq(newPos).after("<option value='"+$(this).val()+"' selected='selected'>"+$(this).text()+"</option>");
            $(this).remove();
        }
    });
});
$('#pending').change(function() {
    $.ajax({
        url: 'recommend/'+$(this).val(),
        success:function(data,textStatus) {
            $("#students").html(data);
        }
    });
});
});

//]]></script></head>
<body>
    <div class="inner_content">
        <select id="pending">
<option value='2978'>511-150602_M   S511 - Const... (4)</option>
<option value='3063'>031_M1 S031-Basic O... (4)</option>
</select>
<form method="post" accept-charset="utf-8" id="form1" action="/url">
<div style="display:none;"><input type="hidden" name="_method" value="POST"></div>
<table>
<tr id="students">
<td>
<select id="select-from" multiple="multiple" style="clear:none" size='5'>
<option value="0">Not recommended</option>
</select>
</td>
<td>
<select id="select-to" name='UserId[]' multiple="multiple" style="clear:none" size='5'>
<option value="0">Recommended</option>
</select>
<input type="hidden" name="CourseId" value='0'/>
</td></tr><tr>
<td colspan="2">
<input type="button" id="btn-add" value="Add"/>
<input type="button" id="btn-remove" value="Remove"/>
<input type="button" id="btn-up" value="Up"/>
<input type="button" id="btn-down" value="Down"/>
</td></tr>
</table>
<button type="submit">Submit</button>    </form>        </div>
</div>
</body>
</html>

The contents of the select-from and select-to boxes are placeholders on page load. I select an option from the #pending select box the change event correctly send an ajax request to update the select-from options. I added options through #btn-add and the options are moved to #select-to. Chrome/Firefox developer console also showed that the CourseId hidden input and the select-to options are updated in the DOM. With Chrome when I click the submit button, the resulting POST request only include the hidden inputs (_method). Firefox is better: I got one selected option although I selected two options and select-to has a name of UserId[] and set to multiple.

What is the problem here?

Bandwidth vs database querying

I display images that I want the user to be able to delete. I do this with an AJAX request.

Is it best practise to:

  1. Pass just the ID of the image, use mysql to find what the filename of that record is, and then delete the file?

OR

  1. Pass the ID and the src of the image so I can just delete the image right away without looking it up?

One uses more bandwidth, the other more processing power.

Either way I need the ID because I have to do delete the record.

How do I get Amazon Signature 4 presigned URL to work with Ajax?

I can generate a working presigned URL to list part of an S3 bucket's contents.

It works fine if I paste it in the browser or use hurl.it

However, in a jQuery Ajax GET call it fails on the signature.

I viewed the request in fiddler and it does append one parameter to the request which is presumably the callback.

I tried that in hurl.it and it also failed. It seems for Amazon Signature 4 the extra parameter added by Ajax is a show stopper.

I would pass it along to my server to be signed but unfortunately Ajax is after the fact so AFAIK it is impossible to specify the callback parameter ahead of time.

The odd thing is using the C# SDK to generate a presigned URL this extra parameter in Ajax is NOT a problem. But unfortunately the SDK does not provide a mechanism I am aware of for generating presigned URLs to LIST a buckets contents. Only to get an object.

So the presigned URL is not an issue. Nor is the headers as far as I can tell. It seems that it wants all the query parameters to match what I sign.

I have been at this for 2 days almost and I am so close yet so far.

Any insight from experienced s3 / ajax users would be sorely appreciated.

Thanks!

Ajax on server not working, but on localhost

I have an ajax call that has a generated url via a paginator script:

"http://ift.tt/1FOpXIW"

Quite the same link is generated on the server:

"http://ift.tt/1PntWwW

The links are passed to this ajax call, in this case set as data:

$.ajax({
            url: (data) ? data : '/pricing/' + this.state.country + '/' + this.state.operation + '/' + this.state.optional,
            type: 'POST',
            data: {
                _token: window.token
            },
            success: function (e) {
                $('#loader-wrapper').fadeOut();
                this.setState({
                    paginator: true,
                    menuActive: false
                });
                this.handleArticles(e);
            }.bind(this),
            error: function (err) { alert(err);
                console.log(err);

            }

        })

On localhost the next page is loaded without any problems, but on the server I get an error 405 - Method Not Allowed.

I'm using a combination of react.js and laravel. My route for this kind of link is:

post('pricing/{country}/{operation}/{page}', 'PricingController@getArticles');

I only know method not allowed errors from a get request to a post route, but that's not the case as ajax is performing a post call though there is some "get data" attached, and more important, it's working on localhost. Does somebody have an explanation for this and how could I solve it?

I am tyring to fadeIn and fadeOut css background color with jquery ajax?

I am trying to fadeIn a background color in the beforeSend and fadeOut in the success with ajax. I don't know what I have done wrong. Help, please.

var data={
                              action: 'tag_user_update',
                                postSearchNonce : MyAjaxSearch.postSearchNonce,
                                                                tag : $(this).closest("a").text(),
                                                                users_id : $("#users_id").val()
                                                        }
                                                        $.ajax({
                                                                url: MyAjaxSearch.ajaxurl,
                                                                type:'POST',
                                                                cache: false,
                                                                data:data,
                                                    beforeSend: function() {
                                                                        $('.tag_link').animate({ backgroundColor:'yellow'},'slow');
                                                                                                          
                                                                                },
                                                                success: function(data){
                                                                          $('.tag_link').animate({ backgroundColor:'white'},'slow');
                                                                }
                                                                        });//ajax

jQuery AJAX call returning 403 Forbidden error when passing Rgraph image data

I am working on a project, where I have implemented a couple of graphs/charts using the Rgraph PHP library. In my script I do the following for the graphs:

  1. Calculate the graph points and draw the graph using the Rgraph Draw() method.
  2. Create an image data variable using the canvas.toDataURL() method.
  3. Pass this image data variable to the server using jQuery AJAX $.post() method.
  4. Save the image to server via the PHP script.

Everything in this solution works great on my localhost, however on the development server, the AJAX request that passes the image data returns a 403 Error.

I logged the data on both the client and server side to determine the issue. Client side logging confirms the imageData variable being passed looks correct. However server side logging confirms that the imageData variable being passed is what is causing the issue.

There was a very similar question posted last year about this, however they were unable to determine the root cause of this. Can anyone help point me in the right direction of resolving this?

Possible reasons:

  • An issue between server configurations, but if this is the case, I'm a little unsure where to start digging next to resolve this.
  • A possible data encoding issue, but if this the case, why does it work on one server and not the other?

My Relevant Javascript:

radar.Set('chart.contextmenu', [
     ['Get PNG', RGraph.showPNG],
     null,
     ['Cancel', function () {}]
]);

radar.Draw();   

var imageData = radar.canvas.toDataURL("image/png");

console.log('imageData: ' + imageData);
console.log('filename: ' + 'tmpRadar<?php echo $us['UsersSurvey']['user_id']; ?>-<?php echo $survey['Survey']['id']; ?>.png');

$.post("/Surveys/save_chart", { 
    src     : imageData, 
    filename: 'tmpRadar<?php echo $us['UsersSurvey']['user_id']; ?>-<?php echo $survey['Survey']['id']; ?>.png'
});

Client Side Logging:

imageData: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABLAAAAOECAYAAACxbcj6AAAgAElEQ…AgQIAAgVECAqxR49YsAQIECBAgQIAAAQIECBAgQKCfwP8CXHJ+WDHVMbcAAAAASUVORK5CYII=
filename: tmpRadar19-1.png
POST http://ift.tt/1cjRtTp 403 (Forbidden)

PHP Function called by AJAX:

public function save_chart() {
    if($this->request->is('ajax')) {
        $this->log('request data: '.print_r($this->request->data, true));

        $filename = $this->request->data['filename'];

        $src     = $this->request->data['src'];
        $src     = substr($src, strpos($src, ",") + 1);
        $decoded = base64_decode($src);

        $fp = fopen(WWW_ROOT.'files/graphs/'.$filename,'wb');
        if(fwrite($fp, $decoded)) {
            fclose($fp);
            return json_encode(array('success' => '1'));
        } else {
            fclose($fp);
            return json_encode(array('success' => '0'));
        }
    }
}

Title Tag Nested inside itself with jQuery PHP Load

I have a dynamic site that loads only the body when a usr clicks a page. I am trying t change the title tag, but am getting no luck.

HTML:

<head>

    // Title tag is contained in the php file
    <?php include (BASEPATH . "includes/widgets/pageTitle.php"); ?>
</head>

JavaScript/jQuery:

$(document).on('click', 'a', function(e) {

    // Page url of destination
    var pageurl = $(this).attr('href');
    var baseurl = "http://localhost/offstreams/";

    // prevent page from loading
    e.preventDefault();

    // Empty info inside the body class and reload new info
    // THIS WORKS PERFECTLY
    $('.body').empty().load(pageurl + " > .body > *");


    //!!!!!!!!!!!!!!!!!!!!!
    // THIS DOES NOT WORK
    //!!!!!!!!!!!!!!!!!!!!!
    $('title').empty().load(pageurl + "> title > *");


    // Push the URL state
    if(pageurl!=window.location){
        window.history.pushState({path:pageurl},'',pageurl);
    }


    //stop refreshing to the page given in
    return false;
    }
});

A Snippet of PHP code:

//Band page title tag
if (isset($_GET['member']) && isset($_GET['edit']) && isset($_GET['band'])){
    $band_id = $_GET['band'];
    $sql = "SELECT `band_name` FROM `bands` WHERE `band_id` = '$band_id'";
    $query = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_array($query)){
        $band_name = $row['band_name'];
        echo "<title>" . $band_name . " | " . "Offstreams</title>";
    }

An example output on actual load would be Count to Four | Offstreams, which is what I want.

When I do the ajax load, the website works, but the title tag gives the default url like localhost/offstreams/etc... and the title tag turns into

<title>
    <title>Count to Four | Offstreams</title>
</title>

Does anyone know why?

Datatables 1.10 modify custom HTML param to send to server

How do I modify a custom HTML variable to send to the server after dataTables has been initialized?

I can send custom data using the ajax paramater before dataTables has been initialized.

I have a custom filter that I want to use add data to the request after dataTables has been initialized and then redraw the data.

CORS ajax request clarification

So I have an API deployed on a cloud service. For testing purposes I use various HTTP clients like Postman, Paw and RestClient to send request to my API and they all work just fine. But when I send an AJAX request from Browser either with jQuery, reqwset or any other, I get the following error:

XMLHttpRequest cannot load {/path/to/my/api/on/google-app-engine}. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access

So Why does an HTTP client work but browser throws an error? Is there any risk if enable CORS on the server?

Wordpress ajax call returns entire html page

I am migrating a web app into my wordpress site. I would like to house the app on one wordpress page. When I initialize the content with an ajax call on page load, I receive what looks like the html string for the entire page.

php code housed in functions.php

<?php 

function my_scripts_method() {

    if (is_page('testpage')) {
        wp_register_script(
            'ajaxexample',
            get_template_directory_uri() . '/js/ajaxexample.js',
            array('jquery')     );
        wp_enqueue_script('ajaxexample');
        wp_localize_script( 'ajaxexample', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); 
    }
}
add_action('wp_enqueue_scripts', 'my_scripts_method');




    function example_ajax_request() {


        if ( isset($_REQUEST) ) {

            $fruit = $_REQUEST['fruit'];

            // Trivial action
            if ( $fruit == 'Banana' ) {
                $fruit = 'Apple';
            }


            // return this to js function
            echo $fruit;



        }

       die();
    }

    add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
    add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

and the javascript file ajaxexample.js

jQuery(document).ready(function($) {


    // We'll pass this variable to the PHP function example_ajax_request
    var fruit = 'Banana';

    // This does the ajax request
    $.ajax({
        url: ajax_object.ajaxurl,
        data: {
            'action':'nopriv_example_ajax_request',
            'fruit' : fruit
        },
        success:function(data) {
            // This outputs the result of the ajax request
            alert('data:'+data);
            console.log(data);
        },
        error: function(errorThrown){
            alert(errorThrown);
            console.log(errorThrown);
        }
    });  

});

When I load 'testpage,' my ajax return looks something like:

data:


<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" lang="en-US">
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" lang="en-US">
<![endif]-->
<!--[if !(IE 7) | !(IE 8)  ]><!-->
<html lang="en-US">
<!--<![endif]-->
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <title>testpage | TITLE </title>
    <link rel="profile" href="http://gmpg.org/xfn/11">
    <link rel="pingback" href="MYSITEURL/xmlrpc.php">
    <!-- start favicon and apple icons -->
                            <!-- end favicons and apple icons -->
...

My understanding is that the ajax request successfully reaches admin-ajax.php but I do not understand the return, as I expect the wp file to pass the content to my example_ajax_request function. How can I get my ajax request to be handled properly by the intended php script?

Using drag and drop to build an image

I'm trying to build a cake dragging some items to it, and then that I can download the image with all of the items dragged, But I don't want the image of the item disappears , I want that count every time that I drag it. Has anyone built something like this before? I need an example please, I have to do it in javascript or Jquery.

This is my gui: http://ift.tt/1GXNNAJ

Minicart product amount display Magento

I have a question about the minicart for example: If I have 3 unique products in my cart with 30 of each, the minicart shows a total amount of 90.

How can I make the minicart show the number of unique products, so only 3?

Why form can be used to download file but AJAX cannot?

Given two codes, both trying to trigger server to give back of downloadable file using http header in response i.e. "Content-Disposition", "attachment; filename=filename.ext:

  1. Using form, $('<form></form>').attr('href', path) ... .submit().remove();

  2. Using ajax, $.ajax(url, config);

I would like to know why browsers handle that differently, since form and ajax are not quite different in term of sending request and receiving servers responses. I have search around, but nothing is convincing.

PS: I'm aware of CROS, but in this case cross domain is not an issue here.

How to Bind Data to kendo grid by passing date from kendo datepicker?

I am new in Kendo UI, I have one kendo DatePicker and one Kendo GridView. After selecting a date from DatePicker according the data should bind to the Kendo GridView. I use jquery with Ajax and my jquery function is

enter image description here

List<MDA.AppEntities.Orders.OrderList> objConsults = new List<MDA.AppEntities.Orders.OrderList>(); 
objConsults = DataFacade.Operations.GetCustomerOrderDetailsByCustomerID(Patientid,startDate,en‌​dDate ); 
return new PrimeJsonResult { MaxJsonLength = int.MaxValue, JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new GridModel<MDA.AppEntities.Orders.OrderList> { Data = objConsults } };

It is going inside success: function(data), but not executing inside code and jump back to $.ajax(), and I don't understand why.

jquery replace HTML div value

I am forming the div dynamically on document load like below. I have a ajax call and on response fro the ajax call i want replace the value 'right' with the value from the ajax call using jquery.

Basically i want to replace the value for the text div mentioned below once ajax has the success data.

            var beginContainer = '<div class="container">';
            var endDiv = '</div>';
            var beginInner = '<div class="inner">';
            var text = '<div class="text" id=3 style="color:#0000FF" align ="center">';
            var append = beginContainer + beginInner + text + 'Number of sensors' + endDiv + text + '10cents/sensor' + endDiv + endDiv + beginInner + text +'right'+endDiv +endDiv;
            $('#content').append(append);  
            var beginContainer = '<div class="container">';
            var endDiv = '</div>';
            var beginInner = '<div class="inner">';
            var text = '<div class="text" id=4 style="color:#0000FF" align ="center" value="kkk">';
            var append = beginContainer + beginInner + text + 'Total Bill' + endDiv + text + 'Month-to-Month' + endDiv + endDiv + beginInner + text +'right'+endDiv +endDiv;
            $('#content').append(append); 

Ajax stop php page refreshing when navigating away

I joined Stack overflow today, it's my first time here! I'm hoping I'll get my answer. My Questions is simply this: How do I stop a php Page from Refreshing When Navigating away to another php page using AJAX. (please note im not as good as I am in php compared to Ajax, so im a Ajax beginner)

For example this is my coding on my home page: on home.php:

(A: I don't want this php file to refresh no matter where I navigate too, unless I'm navigating to a page where doesn't include this file)

(Same as above 'A')

Coding inside those php files: see below: vis1.inc.php

<!doctype html> <html> <head> <div id="vinfo"> <meta name="description" content="blah"> <title>blah</title> <link type="text/css" rel="stylesheet" href="style/style.css"> <div id="wrapper"> <div id="fileWrapper" class="file_wrapper"> <div id="info"> </div> <label for="uploadedFile"> Drag & drop </label> <input type="file" id="uploadedFile"> </input> </div> </div> </div> </head> </html>

Code for: vis.inc.php

<!doctype html> <html> <footer> <link type="text/css" rel="stylesheet" href="style/style.css"> <div id="v_wrapper"> <canvas id='canvas' width="1950" height="800"><script type="text/javascript" src="js/hav.js"></script> </canvas> </div> <div id="c2"> <small>random info<a href="website name" target="_blank">website name - Owner</a></small> </div> </footer> </html>

That's all. Thank you. I hope I my question wasn't too vague. Thanks again.