using ajax to send javascript data to php - javascript

so i've been looking at how to record and send client-side data to a php server.
i'm not sure of the correct terminologies, but i think that using an ajax call to send a post to the php server is the most elegant way to solve this problem.
so i decided to implement this data exchange:
$("#"+activityInfo.ID).click(function(){
window.open(activityInfo.URL+"userId="+$("#userid").val()+"&activityId="+activityID+"&classId="+classID);
classid = classID;
activityid = activityID;
$("body").append("class: " + classid);
$("body").append("id: " + activityid);
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { 'cid':classid , 'aid':activityid } );}); //i think this is the important line that sends the data
and the corresponding php file (updateProgress.php)
$class_id = $_POST['cid']; //receives the data
$activity_id = $_POST['aid'];
i'm not sure why this is the case, but class_id and activity_id variables always return an empty value.
i understand somewhat that the client-browser is on a page that is preloaded by information from a php server. but there were posts that said this is a possible way to communicate back to the php server with information from the client. i'm not really sure what is going on b/c at this point i don't really know what questions to ask.
one of the example explanations that i had been following:
Ajax passing data to php script
thanks for the help.
i've also played around with start_session() and storing/loading session variables as a way to transfer data information. this works but only for php <-> php communication. it does not for saving javascript variables, so i couldn't really use $_SESSION = ..... in my javascript code.

you need to get the cid and aid outside of the single-qouts while using $.post! try this:
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { cid:classid , aid:activityid } );

Related

Inserting data from JS script into mysql database

I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.

Ajax inside wordpress security

Before I get to the question, let me explain how we have things set up.
We have a proxy.php file, in which class Proxy is defined with functions that call upon a rest for creating/editing/getting Wordpress posts, fields etc.
Then, we have a proxyhandler.php, in which Proxy class is initialized and serves as a handle between proxy.php and a javascript file.
In javascript file we have an ajax call to proxyhandler.php in which we send our secret and other data.
Now, the problem arises here:
We define the secret through wp_localize_script, by using md5 custom string + timestamp. We send the encripted string and timestamp through ajax to proxy handler, where we use the previous (hardcoded inside proxyhandler) string and timestamp to generate a md5 string again, and check the one sent against the one generated. If they are the same, we continue by doing whatever was requested, if they dont fit, we just return that the secret didn't match.
Now, the real issue comes here - by using wp_localize_script, the variable for the secret is global and as such, anyone can utilize it via dev tools and can send any ajax request to proxyhandler that they want.
What would be the proper procedure to make it more secure? We've thought of doing this:
Instead of using wp_localize_script, we put the script inside a php file, we define the secret using a php variable and then simply echo the secret file into ajax. Would this be viable, or are there any other ways?
Instead of sending an encrypted string in global scope, then check against it, you should use nonce in your AJAX request:
var data = {
action: 'your_action',
whatever_data: who_know,
_ajax_nonce: <?= wp_create_nonce('your_ajax_nonce') ?>
};
Then, use check_ajax_refer() to verify that nonce:
function your_callback_function()
{
// Make sure to verify nonce
check_ajax_refer('your_ajax_nonce');
// If logged in user, make sure to check capabilities.
if ( current_user_can($capability) ) {
// Process data.
} else {
// Do something else.
}
...
}
Depend on the AJAX METHOD, you can use $_METHOD['whatever_data'] to retrieve who_know data without needing to use wp_localize_script().
Also remember that we can allow only logged in users process AJAX data:
// For logged in users
add_action('wp_ajax_your_action', 'your_callback_function');
// Remove for none logged in users
// add_action('wp_ajax_nopriv_your_action', 'your_callback_function');
The final thing is to make sure NONCE_KEY and NONCE_SALT in your wp-config.php are secure.

load entire json file into variable as array

I want to take an external json file (locations.json) and load the contents into a variable. I would then like to use this variable using the information provided here: http://www.json.org/js.html
I've had a lot of trouble trying to load the external json to a variable. I've looked at this ( load json into variable ) page quite a bit, and none of that actually populates the variable. When displaying the variable's contents later, it appears to be empty.
$("#testContain").html("<p>" + json + "</p>");
Using methods listed in the last link, this dispays "undefined".
The json file that I am using looks like this:
[{"id":"1","locname":"Dunstable Downs","lat":"51.8646","lng":"-0.536957","address":"Chiltern Gateway Centre","address2":"","city":"","state":"England","postal":"","phone":"","web":"http:\/\/www.nationaltrust.org.uk\/main\/w-dunstabledownscountrysidecentrewhipsnadeestate","hours1":"","hours2":"","hours3":""},
{"id":"2","locname":"West Delta Park","lat":"45.5974","lng":"-122.688","address":"N Broadacre St and N Expo Rd, Portland","address2":"","city":"","state":"OR","postal":"","phone":"","web":"http:\/\/en.wikipedia.org\/wiki\/Delta_Park","hours1":"","hours2":"","hours3":""}]
Anyone have any suggestions?
The problem is that the request is asynchronous. You could make a synchronous call as suggested by the accepted answer to the question that you linked to, but that is generally not a good idea as it will freeze the browser completely while it is waiting for the response.
The variable is assigned just fine, but when you use it after requesting it, you have to make sure that it's after getting the response, not just after sending the request. Using the value in the callback for the getJSON method is the easiest way to make sure that you have the value:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
// here you have the value
});
// here you don't have the value, as this happens before the response arrives

query database with knockout.js / jquery

I'm following a knockout.js tutorial for loading data from the server and I'm a bit confused on where the query is actually coming from. The tutorial can be found here and the specific bit of code I'm talking about is on page 2.
I understand the necessity for using ajax, but I'm not actually sure how to make a query based on what they're doing.
$.getJSON("query/tasks", function(allData) {
var mappedTasks = $.map(allData, function(item) { return new Task(item) });
self.tasks(mappedTasks);
});
The description of what is taking place:
On this server, there's some code that handles requests to the URL /tasks, and
responds with JSON data. Add code to the end of TaskListViewModel to request that
data and use it to populate the tasks array:
So, say I'm working with PHP and want to make the following query to find the tasks:
$tasks= mysql_query("select * from tasks");
Where would I place this query? I see it's somehow related to /tasks, but what's going on here exactly?
edit, would I do something like this? So essentially the $.getJSON request is calling a function residing at query/tasks in this case?
//assuming this is on query.php
Class query{
function tasks(){
$task = mysql_query("select * from tasks");
return $task;
}
}
Essentially what is happening is that you are making an AJAX call to some endpoint on your server that will return JSON data. I haven't worked with PHP in quite a while, but you are basically requesting a resource on your server. Let's say that your website is http://www.myawesomesite.com. If you were to make an AJAX request to "/tasks", there will be a request to http://www.myawesomesite.com/tasks that is expected to return JSON data.
That resource can be another page, a web-service of some kind, whatever you have available. I work primarily in the ASP.NET MVC space, so my experience is different from PHP, but the idea is the same. You are making a request to a resource on your server to return JSON data. Whatever that resource is is up to you. HTH!

Pass data to database using javascript Onclick

I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.

Categories