how to run a MySQL query using JavaScript - javascript

I want to run MySQL query's on command without reloading the page. I think JavaScript can do this but i am unsure how. What i want to do is have a form with an return id field and when you fill out the form once with the return id and come back later and use that return id and it fills in in a lot of the content for them to save time.

Javascript cannot run MySQL Queries itself; however, you can use ajax to make a call to the server to retrieve the data. I like to use jQuery's ajax() for my ajax needs.
Here is an example of how jquery's ajax() method works:
$.ajax({
url: "pathToServerFile",
type: "POST",
data: yourParams,
dataType: "json"
});

You can't query with pure javascript. It has to be done from a hook that is setup on a backend.
This tends to be done with ajax.
Moreover, if querying were available from client side, then everyone could see your connection string.

You'll need to have a backend script do the query - JavaScript, being an entirely client-side language, has no say-so in what goes on with your MySQL server.
What you'll need to do is pass the parameters you want in your query to whatever server-side language you're using via AJAX, and have the script create and process the query as you wish.
DO NOT create the query in javascript and pass it to the server - this is VERY unsafe as it allows anyone to run whatever queries they want.

Using ajax will do the job. But you'll still need a server-side language for the ajax to call to.
Using jquery with ajax will be even quicker!
$.ajax({
type: "POST",
url: "someserversidelangfile",
data: "" //pass data through this variable
}).done(function( msg ) {
//do so
});

Everyone's all about ajax so here's an example on how to send data with vanilla JavaScript and fetch the response back. It will be a nonsense example and will use non-PDO MySQL connection. Backend is PHP, but script.js file is practically the same for NODE.js backend.
script.js
/* mode options are cors, no-cors (only send, no response) and same-origin */
fetch('not-ajax.php', {
method: 'post',
mode: 'same-origin',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
body: JSON.stringify({
/**
* FYI: For this particular case you would actually prefer to have this snippet
* just before ending </body> tag so it get's actual width of the window minus
* the width of the scrollbar if there is one. If you use it in an external
* script it's the same as using window.innerWidth and window.innerHeight.
**/
'screen_width': document.documentElement.clientWidth,
'screen_height': document.documentElement.clientHeight
})
})
/**
* You need this part as well if you send json-encoded data back from backend.
**/
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
not-ajax.php
<?php
include 'connection.php';
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
// Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
// $decoded can be used the same as you would use $_POST with ajax
$decoded = json_decode($content, true);
/**
* Sure enough you can use a SELECT statement, get the data from the database,
* manipulate it to your heart's content, and then send it back to fetch
* function in JavaScript for further manipulation and usage.
**/
$sql =
"INSERT INTO used_screen_dimensions (
) VALUES ( ?, ? )";
$statement = $connection->prepare($sql);
/**
* first parameter is a string with characters
* 'i' for integer,
* 'd' for double,
* 's' for string,
* 'b' for blob
* in the respective order to all other binded parameters
**/
$statement->bind_param('ii', $decoded['screen_width'], $decoded['screen_height']);
$result = $statement->get_result();
$statement->close();
/**
* You may only echo out one thing, but it doesn't have to be a boolean.
* You can (and should) echo an object with more info including what error
* it is.
**/
if(! is_array($decoded)) {
echo 0; //If json_decode failed, the JSON is invalid.
return;
} else {
// Send error back to fetch.
if (!$result) {
echo 0; // couldn't insert to database
return;
}
echo 1; // Success
}
} else {
echo 0; // Wrong content type
}
Don't know why I went and typed this answer out by hand. There's bound to be errors.

JavaScript can't run MySql commands.You can use JQuery with Ajax.
like this :
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

Related

AJAX PHP - response is an object with null values

I have a small problem maybe because i am a beginner in ajax programming, i make a function in ajax jquery that calls a php file, which makes a request to the database for informations about a player. When the php file replies to the ajax function, i get an object with null values as an answer.
Is there a line i've missed in my code? or something i forgot to do?
Here is my code,
AJAX function:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
And the php file :
<?php
include("connexion_bdd.php");
$_GET['mail'] = $mail;
$req = $bdd->prepare('SELECT * FROM joueurs WHERE mail = ?');
$req->execute(array($mail));
$reponse = $req->fetch();
$return = array();
$return["user_name"] = $reponse["nickname"];
$return["profile_pic"] = $reponse["profile_pic"];
$return["user_id"] = $reponse["id"];
print(json_encode($return));
?>
In the success of the ajax function, i get this :
{"user_name":null,"profile_pic":null,"user_id":null}
Although the database is not null.
Where do you think is my mistake? php file or ajax function? or both?
Thanks for helping :)
Edit :
I've changed my code according to the remarks i had on the way i pass the variable AJAX->PHP.
I've tested my sql query on my database and it works fine, but i still have the problem of null values after i pass the object from my php file to the succes function of the AJAX/JS file.
Any ideas about what's wrong with my code?
Thanks again.
You have two problems here.
First, you are not sending the mail parameter in your jQuery AJAX request. You need to append the GET parameter to the end of the URL under the url key:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php?mail=youremail#gmail.com",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
The second problem is that you have your $mail variable assignment in your PHP script backwards. It should be
$mail = $_GET['mail'];
$_GET['mail'] is automatically set by PHP when you call the script with a GET request. But since you are referencing $mail in your prepared SQL statement, you want to assign the value of $_GET['mail'] to $mail.

Ajax receive a collection of objects from Laravel

I currently am attempting to create my own instant messenger for my site (NOT using a plugin - am attempting to hand make this for learning purposes) and I am looking to try to send an ajax request to the server for a list of all messages between two users. My question is this: can ajax 'read' a collection of Message objects sent from Laravel (doubt it) or does it need to be formatted in a certain way/manner? I initially thought to use lists to get the sender_id along with the message (the order is by date by default), however, I don't think that javascript can read PHP's (not)-arrays. The only viable solution I have came up with thus far is to send either 1 array with sender_id followed by the message for the entire conversation OR 2 arrays- one with all sender_id's in order and a second with all messages in order.
Thanks.
You can use JSON for communicating between PHP and JavaScript (look up PHP json_encode and json_decode functions), it'll allow you to pass complex arrays almost natively between the languages.
EDIT: a few examples to give some indication how it works, I'm using jQuery for my examples here
Requesting information from a PHP script via AJAX:
$.ajax({
method: 'GET',
dataType: 'json',
success: function(data) {
for (i in data.messages) {
output(data.messages[i]);
}
}
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can output:
$messages = array(
array(
'id' => 1,
'message' => 'Awesome',
'sender' => array(
'id' => 1, 'name' => 'John',
),
),
);
echo json_encode(array('messages' => $messages));
Sending information using JSON via AJAX:
// Example data object, you can have this infinitely nested
var data = [
{id: 1, "message": "test" }
];
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can then read this using:
$data = json_decode(file_get_contents('php://input'), true);
// This becomes a simple 2D PHP array which is an exact representation as your JS object. The above example data can be output as:
foreach ($data as $message) {
echo $message['id'] . ' - ' .$message['message'];
}

Securing an AJAX service call in jQuery and PHP (with session token)

I'm currently building a framework in which for example form submit's are being implemented as jQuery ajax calls to a .php (service) file.
Part of the jQuery for reference:
var dataSerialized = $(form).serialize();
var service = $(form).attr("action");
$.ajax({
url: "services/" + service + ".php",
data: dataSerialized,
type: "POST",
cache: false,
dataType: "json",
success: function(json) {
$(json).each(function() {
loadPage(this.callback);
});
},
error: function(json, message) {
finalError(message);
}
});
And the .php does currently nothing more than:
include_once("../content/includes/connect.php");
include_once("_functions.php");
//TODO: support sending variables
$check = true;
$callback = "error";
foreach ($_POST as $key => $value) {
list($pass, $errormessage) = checkRules("register", $key, $value);
if (!$pass) {
$check = false;
$callback = "error";
break;
}
}
if ($check) {
$callback = "register_success";
}
echo json_encode(array(
"callback" => $callback
));
SQL::close();
Now I want the service call to be as secure as possible, given my situation, I see the following options:
SSL cannot be used, as it is relatively too expensive. Just working on a homebred project, nothing important.
jCryption library cannot be used, as I'm on a cheap web hosting and do not have access to the server itself.
OAuth 2.0 is a possibility, but seems quite complicated.
$_SERVER variables can be used to help protecting the service .php pages, but not reliable.
$_SESSION could be used to generate tokens.
I already implemented an easy measure: Change GET to POST. This will only deter the most easy attack, now the attacker actually needs to use some tampering tool instead of being able to do it directly through the browser.
I think I can protect every call that comes from an URL typed in the browser, however I see two serious threats:
Direct requests to the webserver: The attacker can pass any data he wants.
Using a Browser JavaScript Console to send custom jQuery requests.
I think it is best, again under these circumstances, to try to protect the service .php pages with $_SESSION tokens, but how exactly do I go about these?
They need to be set as some point in time before the service call, and then the service call could check it.
I also have access to a MySQL database and of course plain text files on the webspace.
Can anyone help me out any further?
Have a csrf token send together with the form and in your .php file you could use something like this
session_start();
if ($_SERVER['HTTP_X_CSRF_TOKEN'] !== $_SESSION['csrfToken']) {
return false;
die();
}
Send CSRF Token with all service calls
$.ajaxSetup({
headers: {
'X-Csrf-Token': "TOKEN HERE"
}
});

cross domain request data using pure javascript

I am trying to access an external url which returns json data and based on one of the value in that data I need to hide a table row. I have tried several options to do this with jsonp, jquery and ajax but nothing seem to work. YQL is working for me but I can't use outer Service as the code need to be independent. Please someone let me know how I can make this work with javascript
This is one approach I have tried
<script type='text/javascript'>
function checkBlueLight() {
$('#trBlueLight').hide();
$.getJSON('http://.../Lights/getBlueLight?callback=?', function (data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
});
}
</script>
This is another approach I have tried. same issue unauthorized - 401
$.ajax({
url: 'http://.../Lights/getBlueLight',
dataType: 'json',
success: function(data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
}
});
I have even tried to get data from url using jsp with and that also causing some permission issue
Do you control the external url? Because you can do:
On your local page:
function your_function(data) {
alert(data.message)
}
And then on http://www.include.me/remote.php (or whatever is returning JSON) you would have it return
your_function({message: "it works!"});
And then back on your local page:
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://www.include.me/remote.php");
document.getElementsByTagName("head")[0].appendChild(script);
Which will then include the script, which simply tells it to run your already defined function with the data it provides.
If you can't control the external URL, and it doesn't support CORS nor JSONP, then you best option is to write a server side proxy method for the service. So on your server, you expose a new endpoint on your own host that on the server side access the real service on your clients behalf, and returns the result to your client.
For using jsonp, the server should bind the return type with a callback function. If it not, you cannot get the data from server.
If you are using cors, server should support that. Which means server should set,
"Access-Control-Allow-Origin" header to "*"
The issue with JS or jQuery is that crossdomain data may not be possible depending on the browser or server or a combination of both that prohibits the data exchange. This is security policy on many browsers and servers.
The best and safest choice is using a combination of JS or jQuery (Ajax call) with PHP cURL where the cURL will make the call requesting the data xml/json format and then sent back to the Ajax request.
Please take a look at the following example:
In the JS/JQuery AJax script:
$.ajax({
url: 'php_script_with_cURL.php',
dataType: 'json',
data:'THE_DATA_OR_REQUEST',
type:'post',
success: function(data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
}
});
and then in the php file (must be in the same server as your JS):
(you can use url string or post to request the data)
//USE POST IF YOU NEED TO SEND VARIOUS COMMANDS TO GET THE DATA BACK
$post = $_POST;
//INIT THE CURL CALL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
//this will tell the server how to return the data format
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
//use the query string if require, if not just remove it
CURLOPT_URL => 'http://THE_URL_HERE.COM?request_value=some_value',
//use the post only if yo need to post values
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
value1 => $post['value1'],
value2 => $post['value2']
)
//alternative you can also pass the whole POST array
//CURLOPT_POSTFIELDS => $post
));
$data = curl_exec($curl);
if(!$data){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
curl_close($curl);
//echo the data that will be sent to the JS/JQuery Ajax call
echo $data;
//or if you need to do more processing with php
//$response = json_decode($data);
Hope this helps :)
Happy coding !

how do i use the success function with an $.ajax call

I don't understand how the success function works in a $.ajax call with jquery.
for instance
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
useReturnData(data /* ??? not sure how to use the data var */ );
}
};
ajax.php:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
?>
how do i use that data within the success function? No where seems to explain what the data parameter is, they just seem to use it ambiguously.
another side question, is the data: "function=1" related to the data as a parameter for the success function?
The data variable contains the output of your php file, so if in your php file you do:
echo "<p>success</p>";
data will contain <p>success</p>.
In your example you would change your php file to:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
// other stuff...
echo $string;
?>
The content of the data parameter depends on the type of the response. If the Content-Type is application/json, then it's parsed as JSON. If it's text/html or similar, the content is HTML. In your case, it looks like you're returning text. If you make your Content-Type header text/plain or similar, then data should just be a string.
To answer your second question, the data property for the Ajax request is something different; it specifies the request data that is sent. In other words, it's the query string if you have a GET request, and the post "form" variables if it's a POST request.
data is whatever is returned by the server side script, so in this case it would be
this is the data i want to return and use
Providing the if() condition is met.
Nobody really says what data contains because it can contain various different things, although it's always a string. Sometimes it's HTML, sometimes it's JSON and sometimes just a return message.
In your case, data will just be a string providing you echo the string out in your server side script.
The easiest way is to load the data into some placeholder element (div?)
E.G.
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
$('div.selector').load(data);
}
};

Categories