JSON array to and from MySql. Saving and Looping - javascript

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}

This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

Related

Resubmitting or Creating a Nested jQuery.post

I have a variable in Javascript which I am trying to pass to PHP. I have this working using jQuery.post. The issue is, the variable (linkforsharedURL) is declared within a multidimensional array and the default value is immediately sent when the jQuery.post command is executed. However the value of this variable is further modified within the function, but the modified value is not sent to PHP - the original value is sent.
A solution forward I was considering was to execute another jQuery.post just after the If statement again containing the updated 'data' array - but I don't think this would be best practice.
I did consider bringing the If statement out of the jQuery.post, however the If statement is dependent on the jQuery's response variable.
My apologies for the way I have explained the above - just trying to get my head round this particular issue.
// build data
var dataURL = dataURLs[0],
data = {
email: email,
name: name
linkforsharedURL: linkforsharedURL
};
// send data
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
if (response.share_id !== undefined) {
var pattern = new RegExp('(share_id=).*?(&|$)'), shareUrl = window.location.href;
if (shareUrl.search(pattern) >= 0) {
shareUrl = shareUrl.replace(pattern, '$1' + response.share_id + '$2');
linkforsharedURL = shareUrl;
}
You have to create a function to call again within jQuery.post response. try the below code.
// build data
var dataURL = dataURLs[0],
data = {
email: email,
name: name,
linkforsharedURL: linkforsharedURL
};
SendDataToPhp( data );
function SendDataToPhp(){
// send data
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
if (response.share_id !== undefined) {
var pattern = new RegExp('(share_id=).*?(&|$)'), shareUrl = window.location.href;
if (shareUrl.search(pattern) >= 0) {
shareUrl = shareUrl.replace(pattern, '$1' + response.share_id + '$2');
linkforsharedURL = shareUrl;
data.linkforsharedURL = 'updated value to send';
SendDataToPhp( data );
}
}
});
}

Loop in IndexedDB Transactions

I am using the product design tool "Lumise" which saves the guest designs and uploads in IndexedDB. I want to save the data which is saved in these object stores in MySQL table using the insert query. I have created a selectindexeddb.js file and indexeddbtomysql.php file and already there is a file for the tool which created the IndexedDB and updating it called "app-uncompressed.js".
my question is: I want to make the loop for each transaction happen to the design from creating, update or delete how can I do it from separate js file.
hint: I have tried to write this for loop in lumise js file but it shows bunch of errors also because this file is extremely huge.
any help ?
app-uncompressed.js :)
https://pastebin.com/cm6aNZ2A
Another Hint:)
in this file, you can focus in 12177 lines which starts creating IndexedDB
selectindexeddb.js
var db;
var request = indexedDB.open("lumise");
var transaction = db.transaction(["designs"]);
var objectStore = transaction.objectStore("designs");
var request = objectStore.get("K730MRT0"); // this i want it to have it from app_uncompressed.js as a variable.
// i want to make the loop here ?!
request.onsuccess = function(event) {
// Do something with the request.result!
var designid = request.result.id;
var designname = request.result.name;
var designscreenshot = request.result.screenshot;
console.log("rsults is " + designid);
$.ajax({
url: 'indexeddbtomysql.php',
method: 'POST',
data: {design_id:designid ,design_name:designname,design_screenshot:designscreenshot },
success: function(data) {
alert("saved y marweta ;)")
}
});
};
indexeddbtomysql.php
<?php
session_start();
include '../config.php';
$design_id = $_POST['design_id'];
$design_name = $_POST['design_name'];
$design_screenshot = $_POST['design_screenshot'];
$query = 'INSERT INTO `user_designs`( `key`, `name`, `screnshot`) VALUES ($design_id
,$design_name , $design_screenshot);';
?>
updated I have tried to put the for loop in the app_uncompersed.js but it didn`t work
save : function(ob, storeName, callback) {
if (this.db == null)
return callback(null);
var i ;
for (i = 0; i < count(rows); i++) {
var trans = this.db.transaction(ob.length === 2 ?
[storeName, 'dumb'] : [storeName], "readwrite");
var store = trans.objectStore(storeName);
if (ob.id === null || ob.id === undefined)
ob.id = parseInt(newDate().getTime()/1000)
.toString(36)+':'+Math.random().toString(36).substr(
2);
var obj = $.extend({
created: new Date().getTime()
}, (ob[0] !== undefined ? ob[0] : ob));
var process = store.put(obj, obj.id);
if (typeof callback == 'function')
process.onsuccess = callback;
console.log("ABC");
if (ob[1] !== undefined) {
var obj_dumb = $.extend({
id: obj.id,
created: obj.created
}, ob[1]);
trans.objectStore('dumb').put(obj_dumb, obj.id);
}
var designid = obj.id; //this var i want to save
}
},
I am currently learning IndexedDB and find this link to be very useful. There is a tutorial in it which covers what you're trying to achieve.
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

How to create JSON dynamically in proper json format and keep appending new data to the same object?

I have a form in which user enters email and password and on submitting, JSON is being created dynamically. When I login again with another user details, the same JSON gets updated, but with new object and thus my JSON gets corrupted.
Below is the JS function Used to create JSON -
`var g_objJSON = {};
/** setJSON - Create JSON object
* Returns - Nothing
**/
function setJSON() {
var v_aJSON = [];
var v_hObject = {};
var v_hTempHash = {};
var v_sKey = document.getElementById("user_email").value;
// v_sKey = $_SESSION['user_email'];
var v_sValue = document.getElementById("user_password").value;
try {
v_hObject[v_sKey] = v_sValue;
document.getElementById("user_email").value = "";
document.getElementById("user_password").value = "";
if (g_objJSON == undefined) {
v_aJSON.push(v_hObject);
} else {
v_hTempHash = mergeHashOb(g_objJSON[0], v_hObject);
v_aJSON.push(v_hTempHash);
}
g_objJSON = v_aJSON;
alert("Account successfully created!");
for (var item in g_objJSON[0]) {
console.log("Email: " + item + "\nPassword: " + g_objJSON[0][item]);
$.ajax({
url: "/open day planner/json.php",
type: 'POST',
data: {json: JSON.stringify(g_objJSON)},
dataType: 'json'
});
}
} catch (x) {
alert(x.message);
}
}
/** mergeHashOb - Merge a new JSON object with the global JSON object
* #prm_hObj - Existing Hash object
* #prm_hObj2 - New Hash object
* Returns - A new Hash object contains the merged Hash objects
**/
function mergeHashOb(prm_hObj, prm_hObj2) {
var v_hObj = {};
for (var item in prm_hObj2) {
v_hObj[item] = prm_hObj2[item];
}
return v_hObj;
}`
json.php:
`
<?php
$json = $_POST['json'];
/* sanity check */
if (json_decode($json) != null)
{
$file = fopen('new_account_data.json','a');
fwrite($file, $json);
fclose($file);
}
else
{
// handle the error
}
?>
`
JSON output:
[{"c.harlie#gmail.com":"zxcvb"}][{"vrishgarg#xxxx.com":"vrish"}]
Expected output:
[{"c.harlie#gmail.com":"zxcvb"},
{"vrishgarg#xxxx.com":"vrish"}]
You should take the json out of the file, and actually append to that json, not to the file's contents. I believe something like this will get you started to what you want to happen.
<?php
// let's parse this right away
$json = json_decode($_POST['json']);
/* sanity check */
if ($json != null)
{
// parse the file contents to json
$fileContents = file_get_contents('new_account_data.json');
$parsedJson = json_decode($fileContents);
if ($parsedJson === null) {
// it's either the file contains bad json or it is empty (tested with 7.1)
$parsedJson = array();
}
// append your new data to the parsed json
// I'm assuming the $_POST['json'] returns a stringified array, I'll take the first element and append it.
$parsedJson[] = $json[0];
// now write to the file
$file = fopen('new_account_data.json','w'); // note that we're writing, not appending.
// write to file the json_encoded $parsedJson
fwrite($file, json_encode($parsedJson));
fclose($file);
}
else
{
// handle the error
}
?>

creating query from data recived from javascript via ajax

I have the following javascript:
function update_number_of_adds_found(field_dropdown, selected_value) {
selected_value="";
for(i=0; i<document.submitadd.elements.length; i++){
if(document.submitadd.elements[i].value !='' && document.submitadd.elements[i].value != 'Αναζήτηση' && document.submitadd.elements[i].checked !=''){
selected_value += (document.submitadd.elements[i].name +'-' + document.submitadd.elements[i].value +' ');
}
}
var result5 = $.ajax({
'url': '<?php echo site_url('search/findNumberOfAdds'); ?>/' + selected_value,
'async': false
}).responseText;
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(result5);
}
This script send the data in the following format:
addtypeid-1%20isnew-1%20geographicareaid-3
I am a bit restriced in which symbols i can use, because I am using codeigniter, and if I use & for example i get message that i use dissalowed characters in my url.
My question is how can i transform this data in the format $key['fieldname'] = $value['fieldvalue'] so i can built my where clausule?
I was trying something with explode or replace, but without success so far. Any help will be deeply appreciated.
Regards, John
Just following up on my comment above ... You can try something like this ... I haven't tested it but should give you ideas to how to go about ...
jQuery('.submit').click(function(){
var str = $("#myForm").serialize();
str += '&serialize=' + encodeURIComponent(str);
str += '&action=myformsubmit';
jQuery.ajax('phpscripturl.php', {
method: 'POST',
data: str,
success: function(response) {
alert('Got this from the server: ' + response);
},
beforeSend: function(){
alert('Sending...');
}
});
return false;
});
By serializing the form inputs with jQuery's serialize you create a string like:
a=1&b=2&c=3&d=4&e=5&postID=10
So you can fetch this serialized data as
$data = $_POST['serialize'];
foreach($data as $key => $value) {
if($value == '') continue; //skip empty values as per your request
//else save in db etc ...
}
Build an JSON object then Stringify and post it in one variable. Then use json_decode($_POST['key']) to create a PHP object and can access the values easily.
In JS
var ValueToSend = new Object();
ValueToSend.field1 = value1;
var postString = JSON.stringify(ValueToSend)
In PHP
$Object = decode_json($_POST['key']);

Using Javascript with php

I know this question has already been asked a few times, but I'm trying to use javascript with php. I have a file called parsing.php that parses through a xml feed and converts the metadata into JSON Object called "data". The parsing is done using ajax calls with JavaScript and JQuery.
<script src="json2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
category.videos.push(video);
}
data.categories.push(category);
}
});
window.data = JSON.stringify(data);
<script>
"<?php
$dataVar = ?> <script type=text/javascript>window.data</script><?php;?>"
"<?php
print_r($dataVar,true);
?>"
The only reason why I need to use javascript and php is because I want to use the "print_r()" function from php which allows me to return the information rather than just printing it to the screen, but unfortunately I can't get it to work. If anybody knows of other alternative or could give some advice that would be greatly appreciated.
Here is what I believe you are trying to achieve, written in PHP:
$dom = new DOMDocument();
$dom->load("fakeFeed.xml");
$data = ["categories"=>[]]; // may need to use array() instead of [] depending on PHP version
foreach($dom->getElementsByTagName('item') as $item) {
$name = trim($item->getElementsByTagName('category')->item(0)->textContent);
if( !isset($data['categories'][$name])) {
$cat = ["name"=>$name,"videos"=>[]]; // again, adjust if you're on an older version
// I'm not entirely sure what you're trying to achieve on this part.
// you seem to be getting the same video five times...
// revise your approach, comment if needed, and I can try to help
// for now, "insert code here"
$data['categories'][$name] = $cat;
}
}
// we were using the name as a key for simplicity, now just take the values
$data['categories'] = array_values($data['categories']);
// done! $data now has your data.
var_dump($data);
If you really want to use this instead of using document.log for JS:
$.ajax({
type: "POST",
url: "some_php.php",
data: JSON.stringify(data);
})
.done(function( msg ) {
document.write(msg);
});
and the some_php.php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Categories

Resources