Problem showing file info with Ajax and PHP - javascript

I have a list of files made by my PHP code
if ($handle = opendir($director))
{
$path="images/files/nou/";
if(Files::is_empty_dir($director))
{
echo "<p>There are no script available.</p>";
}
else
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$size=Files::getSize($director."/".$file);
$exts=Files::getExtension($file);
$filex = str_replace(".".$exts,"",$file);
if(strlen($filex)>10)
{
$filex=substr($filex,0,6);
}
echo "<div class='file' title='".$file."'>".$filex."</div>";
There are functions defined in my own class Files.
Good. I want that on mouseover to show file information with this code
function getInfo($file)
{
$info="<div class='info_public'><table border=0 cellpadding=2><tr>";
$info.="<td>File : </td><td>".$file."</td></tr>";
$info.="<tr><td>Extension : </td><td>".Files::getExtension($file)."</td></tr>";
$info.="<tr><td>Size : </td><td>".Files::getSize($file)."</td></tr>";
return $info;
}
I want to show info dynamically with JQuery. I wrote this
$(".file").mouseover(function()
{
data=$(this).attr("title");
alert(data);
});
It alerts always first filename not what I crossed with mouse. But if I disable mouseover JQuery function, the title appears correctly for each file in part. If I use mouseover function, the selected value from title doesn't appear correctly, it shows first filename in alert no matter what file I crossed with mouse.
I called the alert function to see results before implementing $.ajax function to avoid bad responses.
What's the problem in my script ?
Thank you

Your jquery code works, so check something else, may be you need to onload() that script ?
http://jsfiddle.net/oceog/hJyRm/

Related

How to load php vars from an external file with javascript

I had this code inside the <div id="chtmsg"> on a page that shows a messenger...
PHP :
if($perguntas){
for($c=0;$c<count($perguntas);$c++){
$perguntas[$c]->tipo == 'F' ? $class = 'message_F' : $class = 'message_P';
$hora = substr($perguntas[$c]->hora, 0, 5);
echo "<li class=\"".$class."\"><p>".$perguntas[$c]->mensagem."</p><span>".$pergunta->databr($perguntas[$c]->data)." - ".$hora."</span></li>";
if($perguntas[$c]->tipo=='F' and $perguntas[$c]->status == 0){
$pergunta->marcaRespLida($perguntas[$c]->id);
}
}
}
It works very well. So, I wanted to load it with js to refresh all new messages only inside the div #chtmsg and then I created a file msg.php and with the <?php include("msg");?> it continues working good, but with js I needed to put the path...
HTML :
$(document).ready(function () {
setInterval(function() {
$.get(hostGlobal+'site/modulos/produto/msg.php', function (result) {
$('#chtmsg').html(result);
scTop();
});
}, 3000);
});
But its shows the error inside de div...
Notice: Undefined variable: perguntas in /Applications/XAMPP/xamppfiles/htdocs/sisconbr-sistema-novo/site/modulos/produto/msg.php on line 3
I tested other codes inside the msg.php file and works ok without variables...
Just a thought...
Your first line in PHP
if($perguntas){
Should perhaps check if defined like so
if(isset($perguntas)){
My suggestion explained in another answer here
For better code, You should preferably use:
if (isset($perguntas) && is_array($perguntas)){

Multiple JSON arrays as reponses - AJAX & PHP

I have a PHP script setup that echo's JSON responses depending on what the user has done (or not done as the case may be):
The responses look like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
Each response is generated like this:
echo $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
This is picked up by pNotify and displayed - lovely. (See below .done function for ajax request)
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var array = json_to_array(msg);
}
if (array['type'] !== 'none') {
if (array['title'] !== null) {
pushNotification(array['title'], array['response'], array['type'], array['hide']);
} else {
pushNotification(ucfirst(array['type']), array['response'], array['type'], array['hide']);
}
}
ready_status();
});
If the response cannot be validated by tryParseJSON(); the reponse is written directly to the page for debugging.
The problem is when I echo multiple responses back like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NDat]","title":"Exception","hide":false}
tryParseJSON() sees it as mumbo jumbo and prints it to the page.
Question
How do i pick up the above two lines as separate responses and parse them through my function and sub-sequentially to pNotify without combining them into a single JSON array?
Solution
As pointed out this was over complicated. Instead I combined each response (PHP side) into a an array:
$res['json'][] = $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
Then echo'ed it at the end of the script:
echo json_encode($res['json');
On client side, I used a for loop, sending them to pNotify in each iteration:
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var obj = json_to_array(msg);
}
for (var i=0;i<obj.length;i++) {
if (obj[i]['type'] !== 'none') {
if (obj[i]['title'] !== null) {
pushNotification(obj[i]['title'], obj[i]['response'], obj[i]['type'], obj[i]['hide']);
} else {
pushNotification(ucfirst(obj[i]['type']), obj[i]['response'], obj[i]['type'], obj[i]['hide']);
}
}
}
ready_status();
});
Instead of creating so sperate JSON-Outputs merge it to one single output string.
For this just wrap your two arrays you are currently outputting separately in an array like so
$myOutput[0] = responseArray1;
$myOutput[1] = responseArray2;
echo json_encode($myOutput);
This way you will get a valid JSON-response. Everything else is just some dirty workaround and causes shivers to everyone who has to review your work.

Jquery script wont see the difference between the 2 div's

I have a database with my projects, Table called: Projects. In this table i have 3 columns:
ID, Titel, BLOB
This is my php:
{
echo '<div class="project_box">';
echo '<p class="project_text">' . $row['titel'] . '</p>';
echo '<img class="project_box_image" src="data:image/jpeg;base64,' . base64_encode($row['image']) . '" width="200" height="200"</img>';
echo '</div>';
}
Every ting loads already into my website, but now i want to check if the titel equals to something, with jQuery.
Now I have this code, but it works only for 1 div. If I make a second div in my database it loads in my website but when i click each of them it says alert "test".
It seems my code wont see the difference between the 2 title's in my div's
$('.project_box').click(function() {
if ($('.project_text').text() == "Portefolio"){
window.location.href = "portefolio/";
}else if ($('.project_text').text() == "test"){
alert('test');
}
});
.project_box is the div I load my, title and BLOB in, and on click I want to check project text equals to something.
.project_text is the title text of the project.
I hope its clear for you, it would really help my out!
thanks.
When you have multiple <p class="project_text"> how do you think jQuery interprets $('.project_text')? You can use .find() to get the class that is inside the clicked box.
$('.project_box').click(function() {
if ($(this).find('.project_text').text() == "Portefolio"){
window.location.href = "portefolio/";
}else if ($(this).find('.project_text').text() == "test"){
alert('test');
}
});
I think a switch() would be better here as well, saves you writing the .text() part multiple times.
$('.project_box').click(function() {
switch ($(this).find('.project_text').text()) {
case "Portefolio":
window.location.href = "portefolio/";
break;
default:
alert("test");
break;
}
});
it seems that it will solve your problem:
Better Way use children():
replace your jquery by this:
$('.project_box').click(function() {
var strText = $(this).children(".project_text").text();
if (strText == "Portefolio"){
alert("portefolio");
}else if (strText == "test"){
alert('test');
}
});
Demo:http://jsfiddle.net/a6NJk/676/

Php opens up a whole bunch of windows

I have a php script that I got from another guy and for some reason the login function does not work unless it opens up in a new window. (??? no idea why but that's just how it is) Anyways when I execute the open up window javascript from my PHP file, it opens up a whole bunch of windows. I figured that it was somehow looping, so I put the javascript function inside of a for loop that should only execute once. When I click my button, it opens up windows continously until I feverishly close them all and it stops.
Here is the code that seems to be the issue:
if(basename($_SERVER['PHP_SELF'])==USRFILE && (isset($_REQUEST['usr']) || isset($_REQUEST['susr']) || isset($_GET['mp']) || isset($_REQUEST['rc'])))
{
if(ISAJAX === 0) include(USRTEMPL.'head.php'); // if not Ajax request, include head.php (from USRTEMPL)
include(USRINCLS.'class.UsersReg.php'); // include the class for Register (used also for Recovery data)
ob_start(); // start storing output in buffer
// if 'susr'=Register, create objet of UsersReg (for Register)
// if 'rc' or 'mp' (for Recover-Confirma), uses UsersRecov class
// if 'usr', create object of UserPage class (for user page data)
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
}
else if(isset($_REQUEST['rc']) || isset($_GET['mp'])) {
include(USRINCLS.'class.UsersRecov.php'); //account recovery
$objRe = new UsersRecov($mysql);
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?rc=Recover');</script>";
}
}
Specifically this section:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
I tried looking up javascript opening up many windows but didn't find anything noteworthy. Same goes when I looked up php opening up a whole bunch of windows. It really makes no sense why it is looking, because it was looping before I put the for loop in. I put in the for loop to stop it, and it still loops.
If this code lives on or gets executed from users.php then that is your problem, because you would have an infinite loop.
The first line only runs this code on the users.php page (or it seems that way based on the constant name). The code goes on to say:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
I'm assuming that $lsite['users_logform']['register'] == 'Register'. Thus, when you visit users.php, this code runs. If the $_REQUEST['susr'] == 'Register' (because of the first page load that opened a new window to a url that matches users.php?susr=Regsiter), then you are instructing it to open ANOTHER instance of the page again, here:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
}
IMO, you need to tell the second request to users.php (generated by your javascript bit) that it is from javascript. Then ignore your entire code block if it is from javascript. Something like this should work:
if ( !isset($_GET['from_js']) && basename($_SERVER['PHP_SELF'])==USRFILE && ( isset($_REQUEST['usr']) || isset($_REQUEST['susr']) || isset($_GET['mp']) || isset($_REQUEST['rc']) ) )
{
if(ISAJAX === 0) include(USRTEMPL.'head.php'); // if not Ajax request, include head.php (from USRTEMPL)
include(USRINCLS.'class.UsersReg.php'); // include the class for Register (used also for Recovery data)
ob_start(); // start storing output in buffer
// if 'susr'=Register, create objet of UsersReg (for Register)
// if 'rc' or 'mp' (for Recover-Confirma), uses UsersRecov class
// if 'usr', create object of UserPage class (for user page data)
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
// there is no reason for the for loop. totally pointless
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register&from_js=1');</script>";
}
else if(isset($_REQUEST['rc']) || isset($_GET['mp'])) {
include(USRINCLS.'class.UsersRecov.php'); //account recovery
$objRe = new UsersRecov($mysql);
// there is no reason for the for loop. totally pointless
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?rc=Recover&from_js=1');</script>";
}
}
Ok. I changed the first line to include a check for the $_GET['from_js'] variable. I removed the for loops, because they are totally pointless, since they only ever run once. To the urls that are opened in the new window, I added &from_js=1. With this, your code does not run on the subsequent new window openings. This will prevent the infinite popups.
Hopefully this helps.
Change
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
to:
header('Location: users.php?susr=Register');

Zend_Form Jquery & fileUploadErrorIniSize

Edit, I fixed it by changing my JS to:
$('.zend_form input:not([type="file"]), .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
Hello,
As I posted earlier, I followed a ZendCast that allowed you to use jQuery to detect and display to users problem with their form.
However, file fields always return: fileUploadErrorIniSize (File 'image_front_url' exceeds the defined ini size" even if the file is within size limits.
TPL For Forms:
<?php $this->headScript()->captureStart(); ?>
$(function() {
$('.zend_form input, .zend_form textarea').blur(function() {
var formElementId = ($(this).parent().prev().find('label').attr('for'));
doValidation(formElementId);
});
});
function doValidation(id) {
var url = '/<?php echo MODULE; ?>/json/validateform/form_name/<?php echo get_class($this->form); ?>';
var data = {};
$('.zend_form input, .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function(resp) {
$('#'+id).parent().find('.errors').remove();
$('#'+id).parent().append(getErrorHtml(resp[id], id));
}, 'json');
};
function getErrorHtml(formErrors, id) {
var o = '';
if (formErrors != null) {
var o = '<ul id="errors-'+id+'" class="errors">';
for (errorKey in formErrors) {
o += '<li>'+formErrors[errorKey]+'</li>';
}
o += '</ul>';
}
return o;
}
<?php $this->headScript()->captureEnd(); ?>
<?php
if (is_object($this->form) && $this->form->getErrorMessages()) {
echo $this->partial('partials/errors.phtml', array('errors' => $this->form->getErrorMessages(), 'translate' => $this->translate));
}
?>
<?php if (isset($this->errorMsg)) { ?>
<p><?php echo $this->errorMsg; ?></p>
<?php } ?>
<?php echo $this->form; ?>
Which is directed to
<?php
class Administration_JsonController extends Zend_Controller_Action {
public function validateformAction() {
$form_name = $this->_getParam('form_name');
$form = new $form_name();
$data = $this->_getAllParams();
$form->isValidPartial($data);
$json = $form->getMessages();
$this->_helper->json($json);
}
}
Example of returned json:
{"name":{"isEmpty":"Value is required and can't be empty"},"name_url":{"isEmpty":"Value is required and can't be empty"},"image_site_url":{"fileUploadErrorIniSize":"File 'image_site_url' exceeds the defined ini size"},"image_url":{"fileUploadErrorIniSize":"File 'image_url' exceeds the defined ini size"},"image_front_url":{"fileUploadErrorIniSize":"File 'image_front_url' exceeds the defined ini size"},"image_back_url":{"fileUploadErrorIniSize":"File 'image_back_url' exceeds the defined ini size"}}
I noticed a few people had this issue and they said that isValidPartial fixes it, so I changed
$form->isValid($data);
to
$form->isValidPartial($data);
but it didn't fix this issue.
Any ideas?
The problem is that you can't treat file fields in the same manner as regular text fields.
When you call $('input').val(), you get an actual text value for the text field, but for the file field you get the file name - and not the file contents.
Then your script tries to validate your file name as a file and, apparently, fails. In order for file validator to succeed you need to pass actual file contents to the script.
So, basically, you need to upload a file asynchronously to the server to perform all the necessary validations.
Unfortunately, uploading files via Ajax is not quite a trivial thing to do. Your basic options are uploading files via iFrame or swfObject. You can take a look at the broad selection of plugins suitable for this purpose here.
My personal choice for asynchronous file upload would be file-uploader jQuery plugin.
Are you putting an Encrypt type on your form?
I have found two different forum posts about this, including a stack post:
odd Zend_Form_Element_File behavior
You need to add enctype="multipart/form-data" to your form tag.
Basically what is happening is the form is using its default "application/x-www-form-urlencoded" method of encryption before it is sent to the server. File uploading is not supported with this method.

Categories

Resources