Julia
Julia

Reputation: 397

load data to server using jquery

I have read a lot about loading or posting data to server via jquery, but can`t find the right one for me. I have a bunch of inputs and data obtained from them I contain in a list (array).

I need to load it to server. I think I should do it like this

client side

<html>
<head>
<title>the title</title>
<script type="text/javascript" 
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
   $("#driver").click(function(event){
      var name = $("#name").val();
      $("#stage").load('/jquery/result.php', {"name":name} );
  });
});
</script>
</head>
<body>
    <p>Enter your name and click on the button:</p>
    <input type="input" id="name" size="40" /><br />
    <div id="stage" style="background-color:blue;">
         STAGE
    </div>
    <input type="button" id="driver" value="Show Result" />
</body>
</html>

server side

<?php
if( $_REQUEST["name"] )
{
   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
}
?> 

got it from here passing data to server but in my case I need to load a list (array) and I have no idea how the php part must be written in python at server side. Also need to mention that I`m using Flask.

I will really appreciate any help.

EDIT

Well, I`m almost there!

Except of a strange thing that happens

home.html

<script>
var dict = {}
$(document).ready(function(){
    $("#save").click(function(){
        var ids = []
        var datas = []
        $(".result").each(function() {
            ids.push(this.id);
            datas.push(this.value);
        });

        for (var i = 0; i < ids.length; i++){
            dict[ids[i]] = datas[i];
        }
        console.log(ids);
        console.log(datas)

    });
});

var bla = {1:'4', 2:'5', 3:'6', 4:'7', 5:'4', 6:'5', 7:'6', 8:'7'}

console.log(dict)

$(function() {
    $('a#calculate').bind('click', function() {
        $.getJSON('/add_numbers', dict, function(data) {
            $("#result").text(data.result);
        });
        return false;
    });
});

</script>
      <p><input type=text size=5 name=a> +
         <input type=text size=5 name=b> =
         <span id=result>?</span>
     <p><a href=# id=calculate>calculate server side</a>

     <div id="chosen">
            {% for key, value in selected.iteritems() %}
                    {{value[0]}}<input type="text" id="{{key}}" size="5" class="result">{{value[1]}}<br>
            {% endfor %}
            <input type="submit" id="save" value="save">
    </div>

views.py

@app.route('/home', methods=['GET', 'POST'])
def show_work():
    demount = DemountForm(request.form)
    tile = TileForm(request.form)
    chosen = []
    for each in session['data']:
        chosen.append(each)
    selected = methods.get_selected(chosen)
    return render_template('home.html', demount=demount, tile=tile, selected = selected)

@app.route('/add_numbers')
def add_numbers():
    a = request.args.get('1', '0', type=str)
    return jsonify(result=a)

I got solution from flask "ajax with jquery".

BUT, here is a problem.

In case I use that strange variable bla in template $.getJSON('/add_numbers', bla, function(data) it works just fine. It works because data in bla is global and it is seen in getJSON and this function send data to /add_number, add to URL data from bla like so: "http://localhost:5000/add_numbers?1=4&2=5&3=6&4=7&5=4&6=5&7=6&8=7"and then result comes back with return jsonify(result=a).

The problem comes when I use dict in $.getJSON('/add_numbers', dict, function(data).

After the previous function, where dict is formed $(document).ready(function(){ $("#save").click(function(){... data from dict is added to current URL like this:http://localhost:5000/home?1=6&2=6&3=6&4=6&5=6&6=6 and variable dict does not contain data anymore.

As far as I understand this happens due to, let`s say, URLs, to which each function is related.

Does anyone know how this problem can be solved?

Upvotes: 1

Views: 1862

Answers (3)

Julia
Julia

Reputation: 397

Ok, so here is what I came up with.

home.html

<script>
$(document).ready(function(){
      $('#calculate').bind('click', function() {
             var dict = {}
         var ids = []
         var datas = []
         $(".result").each(function() {
            ids.push(this.id);
            datas.push(this.value);
         });

         for (var i = 0; i < ids.length; i++){
            dict[ids[i]] = datas[i];
         }

         console.log(ids);
         console.log(datas)
         console.log(dict)

         $.getJSON('/add_numbers', dict, function(data) {
            $("#result").text(data.result);
         });
         return false;
      });
});
</script>

view.py

import methods

@app.route('/add_numbers')
def add_numbers():
    ident = []
    amount = []
    ids = [1,2,3,4,5,6]
    for each in ids:
        val = request.args.get(str(each), '0', type=str)
        if int(val) != 0:
            ident.append(each)
            amount.append(int(val))
    res = methods.calc(ident, amount)
    return jsonify(result=res)

methods.py

def calc(ids, amount):
    prices = db_session.query(Work.price).filter(Work.id.in_((ids))).all()
    prices = [each[0] for each in prices] 
    i = 0
    result = 0
    while i < len(ids):
        result += prices[i]*amount[i]
        i += 1
    return result

It works! Thanks to everyone.

Upvotes: 0

andmart
andmart

Reputation: 552

In Flask, you can do something like that

from flask import Flask, request
import json
import random

app = Flask(__name__)


@app.route('/')
def main():
    return """<html>
                   <head>
                      <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
                      <script>
                           $(document).ready(function(){

                                $('#btnSend').click(function(){

                                    var  fruits = ["apple", "banana", "orange"];

                                    $.ajax({
                                      type: 'POST',
                                      url: '/do_something',
                                      data: {"fruits":JSON.stringify(fruits)},
                                      success: function(data){
                                        alert(data);
                                      }
                                    });
                                });

                           });
                      </script>
                   </head>
                   <body>
                    <input type="button" id="btnSend" value="send fruits">
                    </body>
                   </html>"""


@app.route('/do_something', methods=['POST'])
def view_do_something():

    if request.method == 'POST':
        fruits = json.loads(request.form.get("fruits"))
        fruit = fruits[random.randint(0, len(fruits))]
        return fruit
    else:
        return "no fruit"

if __name__ == '__main__':
    app.run()

Run script and try

Upvotes: 0

Sjoerd de Wit
Sjoerd de Wit

Reputation: 2413

normally data is passed to the server with ajax this is an example that could work.

      $.ajax({
          type: 'post',
          url: '/jquery/result.php',
          data: {"name":$('#name').val()},
          success: function(data){
            //maybe do something with response (data)
          }
        });

Getting this info on server side goes like this

<?PHP $name = $_POST['name']; ?> 

after that u can use the name variable whatever way u like

Upvotes: 2

Related Questions