I copied the code from a YouTube tutorial, modified the database connection and SELECT items to connect to my existing DB, but I can't seem to get the JS to load the PHP file. In Chrome using the "inspect" tool, I can see that the JS file is loading, but when I click on GRAB on my HTML page, it doesn't do anything. Almost like the JS file is loading but not running.
Webserver folder structure:
ROOT FOLDER
test.html
-AJAX (folder)
name.php
-JS (folder)
global.js
-CONNECTIONS (folder)
dbase.php
HTML CODE
<!doctype html>
<html>
<head>
<title>AJAX Database</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id=name-submit" value="Grab">
<div id="name-data"></div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
Javascript File
$('input#name-submit').on('click', function() {
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
PHP File
First try to add a console.log('something') inside your javascript click function, right before the var name =... line, to see that your event is even firing. If not you need to register the event properly. Is the click function surrounded by
$(document).ready(function () {
$('input#name-submit').on('click', function() {
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
});
//try using submit event
$(document).ready(function () {
$('input#name-submit').on('submit', function(e) {
e.preventDefault();
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
});
I'm not sure why my PHP code was edited and removed from here, but I've ended up re-writing the whole PHP page. I added or die(mysql_error()); to my SELECT statement and found that it needed me to specify my database in the FROM. I have multiple databases on my server and even though the DB is specified in the connection string it needed it again in the SQL Statement. The next problem I resolved was removing the mysql_num_rows as this was just not working like the demo did.
ORIGINAL PHP
<?PHP
if (isset($_POST['name']) === true && empty ($POST['name']) === false) {
require '../db/connect.php';
$query =mysql_query("
SELECT 'names'.'location'
FROM 'names'
WHERE 'names'.'name' = '" . mysql_real-escape_string(trim($_POST['name'])) . "'
");
echo (mysql_num_rows($query) !== 0) ? mysql_result($query, 0, 'location') : 'Name not found';
}
?>
The original was far too complicated for what I wanted and also for me to problem solve it so I re-wrote it:
NEW PHP FILE
<?PHP
//I've intentionally left out the connection data..
$sql_select = mysql_query("
SELECT names.location
FROM database_name.names
WHERE names.name = '" . $_POST['name'] . "'
")
or die(mysql_error());
$sql_fetch = mysql_fetch_assoc($sql_select);
echo $sql_fetch['name'];
?>
Thanks to those that assisted. Appreciated...
I am aware of the deprecated tags in the PHP file, but when I was copying from a demo so I wanted to get it working before updating it with new tags.
Related
I'm using emailjs to send email through my free subdomain website.There are two problems with it
1). My emailjs account-id, service-id and template-id is getting public so anybody can access it and send email through it.
2). to solve it I used following code but it steel appears in browser "inspect Element"(Developer tool).
<?php echo "
<script>
(function(){
emailjs.init(my user id);
})();
</script>" ; ?>
<?php
echo "<script src='js/formfilled.js'></script>";
?>
now my form submiting button is like this
<button onclick="email();">
Send
</button>
now my formfill file is like this
var myform = $("form#myform");
function email(){
var service_id = "default_service";
var template_id = "xxxxxxxxx";
myform.find("button").text("Sending...");
emailjs.sendForm(service_id,template_id,"myform")
.then(function(){
alert("Sent!");
myform.find("button").text("Send");
}, function(err) {
alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
myform.find("button").text("Send");
});
}
problem is that when I click the button rather than sending an email it reload the page .
Sorry if it is too silly i am totally beginner and Thanks in advance.
UPDATE
it is working if i put the code in the same file(not using external js)
code:--
<head>
<script type="text/javascript">
(function(){
emailjs.init("xxxxxxxxxxxxxxxxxxxxx");
})(); </head>
</script>
<body>
<!-- form is here-->
<script>
var myform = $("form#myform");
myform.submit(function(event){
event.preventDefault();
// Change to your service ID, or keep using the default service
var service_id = "default_service";
var template_id = "xxxxxxxxxxxxxxxxxxx";
myform.find("button").text("Sending...");
emailjs.sendForm(service_id,template_id,"myform")
.then(function(){
alert("Sent!");
myform.find("button").text("Send");
}, function(err) {
alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
myform.find("button").text("Send");
});
return false;
});
</script>
</body>
but if i put this code in formfilled.js it is not working.
what would be the reason behind it?
Answer:
to use
event.preventDefault();
and loading the file before the button is loaded.
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)){
I'm new to jquery and ajax. I'm trying to get my first ajax script to work, but it's not working and I need some assistance, please.
I have a php page that is supposed to post to another php page, where the latter will do some processing and get some files to get zipped and download. The user needs to input a starting and ending date, and the second php script will use this information to prepare the data. This functionality works perfectly fine without jquery, but doesn't work when I add jquery.
What do I want to achieve? I want to post in the to the same php page and get the post output in a <div></div> tag.
My first php page contains (downloadPage.php):
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<form action="doDownload.php" method="post" id="dateRangeID">
<input id='time1' class='input' name="datefield1" style="text-align:center;"/>
<input id='time2' class='input' name="datefield2" style="text-align:center;"/>
<input type="submit" value="Download Data" name="submit" id="submitButton">
</form>
<div id="result"></div> <!-- I would like it to post the result here //-->
The second page (doDownload.php),
<div id="content">
<?php
if(isset($_POST['submit']))
{
$dateVal1 = $_POST['datefield1'];
$dateVal2 = $_POST['datefield2'];
if($dateVal1 != $dateVal2)
{
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="file.zip"');
$fullListOfFiles = $downloadFullTmpFolder.$filesList;
$command = "sudo $ldlib -u myuser /usr/bin/python3 $downloadScriptFile -datadir $gnomeDataDir -time1 $dateVal1C -time2 $dateVal2C -outdir $downloadFullTmpFolder > debug_download.txt 2>&1";
$output = shell_exec($command);
$fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -# -9 - ', 'r');
$bufsize = 1024;
$buff = '';
while( !feof($fp) )
{
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
}
else
{
echo("<p>Dates have to be different in order for the download to start.</p>");
}
}
else
{
echo("<p>Error: Page called without submit.</p>");
}
?>
</div>
Finally, the jquery part in downloadPage.php, which if I add it doesn't work anymore (which I'd like to learn how to do right, and I mainly learned from the manual of jquery, the last example in the link)
<script>
/* attach a submit handler to the form */
$("#dateRangeID").submit(
function(event)
{
event.preventDefault();
var $form = $(this),
t1 = $form.find("input[name='datefield1']").val(),
t2 = $form.find("input[name='datefield2']").val(),
subm = $form.find("input[name='submit']").val(),
url = $form.attr('action');
var posting = $.post(url, { datefield1: t1, datefield2: t2, submit: subm} );
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content'); // <--- So this turns out to be wrong. Right is only $(data);
$("#result").empty().append(content);
});
});
</script>
What is wrong in this? Please assist. Thank you.
If you require any additional information, please ask.
Looking at the obvious, you have:
var content = $(data).find('#content');
where, you're trying to find an element with the ID content in one of the following results:
<p>Dates have to be different in order for the download to start.</p>
or
<p>Error: Page called without submit.</p>
I am trying to write a webpage for a list of files to download. The files are stored with the webpage and I want the webpage to dynamically list all the files in the folder to download. That way when more are added I don't have to modify the webpage. I know how to use JavaScript to create links on the webpage but I need to use it to find the names of the files first.
I found a website that had code for navigating files like a file browser but it only uses a string to store the current location.
This is in the header:
<script type="text/javascript"><!--
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var fileref = locarray.join("/");
//--></script>
this is in the body:
<form>
<input type=button value="Show Files" onClick="window.location=fileref;">
</form>
However this doesn't really help since I am trying to create download links to files not have a file browser.
Edit:
When you host a traditional HTML page you upload the htmlfile and any images or content for the page to what ever server you use.
I want to use javascript to dynamically link to every file hosted with the webpage.
I am trying to combine this with hosting the files in a Dropbox public folder for a simple way to make the files available.
If you want a list of files on the server you will need to use a server-side script to gather their names:
JS--
//use AJAX to get the list of files from a server-side script
$.getJSON('path/to/server-side.php', { 'get_list' : 'true' }, function (serverResponse) {
//check the response to make sure it's a success
if (serverResponse.status == 'success') {
var len = serverResponse.output.length,
out = [];
//iterate through the serverResponse variable
for (var i = 0; i < len; i++) {
//add output to the `out` variable
out.push('<li>' + serverResponse.output[i] + '</li>');
}
//place new serverResponse output into DOM
$('#my-link-container').html('<ul>' + out.join('') + '</ul>');
} else {
alert('An Error Occured');
}
});
PHP--
<?php
//check to make sure the `get_list` GET variable exists
if (isset($_GET['get_list'])) {
//open the directory you want to use for your downloads
$handle = opendir('path/to/directory');
$output = array();
//iterate through the files in this directory
while ($file = readdir($handle)) {
//only add the file to the output if it is not in a black-list
if (!in_array($file, array('.', '..', 'error_log'))) {
$output[] = $file;
}
}
if (!empty($output)) {
//if there are files found then output them as JSON
echo json_encode(array('status' => 'success', 'output' => $output));
} else {
//if no files are found then output an error msg in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
} else {
//if no `get_list` GET variable is found then output an error in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
?>
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.