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>
Related
I am writing a wordpress page with usage of javascript, jQuery and PHP. It generates a QRcode out of passed values to the page. After it is generated, I extract an src of a QRcode which is in data:image/png;base64 format. The problem is in passing this string to PHP without using any methods. I need it to form a HTML formated email, which is sent when page is loaded. I am not familiar with AJAX, but I know that there is a URL() method, which can pass values to the PHP functions?
Here is a code I wrote (yes, it is redundant and untidy...):
Be sure to save it onto your device and show it when you arrive!
<div id="qrcode"></div>
<form method="post">
<input type="text" name="image" id="image"></input>
<input type="submit" value="Send to e-mail"></input>
</form>
[gravityform id="3" title="false" description="false"] //Hidden form with values for QRcode
<script type="text/javascript" src="http://yourjavascript.com/10124121272/qrcode.js"></script>
<script>
var email = document.getElementById("input_3_1").value;
var date = document.getElementById("input_3_2").value;
var type = document.getElementById("input_3_3").value;
var id = document.getElementById("input_3_4").value;
var qrcode = new QRCode("qrcode", {
text: "Email of buyer: "+email+"; Type of an offer: "+type+"; Date of purchase: "+date+"; ID: "+id,
width: 256,
height: 256,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
jQuery(document).ready(function( $ ) {
var image = jQuery('img[alt="Scan me!"]').attr('src');
jQuery('#image').val(image);
});
</script>
[insert_php]
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$to = $_GET[email];
$image = Some magical approach to get base64 image from form name="image"
$subject = 'Subject of an email';
$message = '<html><head><body>
<h1>Hello! Here is your QRcode!</h1>
<img src=$image />
</body></head><html>'
wp_mail( $to, $subject, $message );
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
[/insert_php]
The problem is in passing this string to PHP without using any methods.
The method/verb is a key part of an HTTP request which is required if you want to send data to your PHP script. You must make an HTTP request of some sort.
You can easily use AJAX to get your data to your script.
$.post(
'/yourScript.php'
qrCodeStringData
'text/plain'
).then(function () {
// Do something if successful
}).catch(function () {
// Do something if failure
});
Also, I get the impression that you're inventing your own data format in that QR code. I recommend using JSON so you don't have to worry about structuring your data. (What if someone sticks a semicolon in your data? Suddenly your format is unusable. Using a well known format like JSON means you don't have to deal with it.)
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.
I have button which in enclosed by <a> tag. When clicked, it executes redirect.php script.
login.php - contains
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
redirect.php contains twitter authentication code. If authenticated successfully then gives id and name. I want to fetch these both value in index.php
Using ob_start(); I can receive values from php script to JS function via json.
But I am confused about how to manage the code in index.php to execute script on button click and receiving these two value also.
redirect.php
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$notweets = 5;
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$id = $content->{'id'};
$name = $content->{'name'};
?>
Please let me know if you need further explaination.
Bottomline:
Rather executing redirect.php script on link click, I want it to execute via function on button click event.
Getting id and name from redirect.php to index.php after redirect script executed
I already have session_start() to manage the twitter session. So dont want to mess up using mutiple session if not necessary ..
UPDATE after david's answer
<body>
<input type="button" value="Run somePHPfile.php" id = "b1" />
<script>
$('#b1').click(function () {
window.location.href = 'redirect.php';
$.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed
// data.id is the id
var id= data.id;
var name = data.name;
alert(name);
});
});
</script>
</body>
Apologize to say:
On button click redirect.php script executed. redirect.php includes other files, which finally reach to index.php. And index.php returns name and id.
So is this enough to manage it : $.get('index.php', function(data) { ... }
To bind to a click event of an HTML button, you would use JavaScript. Since you tagged the question with jQuery, I'll assume its use. The event handler would look something like this:
$('#loginButton2').click(function () {
window.location.href = 'redirect.php';
});
Note: This simulates an anchor click effectively. If you instead want to more closely resemble an HTTP redirect, you might want to use this instead:
window.location.replace('redirect.php');
As for the id and name values, how exactly does this flow return the user to index.php in the first place? Your redirect.php has, well, a redirect (though not all code paths result in that) so it kind of assumes non-AJAX interaction. (I think XHR follows redirects sometimes, but the behavior is different from one browser to another.)
If the redirect isn't terribly important and you just want to make an AJAX call to redirect.php, then you can do that with a simple AJAX request:
$.get('redirect.php');
In order to get those values back to the page, they'll need to be emitted from redirect.php. Something like this:
echo json_encode((object) array('id' => $id, 'name' => $name));
Then in the client-side code you would have those values available in the AJAX callback:
$.get('redirect.php', function(data) {
// data.id is the id
// data.name is the name
// use these values client-side however you need
});
<script>
$("#loginButton2").on('click',function(){
window.location.href="redirect.php";
});
</script>
and in redirect.php file
$_SESSION['id']=$id ;
$_SESSION['name']=$name;
and also
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
to
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
How can I dynamically post data to an iframe in Jquery.
I really need to post data to an Iframe in this case, I cannot use a $.POST because data received is returned sequentially (buffered)
If you have a workaround to make jquery handle data returned by a $.POST 'when it receives the data. I'm very curious!
At the moment I handle it with GETS this way:
var iframe = $('<iframe style="display:none;"></iframe>');
$( "body" ).append(iframe);
iframe.attr('src','server.php?type=getFolders&inode='+nodeData.inode).load(function(){$(this).remove()});
This basically creates a temporary iframe and lets the php inject javascript in it (using ob_flush();flush(); )while it is returning data, then when it's finished, it simply removes the iframe to clean up.
from within the iframe, I access the main frame with window.parent. then the mainframe's methods.
this is ideal but works with GET, how can I make this work with POST ?
This function creates a temporary form, then send data using jQuery :
function postToIframe(data,url,target){
$('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
$.each(data,function(n,v){
$('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
});
$('#postToIframe').submit().remove();
}
target is the 'name' attr of the target iFrame, and data is a JS object :
data={last_name:'Smith',first_name:'John'}
Ok, so as this apparently doesn't exist, I created my own solution. Sharing it here in case anybody wants to POST to an iFrame in jQuery.
the js function/ class-like:
function iframeform(url)
{
var object = this;
object.time = new Date().getTime();
object.form = $('<form action="'+url+'" target="iframe'+object.time+'" method="post" style="display:none;" id="form'+object.time+'" name="form'+object.time+'"></form>');
object.addParameter = function(parameter,value)
{
$("<input type='hidden' />")
.attr("name", parameter)
.attr("value", value)
.appendTo(object.form);
}
object.send = function()
{
var iframe = $('<iframe data-time="'+object.time+'" style="display:none;" id="iframe'+object.time+'"></iframe>');
$( "body" ).append(iframe);
$( "body" ).append(object.form);
object.form.submit();
iframe.load(function(){ $('#form'+$(this).data('time')).remove(); $(this).remove(); });
}
}
then when you need to send a form to a temporary iframe :
var dummy = new iframeform('server.php');
dummy.addParameter('type','test');
dummy.addParameter('message','Works...');
dummy.send();
This is the server.php example file :
if($_POST[type] == 'test')
{
header( 'Content-type: text/html; charset=utf-8' );
echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>';
echo str_pad('',4096); //fill browser buffer
for($i = 0; $i < 10; $i++)
{
echo '<script type="text/javascript">window.parent.console.log(\''.$_POST[message].'\');</script>';
ob_flush(); flush();
usleep(350000);
}
}
And the result is as expected:
the main frame's console outputs the string 'Works...' every 350ms starting immediately, even if the php is still running.
When the php is finished sending the chunks, it simply removes the temporary form and the temporary iframe.
Either you can use target method or use AJAX for the above work
<form action="..." target="an_iframe" type="post">
<input type="text" name="cmd" placeholder="type a command here..." />
<input type="submit" value="Run!" />
</form>
<iframe id="an_iframe"></iframe>
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.