AdamSC
AdamSC

Reputation: 360

Save jQuery to Database?

Currently I'm running a site that grabs some third-party API data that grabs a currency price saves it as "msg.data.closing_price.value" and then allows me to compare it against other products in a local price by creating strings like this:

$('#dollar-price').html('Ð' +Math.round10 (1/msg.data.closing_price.value, -2));

I'm looking for a way to be able to take the output of the jQuery above add a timestamp and throw it into a database so that I can later add some historical data, yet I haven't been to successful in finding a method, at least one that I understood

As a really new dev who struggled even getting jQuery going in the first place I'm at a total loss and could use a shove in the right direction!

Upvotes: 0

Views: 61

Answers (1)

LSerni
LSerni

Reputation: 57408

You cannot do this in jQuery - not simply at least. What you can do is take the value and send it to some PHP-side script that may do what you want:

$.post( "/path/to/script", { price: msg.data.closing_price.value } );

and in the script - after some suitable input checks -

$price = $_POST['price'];
if (is_numeric($price)) {
    // some range checks maybe

    // Insert into database proper. PDO recommended.
    insertRows($table, array(
        'price' => (float)$price;
    ));
}

The timestamp may be automatically added by the database using the appropriate data type and default (DEFAULT CURRENT_TIMESTAMP), or you can get it yourself with time() or any suitable function. Beware the timezone, and never trust the data sent by the client.

What you really ought to do, though, is to check out the third-party API and see how it is called and what does it return. You may use Firebug or Chrome WebDev to do this. Suppose it's a simple POST call to /othersite/pricelist/productCode, then all you need to do is to reimplement the call using cURL (or maybe even file_get_contents($url); if it is a GET call), on the server; the client need not enter into this. Using cron jobs you may then also save the data regularly without user intervention, plot them using RRD from PHP, and so on and so forth.

Upvotes: 1

Related Questions