Why my json is returning false? - javascript

I need some help, i can't understand why my json is returning false...
This is my Ajax :
var xhr10 = getXhr();
length=document.getElementById('ChoosenStuff').options.length;
ListChoosenStuffNames = [];
for(var i=0;i<length;i++)
{
ListChoosenStuffNames[i] = document.getElementById('ChoosenStuff').options[i].value;
}
xhr10.onreadystatechange = function(){
if(xhr10.readyState === 4 && xhr10.status === 200){
Selection = JSON.parse(xhr10.responseText);
for(var i = 0; i < Selection.length; i++) {
document.getElementById('ShowResult').innerHTML += Selection[i] + "\n\r";
}
}
};
xhr10.open("POST","Ajax/AjaxGetDTravauxCorrespondant.php",true);
xhr10.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr10.send("ListChoosenStuffNames="+ListChoosenStuffNames);
And then my php file with my query which works on phpMyAdmin :
include '../Reglage/ConnexionBDD.php';
$res = [];
$Query="Select NomDomaineTravaux from equipement
JOIN typeequipement ON equipement.CodeTypeEquipement =
typeequipement.CodeTypeEquipement
JOIN domainetravaux ON typeequipement.IDDomaineTravaux =
domainetravaux.IDDomaineTravaux
WHERE NomEquipement=:stuff";
$rep = $bdd->prepare($Query);
$custom = $_POST['nomsEquipementsChoisis'];
$rep->bindParam(':stuff',$custom);
$rep->execute();
$NomDomaineTravaux= $rep->fetch(PDO::FETCH_ASSOC);
$res[$i]= $NomDomaineTravaux;
echo json_encode($res, true);
I have {NomDomaineTravaux: "Divers"}
how do i use this to display "Divers" in my js file with obj = JSON.parse(xhr.reponseText) ?
I tried obj.NomDomaineTravaux but it says that he dont recognize this... :(
Thanks A LOT,

Related

javascript google script appendRow fails Service Error

I have a Google Apps Script that has been running for 3 months and starting a few weeks ago I'm getting a "Service Error" on the Appendrow function which I've bolded below. Any ideas on how to fix this?
function updateACOPS2(){
var ss = SpreadsheetApp.openById(".....")
var sheetSubmission = ss.getSheetByName("Sheet8");
var dataSubmission = sheetSubmission.getDataRange().getValues();
var lastColSubmission = sheetSubmission.getLastColumn();
var ssActive = SpreadsheetApp.openById("....")
var sheetActive = ssActive.getSheetByName("AcopsAll");
var sheetMain = ssActive.getSheetByName("Sheet1");
var dataActive = sheetActive.getDataRange().getValues();
var lastrow = sheetActive.getLastRow();
for(var i = 1; i < dataSubmission.length && dataSubmission[i][2] != ""; i++){
var currentIDSubmission = dataSubmission[i][2] + dataSubmission[i][3];
var checkGotMatch = false;
var toCopyRow = sheetSubmission.getRange(i+1,1,1,71);
// copy entire row for new record
Logger.log(currentIDSubmission);
// if there is a matching record flag as matched
for(var j = 1; j<dataActive.length; j++){
var currentIDActive = dataActive[j][2] + dataActive[j][3];
var currentIDSub = dataSubmission[i][2];
if(currentIDSub != '' && currentIDSubmission == currentIDActive){
checkGotMatch = true;
Logger.log(currentIDActive);
break;
}
}
// if it is a new record Append entire row
if(currentIDSub != '' && checkGotMatch == false){
**sheetMain.appendRow(toCopyRow.getValues()[0]);**
}
}
SpreadsheetApp.flush();
ss.toast("ACOPS Active has been updated.", "Complete");
}
In appendRow you need to pass an array so update your appendRow and try
sheetMain.appendRow([toCopyRow.getValues()[0]])

loop executes only last array element using php, ajax and javascript

Hi friends am trying to save the data from the loop here is my code.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body onload="searchVideo();">
<?php
ini_set('max_execution_time', 300);
$query = "SELECT * FROM `playlists`";
$result = mysqli_query($mysql,$query);
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
$playlists=$row['playlists'];
$myArray = explode(',', $playlists);
$length = sizeof( $myArray);
$myArray[0]=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-
$myArray[1]=PLFgquLnL59ak1QNHmrUSjNM6WTegpgX__
for ($i=0; $i<$length; $i++){
echo "
<script>
var pageToken = '';
var numOfResult = 0;
var maxResults = 200;
function searchVideo(){
var separator = ',';
$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken=' + pageToken + '&playlistId=$myArray[$i]&key=APIKEY&callback=?',function(data){
var l = data.items.length;
pageToken = data.nextPageToken;
numOfResult += l;
var itemUrl = '';
var videoids = [];
for(var i = 0; i < l; i++) {
if( i == 0) {
separator = ',';
}
else {
separator = ',';
}
var videoid = data.items[i].snippet.resourceId.videoId;
var title = data.items[i].snippet.title;
$.ajax({
method: 'POST',
url: 'add.php',
data: { title: title, videoid: videoid }
})
.done(function(data) {
});
}
if( numOfResult <= maxResults) {
searchVideo();
}
});
}
</script>
";
}
}
?>
add.php
<?php
$title = mysqli_real_escape_string($mysql,$_POST['title']);
$videoid = mysqli_real_escape_string($mysql,$_POST['videoid']);
$thumbnail_url = 'http://img.youtube.com/vi/'.$videoid.'/hqdefault.jpg';
$sql = "INSERT INTO ytfb(name,video_name,thumbnail_url) VALUES('$title','$videoid','$thumbnail_url')";
$create_post_query=mysqli_query($mysql,$sql);
if(!$create_post_query)
{
die("Connection failed".mysqli_error($mysql));
}
?>
When am trying to save the data using ajax in add.php the elements from the last array element are only saved the elements from the first array element is not saved how can I be able to save the data from all the array elements. Can anyone please help me out with this
Define the function searchVideo outside the cycle and organize to call it with different parameters. In cycle change global vars or input parameters of searchVideo.
Now you get this result because finaly executes the last istance of this function.
for(var i = 0; i < l; i++) {
if( i == 0) {
separator = ',';
}
else {
separator = ',';
}
var videoid = data.items[i].snippet.resourceId.videoId;
var title = data.items[i].snippet.title;
Here i will be the index of last element so only last item is getting stored.
You have to loop the ajax call through the loop to get all elements to be saved.

Outputting PHP string into a JS file causes syntax error

I'm trying to output a string into a JS file using PHP. Here's the PHP code
$embedded_form_js = "document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);";
I'm trying to write a JS file like so
$fp = fopen("FOLDER/FILE.js", 'w');
fwrite($fp, $embedded_form_js);
fclose($fp);
The problem is that when I try to write the JS file, this error happens.
syntax error, unexpected '(', expecting ']'
This is in reference to the line:
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
How can I remedy this?
use Nowdocs as it is single-quoted and won't try to interpret the $_GET
$embedded_form_js = <<<'EOS'
document.addEventListener('DOMContentLoaded', function(){
var parts = window.location.search.substr(1).split('&');
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split('=');
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
var ref = $_GET['ref'];
if (ref === 'undefined')
{
ref = 0;
}
}, false);
EOS;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

class inheritance in javascript/angular

I am working on my hello world project. I have two pages let's call them "configuration" and "add configuration" *.html. Each one has its own controller like this:
angular.module('MissionControlApp').controller('ConfigController', ConfigController);
angular.module('MissionControlApp').controller('AddConfigController', AddConfigController);
Now, each controller has some properties that very much overlap:
function ConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject;
vm.configurations;
vm.selectedConfig;
vm.selectedRecords;
vm.filteredConfig;
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
My AddConfigController also wants to have the same functionality for addFile() so I just copy pasted the same code, but coming from C# i am sure i can do some class inheritance here, and just inherit from ConfigController and extend...right?
If this is super noob question. then apologies. js is a bit of a mystery to me.
function AddConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject = {};
vm.newConfig = {};
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
Since you asked about inheritance and you appear to be using ECMAScript 5, let me suggest taking a look at Object.create(). Specifically, the classical inheritance example.
That said, in AngularJS, a better solution would be to create a Service that manages files or configurations and put the addFile function in there. That way, both controllers could inject the service and call the same function when it is time to add a file. Likewise, other services and controllers that may need access to this functionality could inject it as well.

compressing string in js and save in localStorage

I'm trying to save a HUGE json string in my localStorage but for some reason sometimes it saves it and sometimes not, I thought I should compress it so I took an LZW implementation in js from one of the threads in stackoverflow.
The problem is when I try to localStorage.setItem() the compressed string it gives me an error "Invalid argument", any idea why or what should I do?
Edit:
this is the code I'm using:
// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
this is the code that calls the compressing algorithm and saves it in LS
LOG("GetMerchantList(): Done");
var SITESVAR = unescape(data)
localStorage.setItem("MYSITES", lzw_encode(SITESVAR)); //this throws error
IWT.BuildMerchantList(SITESVAR);

Categories

Resources