Turning a Javascript Object Value into a Global Variable - javascript

I have an object from FullCalender
events: [
<?
$sql = "Query removed";
if ($result=mysqli_query($link,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_assoc($result))
{
echo " {
title: '".$row['eName']."',
backgroundColor: 'green',
start: '".$row['scheduledDate']."',
eventID: '".$row['eID']."'
}, " ;
}
// Free result set
mysqli_free_result($result);
}
?>
],
eventClick: function(event) {
$('#modifydialog').dialog('open');
$("#notes").val(event.eventID);
var eID = event.eventID;
}
I am trying desperately to make an object (the event.eventID into a global variable so I can use it here:
var eID = '';
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'checkDelete.php?sID=<?echo $sID;?>&eID='+eID, // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
Basically, I'm trying to take the value, and pop it into the ajax url for the get statement - I am open to suggestions if there are better ways. Thank you for any advice.

I think you can use:
'checkDelete.php?sID=<?echo $sID;?>&eID='+$("#notes").val()
that is if the value of this element won't be changed in the meantime. You can also declare eID in the global scope and use eID = event.eventID; to set it.
var eID;
events: [
....
],
eventClick: function(event) {
.....
eID = event.eventID;
}
you can even do this:
window.eID = event.eventID;

Related

Save the last table filter query when user come back to the page

I'm new on Symfony. I have a table with 5 filters and I want to keep the state of them (save the last query) when the user come back again to that page where the table is because the filters are reset.
I've being reading about how to do it, because I have no idea. I read about html web storage, about session variable but I cant find any example of how to do it, could please someone explain me which is the best method to do it and how to apply.
Here is my filterAction on my controller:
/**
* #Route("/filterFichas/", name="filterFichas")
*/
public function filterFichasAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$txtColectivo = $request->request->get('colectivo');
$txtRol = $request->request->get('rol');
$txtEstadosObjetivos = $request->request->get('EstadosObjetivos');
$txtEstadosFichas = $request->request->get('EstadosFichas');
$idPeriodo = $request->request->get('periodo');
$periodo = $em->getRepository('GOCModelBundle:Periodo')->findOneBy(array('id' => $idPeriodo));
$respuesta = array();
foreach ($periodo->getFicha() as $ficha){
$flag = true;
if($txtColectivo != "todas"){
$colectivo= $em->getRepository('GOCModelBundle:Colectivo')->findOneBy(array('nombre' => $txtColectivo ));
if($ficha->getUser()->getColectivo() != $colectivo){
$flag = false;
}
}
if($txtRol != "todas"){
$rol = $em->getRepository('GOCModelBundle:Rol')->findOneBy(array('rol' => $txtRol ));
if($ficha->getUser()->getRol() != $rol){
$flag = false;
}
}
if($txtEstadosFichas != "todas"){
if(count($ficha->getFichacontenidoestado()) > 0){
$estadoContenido = $em->getRepository('GOCModelBundle:Estadocontenido')->findOneBy(array('descripcion' => $txtEstadosFichas ));
if($ficha->getFichacontenidoestado()[count($ficha->getFichacontenidoestado()) - 1]->getEstadocontenido() != $estadoContenido){
$flag = false;
}
}else{
$flag = false;
}
}
if($txtEstadosObjetivos != "todas"){
if(count($ficha->getFichaobjetivosestado()) > 0){
$estadoObjetivos = $em->getRepository('GOCModelBundle:Estadobjetivo')->findOneBy(array('descripcion' => $txtEstadosObjetivos ));
if($ficha->getFichaobjetivosestado()[count($ficha->getFichaobjetivosestado()) - 1]->getEstadobjetivo() != $estadoObjetivos){
$flag = false;
}
}else{
$flag = false;
}
}
if($flag){
$respTemp = array(
'user' => $ficha->getUser(),
'ficha' => $ficha,
);
array_push($respuesta, $respTemp);
}
}
return $this->render('GOCFichasBundle:Default:fichasFilter.html.twig', array(
'usr' => $respuesta,
));
}
and here is my js action for the filter:
function filterFichas() {
$.blockUI({ message: '<h4><img src="{{ asset('assets/global/plugins/cubeportfolio/cubeportfolio/img/cbp-loading.gif') }}" /> Cargando datos, por favor espere...</h4>' });
var idPeriodo = $('#selectPeriodoActual').val();
$( "#tabla" ).load( "{{ path('filterFichas')}}",
{
colectivo:$( "#selectColectivo" ).val(),
rol: $( "#selectRol" ).val(),
EstadosObjetivos: $( "#selectEstadoObjetivos" ).val(),
EstadosFichas: $( "#selectEstadoFichas" ).val(),
periodo: idPeriodo
},
function() {
$.unblockUI();
});
}
How can I save the last filter action the user did so when the user come back has the last filtered table.
You can use cookies to save your filter value.
$.cookie($( "#selectEstadoFichas" ).val(), 1, { expires : 10 });
The easiest way to do this is to use the session component which is easily accessible inside your controller if it inherits the BaseController.
You can use $this->get('session') to retrieve the session service inside your controller. After that, the interface you can use to interact with it is pretty much the same as the parameter bags of the Request object you are already using (get and set methods have the same signature).
Thus, for handling a parameter, you would have to check first if it is already inside the $request->query parameter bag. If not, look inside the session for a value and if it is still not there, fallback to a default value (presumably null in your case).
You can take advantage of the second optional parameter of the get method that defines a default value in case nothing was found to do this in one line. After that, you can just save the retrieved value in the session so that it can be retrieved when the user comes back later.
$session = $this->get('session');
...
$myParam = $request->request->get('myParam', $session->get('myParam'));
if($myParam !== null)
{
$session->set('myParam', $myParam);
}
By doing that, $myParam will be null if myParam is not defined both in the request and in the session. Either way, if the retrieved value is not null, it is stored into the session for further use.
Note however that, since we are talking about sessions here, those saved parameters will only last for the duration of the session of the user. If your user closes the web browser and comes back, previously saved parameters will be lost.

PHP AJAX upload is not working correctly with php://input

I am trying to use the JavaScript/jQuery Ajax File Uploader by Jordan Feldstein available at https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
It is an older library but still very popular due to it's simplicity and for being so lightweight (around 100 lines) and you can attach it to a single form input filed and it simply works! You select a file as normal with the form inut filed and on selection it instantly uploads using AJAX and returns the uploaded file URL.
This makes the library good for my use where I am uploading a file inside a modal window which is also generate with AJAX and I have used this library in many similar projects.
My backend is using PHP and Laravel and that is where my issue seems to be.
My test script works but when I implement it into my Laravel app it returns this error....
ERROR: Failed to write data to 1439150550.jpg, check permissions
This error is set in my controller below when this code is not retuning a value...
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
So perhaps this part file_get_contents('php://input') does not contain my file data?
It does create the proper directory structure and even a file which is /uploads/backing/2015/08/1439150550.jpg
The 1439150550.jpg is a timestamp of when the upload took place. It create this file in the proper location however the file created has no content and is 0 bytes!
Below is my Laravel Controller action which handles the back-end upload and below that the JavaScript....
PHP Laravel Controller Method:
public function uploadBackingStageOneFile(){
// Only accept files with these extensions
$whitelist = array('ai', 'psd', 'svg', 'jpg', 'jpeg', 'png', 'gif');
$name = null;
$error = 'No file uploaded.';
$destination = '';
//DIRECTORY_SEPARATOR
$utc_str = gmdate("M d Y H:i:s", time());
$utc = strtotime($utc_str);
$filename = $utc . '.jpg';
$folder = 'uploads/backing/'.date('Y') .'/'.date('m');
//if Directory does not exist, create it
if(! File::isDirectory($folder)){
File::makeDirectory($folder, 0777, true);
}
// Save Image to folder
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
if (!$result) {
Log::info("ERROR: Failed to write data to $filename, check permissions");
return "ERROR: Failed to write data to $filename, check permissions\n";
}
$url = $folder . '/' . $filename;
return Response::json(array(
'name' => $name,
'error' => $error,
'destination' => $url
));
}
JavaScript AJAX FIle Upload LIbrary
/*
// jQuery Ajax File Uploader
//
// #author: Jordan Feldstein <jfeldstein.com>
// https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
// - Ajaxifies an individual <input type="file">
// - Files are sandboxed. Doesn't matter how many, or where they are, on the page.
// - Allows for extra parameters to be included with the file
// - onStart callback can cancel the upload by returning false
Demo HTML upload input
<input id="new-backing-stage-1-file" type="file">
Demo JavaScript to setup/init this lbrary on the upload field
$('#new-backing-stage-1-file').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
*/
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery );
My JavaScript usage of the above library:
// When Modal is shown, init the AJAX uploader library
$("#orderModal").on('shown.bs.modal', function () {
// upload new backing file
$('#new-backing-stage-1-file').ajaxfileupload({
action: 'http://timeclock.hgjghjg.com/orders/orderboards/order/uploadbackingimage',
params: {
extra: 'info'
},
onComplete: function(response) {
console.log('custom handler for file:');
console.log('got response: ');
console.log(response);
console.log(this);
//alert(JSON.stringify(response));
},
onStart: function() {
//if(weWantedTo) return false; // cancels upload
console.log('starting upload');
console.log(this);
},
onCancel: function() {
console.log('no file selected');
console.log('cancelling: ');
console.log(this);
}
});
});
The problem is like you said, file_get_contents('php://input') does not contain your file data.
jQuery.AjaxFileUpload plugin wrap file input element with a form element that contains enctype="multipart/form-data" attribute. 1
From php documentation: 2
php://input is not available with enctype="multipart/form-data".

Problems passing parmaters in Javascript

I am trying to pass several variables from a php page into a java script. However only the first parameter is being passed.
The php page calls the script like this:
<?
$sdate = 0;
$edate = 2;
?>
<script type="text/javascript">
window.onload = function() {
datagrid = new DatabaseGrid('<? echo $sdate; ?>', '<? echo $edate; ?>');
};
</script><BR>
The Java Script being called is:
function DatabaseGrid(sdate, edate)
{
this.editableGrid = new EditableGrid("demo", {
enableSort: true,
tableLoaded: function() { datagrid.initializeGrid(this); },
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
}
});
this.fetchGrid(sdate);
this.fetchGrid(edate);
}
DatabaseGrid.prototype.fetchGrid = function(sdate, edate) {
// call a PHP script to get the data
alert("loaddata_dailyotp.php?o=" + sdate + "&e=" + edate + "");
this.editableGrid.loadXML("loaddata_dailyotp.php?o=" + sdate + "&e=" + edate + "");
};
DatabaseGrid.prototype.initializeGrid = function(grid) {
grid.renderGrid("tablecontent", "testgrid");
};
I added the alert window to show the exactly what was being requested. I was expecting this:
loaddata_dailyotp.php?o=0&e=2
However what I am getting is:
loaddata_dailyotp.php?o=0&e=undefined
Why is my second parameter not going through?
You are not passing the "edate" parameter to your fetchGrid() call. That's why it's displayed as "undefined". For some reason you're calling fetchGrid() two times instead.
You could do it the following way:
<script type="application/json">
var payload = <?= json_encode(array('sdate' => $sDate, 'edate' => $eDate)); ?>
</script>
and then call your script:
<script type="text/javascript">
window.onload = function() {
datagrid = new DatabaseGrid(payload.sdate, payload.edate);
};
</script>
Call fetchGrid like this
function DatabaseGrid(sdate, edate)
{
this.editableGrid = new EditableGrid("demo", {
enableSort: true,
tableLoaded: function() { datagrid.initializeGrid(this); },
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
}
});
this.fetchGrid(sdate, edate);
}
You missed to pass the second parameter.
I am sharepoint developer. I faced the same issue in one my application where i was passing two values and only first value was reaching the other end. even alert box was showing two values.
Issue was only last values was not reaching other end so CRAZY SOLUTION was to pass 3 parameters, 3rd being test param so my two params were reaching other end and 3rd param which was anyways useless was getting neglected automatically.
Suggestion in your case :
Please check with THREE parameters whether you are still getting only 1 param or
params ;)

How do you use a php variable for directory path?

I am getting userid from the url.
This is what I have at the moment. I want to replace the one with $userid but I don't know how. It doesn't work and I can't seem to find the right syntax, please can someone help?
function returnimages($dirname = "Photos/1")
Basically I am trying to create a photo slideshow using html, php and javascript. I had something working before I started adding php into my code. I had html and an external javascript that changes the photos and they fade in and out in a loop. I have a photo array in javascript. Right now I am trying to add php to my html. I want to be able to get userid via url and then from that get the photos from a specific path to the userid in the directory. Then I am hoping to create an array of these photos and use them in my javascript. Here is my php code embedded in my html:
<?php
$user_id = $_GET['userid'];
print " Hi, $user_id ";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And my javascript:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
//photodisplay[0].hide().fadeIn(3000);
var user = new Array();
[1, 2, 3, 4, 5];
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
var userphoto = <? echo json_encode($galleryarray); ?>;
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/1" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
My url to get userid:
http://example.com/code.php?user_id=1
Thank you for your time!
The problem is that you are always setting the dirname instead of letting calling the function set it. You could change:
function returnimages($dirname = "Photos/1") {
to
function returnimages($dirname) {
because otherwise the $dirname is always Photo/1. Then, when you call the function, use:
returnimages('Photos/'.$user_id);
You can concatenate in PHP by using the dot '.'. This will concatenate two string and then assign them to the variable $dirname. For example:
$dirname = "Photos/" . $_GET['ID'];
The variable $dirname can then be placed in the function returnimages, like:
returnimages($dirname);

YUI Dialog using ajax request - want to execute javascript returned from Java but out of scope

I have a YUI dialog that submits a form to a Java servlet. The servlet returns html and javascript. I take the response and put it into a div on the page and then eval the javascript that is within the div.
My problem is that I get an error in the firebug console saying "YAHOO is not defined" as soon as the servlet returns.
I do not include the YUI js files in the servlet as I didn't think I would need them, I would expect the files included in the head of the main page would be sufficient.
If I remove all references to YUI from the javascript returned by my servlet then everything works well.
What should I do to stop getting this error as soon as my servlet returns?
My Servlet returns something along the lines of:
<div id="features">some html to display</div>
<script id="ipadJS" type='text/javascript'>
var editButton1 = new YAHOO.widget.Button('editButton1', { onclick: { fn: editButtonClick, obj: {id: '469155', name : 'name 1'} } });
var editButton2 = new YAHOO.widget.Button('editButton2', { onclick: { fn: editButtonClick, obj: {id: '84889', name : 'name 2'} } });
</script>
Here is the code that I used to create the dialog, i use the handleSuccess function to put my response from my servlet into the page (note that even though im not actively putting the javascript into the page it still throws the 'YAHOO not defined' error.):
YAHOO.namespace("ipad");
YAHOO.util.Event.onDOMReady(function () {
// Remove progressively enhanced content class, just before creating the module
YAHOO.util.Dom.removeClass("createNewFeature", "yui-pe-content");
// Define various event handlers for Dialog
var handleSubmit = function() {
this.submit();
};
var handleCancel = function() {
this.cancel();
};
var handleSuccess = function(o) {
var response = o.responseText;
var div = YAHOO.util.Dom.get('features');
div.innerHTML = response;
};
var handleFailure = function(o) {
alert("Submission failed: " + o.status);
};
// Instantiate the Dialog
YAHOO.ipad.createNewFeature = new YAHOO.widget.Dialog("createNewFeature",
{ width : "450px",
fixedcenter : true,
visible : false,
constraintoviewport : true,
buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
{ text:"Cancel", handler:handleCancel } ]
});
// Validate the entries in the form to require that both first and last name are entered
YAHOO.ipad.createNewFeature.validate = function() {
var data = this.getData();
return true;
};
YAHOO.ipad.createNewFeature.callback = { success: handleSuccess,
failure: handleFailure,
upload: handleSuccess };
// Render the Dialog
YAHOO.ipad.createNewFeature.render();
var createNewFeatureShowButton = new YAHOO.widget.Button('createNewFeatureShow');
YAHOO.util.Event.addListener("createNewFeatureShow", "click", YAHOO.ipad.clearFeatureValues, YAHOO.ipad.clearFeatureValues, true);
var manager = new YAHOO.widget.OverlayManager();
manager.register(YAHOO.ipad.createNewFeature);
});
I don't know your use case exactly, but if you just need to create some buttons on the fly based on server response, than it would IMO be better to return JSON or XML data with the variable data and then create the buttons. Something like
var reply = eval('(' + o.responseText + ')');
var editButton1 = new YAHOO.widget.Button('editButton1',
{ onclick: { fn: editButtonClick,
obj: {id: reply[id], name : reply[name]}
} })
And if you really want to append a script node, then the following approach should work:
var response = o.responseText;
var snode = document.createElement("script");
snode.innerHTML = response;
document.body.appendChild(snode);

Categories