Ajax - Inserting values from textarea into database - mysql

Hello all on my quest to learn more about ajax I tried making a textarea, in this a text is submitted and then sended to the database, I also made a button to display everything from the database and this works. However when submitted clicking the display all button it just gives this value [object HTMLTextAreaElement] Here is my code:
Select Code/Display
ToDo: <textarea width='200px' height='300px' id='todo'></textarea>
<p id='dbinfo'>Info goes here</p>
<button id='btn'> Send </button>
<button id='request'> Request </button>
<script>
document.getElementById('btn').onclick = function()
{
var dbinfo = document.getElementById('todo').value;
alert(todo); //Here it gives a object htmlcollection ?
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
alert(xmlhttp.readyState + " | " + xmlhttp.status);
var text = xmlhttp.responseText;
alert(text);
document.getElementById('dbinfo').innerHTML = text;
}
xmlhttp.open("POST", "linktodata", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("todo=" +todo);
}
document.getElementById("request").onclick = function()
{
alert("event works");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var result = xmlhttp.responseText;
alert(result);
document.getElementById("dbinfo").innerHTML = result;
}
}
xmlhttp.open("POST", "linktorequest", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
Data Code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "blok-1-am1a";
try
{
if (isset($_POST['todo']))
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("INSERT INTO `database` (`id`, `item`) VALUES (NULL, :item)");
$statement->bindParam(':item', $_POST['todo']);
$statement->execute();
}
}
catch(PDOException $e)
{
echo "Error occured : ".$e->getMessage();
}
echo "Success";
?>
Request code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "blok-1-am1a";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT * FROM `database` ");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['item']."<br>";
}
}
catch(PDOException $e)
{
echo "Error occured: ".$e->getMessage();
}
echo $data;
?>
So yeah whatever I do the request code works but when submitting I always get [object HTMLTextAreaElement]

Silly me, this is a very simple fix, I made the mistake to use the same var as my <p> tag so the fix is litteraly changing that into todo and everything works.
ToDo: <textarea width='200px' height='300px' id='todo'></textarea>
<p id='dbinfo'>Info goes here</p>
<button id='btn'> Send </button>
<button id='request'> Request </button>
<script>
document.getElementById('btn').onclick = function()
{
var todo = document.getElementById('todo').value; //This needed to be changed into todo
}

Related

Can not save data but the message has been save

I have created Cake PHP 3, I want to add data, but when I clik submit button, the data is didn't save but the message show data has been save. I add into two different tables. When I try to add data in one table is fine.
This is my controller
StoreController.php
public function add()
{
$this->loadComponent('General');
$setStatus = 1;
$store = $this->Stores->newEntity();
if ($this->request->is('post')) {
// dd( $this->request->getData());exit;
$connection = ConnectionManager::get('ora');
$connection->begin();
$store = $this->Stores->patchEntity($store, $this->request->getData());;
$merchantTable = TableRegistry::get('MasterFile.Merchants');
$merchant = $merchantTable->find()->where(['MERCHANT_CODE'=>$store->MERCHANT_CODE])->first();
$store->MERCHANT_ID = $merchant->MERCHANT_ID;
$store->CREATED_DATE = date("Y-m-d h:i:s");
$store->LAST_UPDATED_DATE = date("Y-m-d h:i:s");
$store->LAST_APPROVED_DATE = date("Y-m-d h:i:s");
$store->LAST_VERSION_DATE = date("Y-m-d h:i:s");
// $store->store_address->LINE1 = $store->LINE1;
// Start - Controller Code to handle file uploading
if(!empty($this->request->data['STORE_LOGO']['name']))
{
$file = $this->request->data['STORE_LOGO']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
$fileName = $this->request->data['STORE_LOGO']['name'];
$uploadPath = WWW_ROOT.'img/store_logo/';
$uploadFile = $uploadPath.$fileName;
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
if(move_uploaded_file($this->request->data['STORE_LOGO']['tmp_name'],$uploadFile))
{
$store['STORE_LOGO'] = $uploadFile;
}
}
}
if(!empty($this->request->data['BACKGROUND_PICTURE']['name']))
{
$fileName = $this->request->data['BACKGROUND_PICTURE']['name'];
$uploadPath = WWW_ROOT.'img/background_picture/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['BACKGROUND_PICTURE']['tmp_name'],$uploadFile))
{
$store['BACKGROUND_PICTURE'] = $uploadFile;
}
}
// now do the save
if ($this->Stores->save($store)) {
$setStatus = 1;
$message = 'The store has been saved.';
if($setStatus == 1){
$this->loadComponent('General');
$this->loadModel('MasterFile.Addresss');
$setStatus = 1;
$address = $this->Addresss->newEntity();
//dd($this->request->data);
$this->request->data['Address']['LINE1'] = $this->request->data['LINE1'];
$this->request->data['Address']['LINE2'] = $this->request->data['LINE2'];
$this->request->data['Address']['LINE3'] = $this->request->data['LINE3'];
//dd($this->request->data['Address']);
$connection = ConnectionManager::get('ora');
$connection->begin();
$address = $this->Addresss->patchEntity($address, $this->request->data['Address']);
// dd($address);
// now do the save
if ($this->Addresss->save($address)) {
$setStatus = 1;
$message = 'The store has been saved.';
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
}
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
if($setStatus){
$connection->commit();
return $this->redirect(['action' => 'index']);
}else {
$connection->rollback();
}
}
$this->set(compact('store'));
$this->set('_serialize', ['store']);
}
What should i do?
Thank you for your help!
Try debugging the entity:
if ($this->Stores->save($store)) {
debug($store);
...

PHP MySQL Data To AngularJS

I am using this code to pull data from a MySQL.
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var icon = data[1];
var english = data[2];
var british = data[3];
$('#output').html("<b>id: </b>"+id+"<b> icon: </b>"+icon+"<b> english: </b>"+english+"<b> british: </b>"+british); //Set output element html
}
And it outputs this correctly but my questions is how would put this data into the below.
$scope.items = [
{
english: '<First Row english>',
british: '<First Row british>',
image: '<First Row icon>'
},
{
english: '<Second Row english>',
british: '<Second Row british>',
image: '<Second Row icon>'
}
//So on and so forth for all the records in the DB.
]
This is from api.php not sure if this needs to be returned a certain way?
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo $json_response = json_encode($arr);
?>
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
?>
JS
$http.get('api.php').success(function(data) {
$scope.items = data;
});

Ajax GET content from php page

Hi I have a table which I am trying to update with a call to a MySQL database in a separate php page. This separate page loops through a result set and builds the table through a series of echos. In the main page I am trying to insert that echoed content into a div.
This is all kicked off by the user selecting an option from a drop down box.
This is the separate php page. (It works fine when i manually type in the GET parameters, it is the link between the two pages which doesn't seem to work)
tableGetter.php
<?PHP
$user_name = "rocketeermus_pr";
$password = "zuluhead2";
$database = "rocketeermus_pr";
$server = "pdb1.awardspace.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
echo "Bonjour";
if (isset($_GET['composer'])){
echo "Helloooo";
if ($db_found) {
echo "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$SQL = "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
echo "<table class=\"sortable\" id=\"moder\" width=\"800\">";
echo "<th>TITLE</th><th>COMPOSER</th><th>VOICING</th><th>PRICE</th><th></th></tr>";
while ( $db_field = mysql_fetch_assoc($result) ) {
echo "Hi.";
echo "<tr><td>{$db_field['Title']}</td><td>{$db_field['Composer']}</td><td>{$db_field['Voicing']}</td><td>";
echo money_format("%n", $db_field['Price']);
echo "</td><td> <div class=\"product\"> <input value=\"{$db_field['Title']}\" class=\"product-title\" type=\"hidden\"> <input value=\"0.5\" class=\"product-weight\" type=\"hidden\"> <input value=\"{$db_field['NoVox']}\" class=\"googlecart-quantity\" type=\"hidden\"> <input value=\"{$db_field['Price']}\" class=\"product-price\" type=\"hidden\"> <div title=\"Add to cart\" role=\"button\" tabindex=\"0\" class=\"googlecart-add-button\"> </div> </div> </td></tr>";
}
echo "</table>";
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
?>
And here is the important stuff from the main page:
Javascript:
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
var queryString1 = "";
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
// only if http status is "OK"
if (req.status == 200)
{
var new1 = document.getElementById('composer').value;
queryString1 = "?composer=" + encodeURIComponent(new1);
console.log (queryString1);
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}
function getXMLHTTP() {
var xmlhttp;
if(window.XMLHttpRequest){ //For Firefox, Mozilla, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){ //For ie
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
html:
<div id="menus">
<table>
<tr>
<td><form action=""">
<select name="composer" id ="composer" onchange="getdata();">
<?php
$user_name = "***";
$password = "****";
$database = "****";
$server = "****.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT DISTINCT Composer FROM catalogue ORDER BY Composer";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
while ( $db_field = mysql_fetch_assoc($result) ) {
?>
<option id="composer" onchange="getdata();" value="<?php echo $db_field['Composer'];?>">
<?php
echo $db_field['Composer'];
?>
</option>
<?php
}
}
?>
</select>
</form></td>
</tr>
</table>
</div>
<div id="table">
<?php include("tableGetter.php"); ?>
</div>
The html on the main page works fine, the drop down menu fills up nicely with all the distinct composer names in the database. When an option in the menu is selected the only thing echoed in the "table" div is "Bonjour". It's not getting further than if (isset($_GET['composer'])) in the tableGetter.php page. I'm printing out the queryString1 variable (The get parameters) which is requested in the getData() function and it reports: ?composer=Animuccia%2C%20Paulo which works perfectly when loading the page manually. It just won't work dynamically!
Anybody know what's going on here?
You aren't setting queryString1 before sending the AJAX request. Try this rewrite of getdata().
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var new1 = document.getElementById('composer').value;
var queryString1 = "?composer=" + encodeURIComponent(new1);
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}

phonegap/msql(i) can't establish connection to database

i'm currently developing an web app for iOS but the app can't get the connection right.
when i'm trying to log in, i get the following iOS popup: index.html Error.
while the PHP files are online,
here some of my code:
connection.php
<?php //Make connection with database
// Verbinden met MySQL Database
$host = "localhost"; // Welke server : localhost
$username = "*******"; // Gebruikersnaam
$password = "****"; // Wachtwoord
$dbnaam = "*****"; // Naam van de database
$db_error1 = "<p>FOUT: verbinden met databaseserver is mislukt</p>"; // Foutmelding 1
$db_error2 = "<p>FOUT: selecteren van database is mislukt</p>"; // Foutmelding 2
$db_error3 = "<p>FOUT: sluiten van database is mislukt</p>"; // Foutmelding 3
// Verbinden met Databaseserver
$con=mysqli_connect($host, $username, $password, $dbnaam);// or die($db_error1);
// verbinden met de database
//mysql_select_db($dbnaam, $db) or die($db_error2);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
demo.js
// define the URL of the server component
//var url ="http://www.jorisgraaumans.nl/dutchmobile/";
//var url = "http://localhost:8888/Mobile/Festival/";
var url = "http://www.rikvandoorn.com/mobile/";
// afvangen van het standaard submit event
// zie ook: http://api.jquery.com/submit/
$('#login').on('pageinit', function(event) {
$('#loginForm').submit(function() {
$.ajax({
type: "POST",
url: "processLogin.php",
cache: "false",
dataType: "json",
data: {
email : $('#email').val(),
wachtwoord : $('#wachtwoord').val(),
},
success: function(phpData){
$("#return").data("login", phpData.login);
console.log("login is: "+ phpData.login);
if(phpData['error'] == true){
$.mobile.changePage("#return", {
transition : "fade"
})
} else {
$.mobile.changePage("#home", {
transition : "fade"
})
}
},
error: function(){
alert('Error');
}
});
return false; // return false to prevent the default submit of the form to the server.
});
// end: pageinit loginForm
});
$('#return').on('pageshow', function(event) {
$("#error_message_log").empty();
$("#error_message_log").prepend('<p>' + $(this).data('login') + '</p>');
});
processLogin.php
<?php //process login form
include 'http://www.rikvandoorn.nl/mobile/connect.php'; //connection to database
if(empty($_POST['email']) || empty($_POST['wachtwoord'])){
$return['error'] = true; //return error
$return['login'] = 'Niet alle velden zijn ingevuld';
} else {
$email = $_POST['email'];
$wachtwoord = $_POST['wachtwoord'];
//Check if user exists
$sql = "SELECT * FROM gebruiker WHERE email = '$email'";
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows == 0){
$return['error'] = true;
$return['login'] = 'Gebruiker bestaat niet';
} else {
//Check if password is correct for user
$sql_2 = "SELECT * FROM gebruiker WHERE email = '$email' && wachtwoord = '$wachtwoord'";
$query_2 = mysql_query($sql_2);
$num_rows_2 = mysql_num_rows($query_2);
if($num_rows_2 == 0){
$return['error'] = true;
$return['login'] = 'Wachtwoord onjuist';
} else {
$return['error'] = false;
$return['login']['email'] = $email;
$return['login']['wachtwoord'] = $wachtwoord;
}
}
}
echo json_encode($return);
Unless you've riddled the code with typos, you're mixing two entirely seperate mysql libraries:
$con=mysqli_connect($host, $username, $password, $dbnaam);// or die($db_error1);
^---note the presence of an 'i'
and in the other scripts:
$result = mysql_query($sql) or die(mysql_error());
^---note the LACK of an 'i'
mysql and mysqli are NOT interchangeable, and connections established in one are utterly useless for the other.
The mysql (WITHOUT an i) library is obsolete and deprecated. Stick with mysqli (WITH an i) only.

Show Chrome extension version on options page?

I've got my manifest file with my version number and an options page. Is there a way to display the installed version and latest available version on the options page without needing to do it manually?
You can get the current version of your extension using chrome.runtime.getManifest().version.
In order to get the "latest version" of your extension, you need to download updates.xml, and extract the version number:
var extensionID = chrome.i18n.getMessage('##extension_id');
var currentVersion = chrome.runtime.getManifest().version;
var url = 'https://clients2.google.com/service/update2/crx?x=id%3D' + extensionID + '%26v%3D' + currentVersion;
var x = new XMLHttpRequest();
x.open('GET', url);
x.onload = function() {
var doc = new DOMParser().parseFromString(x.responseText, 'text/xml');
// Get and show version info. Exercise for the reader.
};
x.send();
If you want to customize your request with PHP, avoiding to update the extension every time Google changes the API, I suggest the following
update_info.php (from your site):
<?php
$last_ver;
$googleupdate = 'http://clients2.google.com/service/update2/crx?response=updatecheck&x=id%3D__id__%26uc';
$ver = $_POST['ver'];
$id = $_POST['id'];
//filter/control for post request very fast for this example
if(isset($id) && isset($ver)){
if(strlen($id)>0){
$urlupdate = str_replace('__id__', $id, $googleupdate);
$last_ver = _GetLastVersion($urlupdate);
if($last_ver>0 && $last_ver>$ver){
echo 'New version available, v'.$last_ver;
}else{
echo 'Your version is update';
}
}else{
echo 'Insert id for response';
}
}else{
echo 'Insert data for response';
}
//if your server do not connect with file_get_contents() use this function
function getContent ($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
$info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($output === false || $info != 200) {
$output = null;
}
return $output;
}
//this function return 0 if error or not content load
function _GetLastVersion($url){
try {
$last=0;
//if you have proble you can use getContent($url)
$xmlcontent = file_get_contents($url);
if($xmlcontent){
$doc = new DOMDocument();
$doc->loadXML($xmlcontent);
$items = $doc->getElementsByTagName('updatecheck');
foreach ($items as $item) {
if($item->getAttribute('version')>0){
return $item->getAttribute('version');
}
}
return $last;
}else{
return 0;
}
} catch (Exception $e) {
return 0;
}
}
?>
in your extension send request to your webpage, now you are in control of your script, you can decide which answer back every time