How to pass long data to mySql database at freemysqlhosting.net - javascript

I am using freemysqlhosting.net to host my database and I am doing actions by using their library :
var MySql = {
_internalCallback : function() { console.log("Callback not set")},
Execute: function ( Sql, Callback)
{
MySql._internalCallback = Callback;
Host = "sql9.freemysqlhosting.net";
Username = "myUserName";
Password = "MyPassword";
Database = "MyDatabase";
var strSrc = "http://mysqljs.com/sql.aspx?";
strSrc += "Host=" + Host;
strSrc += "&Username=" + Username;
strSrc += "&Password=" + Password;
strSrc += "&Database=" + Database;
strSrc += "&sql=" + Sql;
strSrc += "&Callback=MySql._internalCallback";
alert(strSrc);
console.log('rabee: '+ strSrc);
var sqlScript = document.createElement('script');
sqlScript.setAttribute('src', strSrc);
document.head.appendChild(sqlScript);
}
};
Then if I want to insert data into table inside this database, I do it simply by doing this:
var command =
"INSERT INTO myTable(id,name,email,data) VALUES ('2','rabee','test#test.com','anydata')";
MySql.Execute(command,function(data){
showAllRaws();
alert(JSON.stringify(data,null,2));
});
When I insert short data inside the data column I got a successful callback, but when I insert long data nothing happens and no callback.
My questions are :
1- Is there any limitation for long URL request or am I doing something wrong?
2- How to replace their tiny library with AJAX request?

Please check your datatype in the database and whether you are using use "text" datatype it will accept all data.

Related

How to get POST raw data on PHP using $_SERVER

I have a dynamic page using on-page-filter i change the data on the page using AJAX response, my question is how can i get from POST raw data when on the URL is not written..
my link on the page is similar like this "example.com/default/list_data"
and on my AJAX I created the query string like this
function create_qs() {
var qs = '?1=1';
$('.fltlist').each(function (index, item) {
var val = ($(item).hasClass('active')) ? 'Y' : 'N';
qs += '&' + $(item).attr('f') + '=' + val;
});
qs += '&from=' + $('#startdate').val();
qs += '&to=' + $('#enddate').val();
qs += '&sort=' + $('#sort_sppt_ticket').val();
qs += '&search=' + $('#search').val();
qs += '&developer=' + $('#fltlistdev').val();
return qs;
}
but on the URL bar it didn't show anything (because the post) I'm using AJAX POST..
i need the raw data and store on the PHP array (maybe in global variable) to pass the raw data to another page..
any help?
Try using this
$rawData = file_get_contents("php://input");

How to query DBPedia from JavaScript by resource URI?

I try to make this query from JavaScript
var subject = document.getElementById("inputUri").value;
var property = "?p";
var object = "?o";
var query = "\
PREFIX dbpedia2: <http://dbpedia.org/property/>\
PREFIX foaf: <http://xmlns.com/foaf/0.1/>\
PREFIX : <http://dbpedia.org/resource/>\
SELECT * \
WHERE {\
"+ subject + property + object +".\
}LIMIT 10";
And I receive the variable ?s from an input form, but when I write another variable name, it doesn't work.
The code for the result is the following:
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function( _data ) {
var results = _data.results.bindings;
var subject = document.getElementById("inputUri").value;
for ( var i in results ) {
var subjectResult = results[i].s.value;
var objectResult = results[i].o.value;
var propertyResult = results[i].p.value;
}
}
});
In
var subjectResult = results[i].s.value;
Is the error, but I don't know to receive the value from my input text to the subjectResult assignation.
I defined the variable which receives any variable name from the input text, by this way:
var str = subject;
var res = str.replace("?", "");
Then in the for loop:
var subjectResult = results[i][res].value;
There is no variable called ?s in your query, so it makes sense you can't retrieve its value.
Depending on the structure of your code, you should be able to use the subject variable directly:
var subjectResult = subject;
var objectResult = results[i].o.value;
var propertyResult = results[i].p.value;
Another option is to create the variable in your query, using BIND:
"SELECT *\
WHERE {\
BIND(" + subject + " AS ?s)\
?s ?p ?o .\
} LIMIT 10"
Not sure what SPARQL server are you using, but when I tried this on Virtuoso, it failed with a confusing error, even though I believe it's valid SPARQL.
Also note that building queries like this from user input leaves you open to injection attacks.

What is the right way to send JSON to clients?

I want to develop an app for Pebble. This app is going to tell you how long it takes from one place you set in options to another one taking in account traffic jams and stuff.
To achieve this I need to make a page that will return JSON. Pebble retrieves information using code like that:
var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;
ajax(
{
url: URL,
type: 'json'
},
function(data) {
// Success!
console.log('Successfully fetched weather data!');
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
I created a small page with a js script that gets needed information from Yandex API:
var route;
ymaps.ready(init);
var myMap;
function init(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var time = 0;
var home = getParameterByName("h");
var work = getParameterByName("w");
ymaps.route([home, work],{avoidTrafficJams: true}).then(
function (router) {
route=router;
time = ((route.getTime())/60).toFixed(2);
var info = new Object;
info["home"] = home;
info["work"] = work;
info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
JSON.stringify(info);
},
function (error) {
alert('Возникла ошибка: ' + error.message);
}
);
}
As you can see I can get a JSON string in the end. But how do I send it to clients when a request with right parameters is made?
I ended up using phantomjs and executing this js script on my php page.

How to send json and parse it on next html page through url in jquery?

I want to send json data through url to next html page. I checked it by emulator as I am working for mobile app, the url could not redirect to next page it is crashing at the moment what is the reason behind this. How can I parse it on next page .I am new to the jquery any idea? my json data contains result of two different sql queries in an array
$.ajax({
type : "POST",
datatype : "json",
url : "http://Localhost/phpBB3/check_pass.php?username="+ username + "&password="+ password+"&f=68",
success: function(data){
alert(data);
window.location.href="source/testmenu.html?varid=" + data +"&username=" + username +"&password=" + password;
}
});
This is the code on next page
$(document).ready(function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var arr = SearchString.split('&');
console.log(arr);
//Set session variables
var username = arr[1].split('=')[1];
var password = arr[2].split('=')[1];
document.getElementById('username').value = username;
document.getElementById('password').value = password;
)};
in your case in first page urlencode json
window.location.href="source/testmenu.html?varid=" + encodeURIComponent(data) +"&username=" + username +"&password=" + password;
and in next page
var data= arr[0].split('=')[1];
var recieved_json = $.parseJSON(data);
Then try this one:
var data = {
username: username,
password: password
};
$.ajax({
type: "POST",
url: "http://Localhost/phpBB3/check_pass.php",
params: $.param(data),
success: function(a) {
window.location.href = "source/testmenu.html?"
+ $.param(a) + "&" + $.param(data)
}
});
And this would be your code for the next page (the iterator is from Satpal's answer):
$(document).ready(function() {
var params = window.location.search;
var getURLParams = function(params) {
var hash;
var json = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
json[hash[0]] = hash[1];
}
return json;
}
params = getURLParams(params);
var username = params.username;
var password = params.password;
$('#username').val(username);
$('#password').val(password);
});
Though I agree with #Jai that sending username and password in url is not recommended.
Once you get the URL to load you'll need to run your data through some encoding and decoding. You might have the wrong path. If you want "http://Localhost/source/testmenu.html" make sure the first character is a "/".
Make sure your data object is encoded correctly.
// Encode data for querystring value.
var data = {
foo: "bar"
};
var data_str = JSON.stringify(data);
data_str = encodeURIComponent(data_str);
Decode and test your URL.
// Get data from querystring value.
// Get the query as an object with decoded values.
// Note that JSON values still need parsing.
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.data);
} catch (err) {
alert(err + "\nJSON=" + q.data);
}
Parameter should be html encode while navigating or requesting to the URL and decode at the receiving end. It may suspect potentially dangerous content which may leads to crash.

Google Apps Script for Form, Generate Unique ID Number

I created a simple Google form with the fields:
Name, E-mail, Salary and Request.
When the user completes the form, I want to send him/her an e-mail with the info. However, I want to use the "Request" field to plug in a unique number that the user can refer to if they need further correspondence. If the user enters anything in the 'Request' field, I want to discard it and use the number that I generate (both in the response and in the spreadsheet).
I've been able to piece together the script using other info I've found. It seems to work for everything except the e-mail response going back to the user.- It does not contain the number that I want to use in the 'Request' field, but instead sends back any input that the user puts in the 'Request' field. The spreadsheet looks ok (it has my number in the 'Request' field.)
Here's my script:
function sendFormByEmail(e) {
var capsht = SpreadsheetApp.getActiveSheet();
var caprow = SpreadsheetApp.getActiveSheet().getLastRow();
capsht.getRange(caprow,5).setValue("Cap-"+caprow);
var admin = "admin#xxx.com";
try {
var recipient = e.namedValues["Email"];
var subject = "Capacity Request Form Received";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for (var i in headers)
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
MailApp.sendEmail(recipient, subject, message);
}
catch (error) {
MailApp.sendEmail(admin, "Error with form submission response email", error.message);
}
}
try it like this :
(added comment in code and deleted repetitions)
function sendFormByEmail(e)
{
var capsht = SpreadsheetApp.getActiveSheet();
var caprow = capsht.getLastRow();
var codenumber = "Cap-"+caprow
capsht.getRange(caprow,5).setValue(codenumber);
var admin = "admin#xxx.com";
try {
var recipient = e.namedValues["Email"];
var subject = "Capacity Request Form Received";
var headers = capsht.getRange(1,1,1,capsht.getLastColumn()).getValues()[0];
var message = "";
for(var i in headers)
if(i!=4){
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
}else{ // if i==4 (column nr5)then use your code number
message += headers[i] + ' = '+ codenumber + "\n\n";
}
MailApp.sendEmail(recipient, subject, message);
}
catch (error)
{
MailApp.sendEmail(admin, "Error with form submission response email", error.message);
}
}

Categories