Running loop from javascript to save in Mysql - javascript

Hello i am currently running a javascript on my php page (below) and it comes out with each data that i need is there any way i can connect this through to mysql database? (i am new to javascript)
<script>
var allItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
for(var i = 0; i < allItems.length; i++) {
var item = allItems[i];
console.log('Current item: %o', item);
}
</script>
'itemsArray comes from a save function'
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
});
Thanks
PS I already have the connection for the database setup

Post your data with ajax/json request to a php function and do all database related work with php. Next return successful or failure status which will be catch in this called js function, and then you can display the success or failure message with javascript.
Example:
Include jQuery library:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Script for ajax request with jQuery:
var path = 'http:/your_url/your_php_script_file.php';
var data = 'json_data=' + JSON.stringify(newItem[num]);
$.ajax({
url: path,
type: "POST",
data: data,
cache: false,
success: function ($returm_msg){
alert($returm_msg);
}
});
PHP for save/update in database:
$receive_value = json_decode($_POST['json_data'], true));
You will get values like
$receive_value['methv'],$receive_value['q1'],....,$receive_value['comm'];
Now do save operation in database.
$result = mysql_query("INSERT INTO .....") or die(mysql_error());
if($result){
return "Success!"; // if not function then simply echo "Success!";
}else{
return "Failure!"; // if not function then simply echo "Failure!";
}
Helpful links:
http://www.bennadel.com/resources/presentations/jquery/demo21/index.htm
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Related

How to make the ajax 'data' that come with 2 values to get each value separately?

<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr[] = array($arrResult, // include only one value
$response_array['status'] );//success or not success value
return $return_arr;
}
?>
This $return_arr[] value return to the javascript ajax file >>
$.ajax({
url: 'PHPMethodCalls_AL.php',
type: 'post',
data: {... post many values to php function.. },
success: function(data) {
alert(data);
//data is successfully come as this format >> [[["Testing123"],"success"]]
var results = JSON.parse(data);
alert(results);
// this alert got >> Testing123,success
},
//this one is post value to function
$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.
You can seperate in php function before response to ajax like below .Then you can get easy
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr = array("data" =>$arrResult, // include only one value
"status" =>$response_array['status'] );//success or not success value
return $return_arr;
}
?>
var results = JSON.parse(data);
alert(results.data || results.status);
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].
To get your status and payload out of this structure, you can use the following snippet.
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested
var status = parsedData[0][1];
console.log(status);
var payload = parsedData[0][0][0];
console.log(payload);
Or using ES6 destructuring:
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);
I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:
{"status": "success", "payload": "Testing123"}

How to send JavaScript collection to PHP variable?

I am trying to send data from form to PHP file using JavaScript. PHP file pushes this data to database. For now, almost all works well but I have a problem with array from getElementsByClassName. After sending to database I can see only "Array" but no values of this array.
Here's a JS:
function przekaz_form($wejscie) {
var datas = document.formularz.datas.value;
var klient = document.formularz.firma.value;
var comment = document.formularz.comment.value;
var collect = document.getElementsByClassName($wejscie);
var datan = document.formularz.datan.value;
var items = new Array();
for(var i = 0; i < collect.length; i++) {
items.push(collect.item(i).value);
}
jQuery.ajax({
url: 'addtobase.php',
type: 'post',
data:{
devices: items,
datas: datas,
klient: klient,
comment: comment,
datan: datan
},
success: function(output) {
alert('Success');
}
});
}
One way to do this is:
$inputData = json_decode(file_get_contents('php://input'));
Once you have the $inputData variable you can access the data in the JSON by:
$devices = (!is_null($inputData) && property_exists($inputData, "devices")) ? strip_tags($inputData->{"devices"}) : 0;
You should also try to better format the JSON : http://json.org/example

passing javascript array to php via jquery AJAX

I am having problems passing my javascript array to a php file. i know that the JS array has the correct users input data because I have tested this by using toString() and printing the array on my web page. My plan was to use send the JS array to my php script using AJAX's but I am new to using AJAX's so there is a good chance I am doing something wrong. I have look through a good lot of different posts of people having this same problem but everything i have tried has not worked so far. All I know at this point is the JS has data in the array fine but when I try to pass it to the php file via AJAX's the php script dose not receive it. i know this because I keep getting undefined variable errors. To be fully honest I'm not to sure if the problem in how I'm trying to pass the array to the php script or if it how I'm trying to request and assign the array values to variables on the php side. At the moment my code is as follows:
My Javascript:
function createAsset(str, str, str, str, str, str, str, str, str)
{
var aID = assetID.value;
var aName = assetName.value;
var pPrice = purchasedPrice.value;
var pDate = purchasedDate.value;
var supp = supplier.value;
var cValue = currentValue.value;
var aOwner = actualOwner.value;
var wEdate = warrantyExpiryDate.value;
var dDate = destroyedDate.value;
//document.write(aID);
//var dataObject = new Array()
//dataObject[0] = aID;
//dataObject[1] = aName;
//dataObject[2] = pPrice;
//dataObject[3] = pDate;
//dataObject[4] = supp;
//dataObject[5] = cValue;
//dataObject[6] = aOwner;
//dataObject[7] = wEdate;
//dataObject[8] = dDate;
//dataObject.toString();
//document.getElementById("demo").innerHTML = dataObject;
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
$.ajax
({
type: "POST",
url: "create_asset_v1.0.php",
data: dataObject,
cache: false,
success: function()
{
alert("OK");
location.reload(true);
//window.location = 'create_asset_v1.0.php';
}
});
}
My PHP:
<?php
// Get Create form values and assign them to local variables.
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
// Connect to the SQL server.
$server='PC028\ZIRCONASSETS'; //serverName\instanceName
$connectinfo=array("Database"=>"zirconAssetsDB");
$conn=sqlsrv_connect($server,$connectinfo);
if($conn)
{
echo "Connection established.<br/><br/>";
}
else
{
echo "Connection couldn't be established.<br/><br/>";
die(print_r( sqlsrv_errors(), true));
}
// Query the database to INSERT record.
$sql = "INSERT INTO dbo.inHouseAssets
(Asset_ID, Asset_Name, Perchased_Price, Date_Perchased, Supplier, Current_Value, Actual_Owner,Worranty_Expiry_Date, Destroyed_Date)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = array($assetID, $assetName, $purchasedPrice, $purchasedDate, $supplier, $currentValue, $actualOwner, $warrantyExpiryDate, $destroyedDate);
// Do not send query database if one or more field have no value.
if($assetID && $assetName && $purchasedPrice && $purchasedDate && $supplier && $currentValue && $actualOwner && $warrantyExpiryDate && $destroyedDate != '')
{
$result = sqlsrv_query( $conn, $sql, $params);
// Check if query was executed with no errors.
if( $result === false )
{
// If errors occurred print out SQL console data.
if( ($errors = sqlsrv_errors() ) != null)
{
foreach( $errors as $error )
{
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br/>";
echo "code: ".$error[ 'code']."<br/>";
echo "message: ".$error[ 'message']."<br/>";
}
}
}
else
{
echo "Record Created!<br/>";
}
}
// Close server connection
sqlsrv_close( $conn );
if($conn)
{
echo "<br/>Connection still established.";
}
else
{
echo "<br/>Connection closed.";
}?>
Just as extra info if its not obvious from my code I am trying to send user data from a html form to a php script that process it and uses it to query a MSSQL database. This function that I am working on now is the create database entry function.
You need to match the keys you send through AJAX:
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
with the POST array keys:
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
Your code should look like this:
$assetID = $_POST['assitID'];
$assetName = $_POST['assitName'];
$purchasedPrice = $_POST['purchasedPrice'];
...
You are reading the wrong keys.
$assetID = $_POST['aID'];
Must be:
$assetID = $_POST['assitID'];
As per your sent object.

Values not being transfered from JS to php

I have a JS script of:
function addTasteingNote(userID,beerID)
{
//get values
var note = $('#note1').val();
var ajaxSettings = {
type: "POST",
url: "a.php",
data: "u="+userID+"&b="+beerID+"&n="+note,
success: function(data){
} ,
error: function(xhr, status, error) { alert("error: " + error); }
};
$.ajax(ajaxSettings);
return false;
}
and the php script to add to the db is:
<?php
error_log("starting code");
require_once('connect.inc.php');
$u = $_GET['uID'];
$b = $_GET['bID'];
$n = $_GET['n'];
//do some checks etc
$db = new myConnectDB();
error_log("Successfully created DB");
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ($u, '$b', '$n')";
error_log($query3);
$result = $db->query($query3);
?>
The problem is that the error log shows nothing being put into the query:
[01-Nov-2013 23:40:29] Successfully created DB
[01-Nov-2013 23:40:29] INSERT INTO x (userID,beerID,note) VALUES (, '', '')
I have put alerts in the success of the ajax call, so I know that values are being passed through...
You need to give data like
var ajaxSettings = {
type: "POST",
url: "a.php",
data: {u:userID,b:beerID,n:note},
success: function(data){
}
data wont be and Query string,And since you are posting the values through ajax you need to get them via POST only like
$u = $_POST['u'];
$b = $_POST['b'];
$n = $_POST['n'];
And your query should be like
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ('".$u."', '".$b."', '".$n."')";
And Better to use escape strings with your POST variables to prevent from SQL injection.
You are using post method so, you need to get data using $_POST or $_REQUEST instead of $_GET
$u = $_REQUEST['u'];
$b = $_REQUEST['b'];
$n = $_REQUEST['n'];

Javascript/Ajax success request delete record from websql

I use the following code to query my websql database to see if there are any records.
If records are found then I use an ajax request to submit these to an asp page which in turn pushes the form information on to a sql server.
So far everything is good however I now want to delete each of the records from the WebSql database only when the ajax request returns a success.
I can't for the life of me get my head around javascript functions and scope correctly when they are nested this big (i've only been writing js/jquery now for a couple of weeks).
I know I need to capture the ID which I have set as a variable vID an then execute another sql statement to delete the record, nested within the success criteria of my ajax call. I cant get vID to reference correctly and then I do not know how to set up the call to execute the sql again based on this.
function Web_SQL_Storage_Open_And_Check() {
if (window.openDatabase) {
var db = openDatabase("ER_Nonconformance", "1.0", "Non-conformance Report DB", 4 * 1024 * 1024); //creates our database if it does not exist at 4mb size
var db2 = db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS tbllog (ID INTEGER PRIMARY KEY ASC AUTOINCREMENT, DteOccur datetime, Pdetected nvarchar(50), DeptRaisedBy int, DeptResp int, NCDescrip nvarchar(255), NCCause nvarchar(255), NCImmediateAct nvarchar(255), NCLocation nvarchar(100), PNumOrRef nvarchar(30), EventCat int, ReportedEmailAddy nvarchar(100), Location_Category int)");
tx.executeSql("SELECT * FROM tbllog", [], function(tx, result) {
if (result.rows.length > 0) {
alert("we need to submit")
for (var i = 0; i < result.rows.length; i++) {
//Submit values to the asp page using the below loop
var vID = (result.rows.item(i)['ID'])
var vPdetected = result.rows.item(i)['Pdetected']
var vDteOccur = result.rows.item(i)['DteOccur']
var vDeptRaisedBy = result.rows.item(i)['DeptRaisedBy']
var vDeptResp = result.rows.item(i)['DeptResp']
var vNCDescrip = result.rows.item(i)['NCDescrip']
var vNCCause = result.rows.item(i)['NCCause']
var vNCImmediateAct = result.rows.item(i)['NCImmediateAct']
var vNCLocation = result.rows.item(i)['NCLocation']
var vPNumOrRef = result.rows.item(i)['PNumOrRef']
var vEventCat = result.rows.item(i)['EventCat']
var vReportedEmailAddy = result.rows.item(i)['ReportedEmailAddy']
var vLocation_Category = result.rows.item(i)['Location_Category']
var request = $.ajax({
url: "untitled.asp",
type: "post",
data: {
DteOccur: vDteOccur,
Pdetected: vPdetected,
DeptRaisedBy: vDeptRaisedBy,
DeptResp: vDeptResp,
NCDescrip: vNCDescrip,
NCCause: vNCCause,
NCImmediateAct: vNCImmediateAct,
NCLocation: vNCLocation,
PNumOrRef: vPNumOrRef,
EventCat: vEventCat,
ReportedEmailAddy: vReportedEmailAddy,
Location_Category: vLocation_Category
},
dataType: "html"
}
);
request.done(function() { alert("done"); })
request.fail(function() { alert("error"); })
request.always(function() { alert("complete"); });
}
}
else {
//no records found so do nothing
alert("do nothing")
} //end of if statement
}, function(tx, error) {
alert("error retrieving")
})
//tx.executeSql();
});
}
}
Define var vID outside function, not inside and that gives you the correct reference.

Categories