Ok so say I have the following pages.
index.php
<form action="create_file.php" method="get">
<input type="number" name="num_lines">
<button type="submit">Download File</button>
<form>
create_file.php
<?php
$num_lines = $_GET['num_lines'];
//create a file with $num_lines lines
?>
How would I be able to:
1.) Create a text file with $num_lines lines and serve it to the user
2.) Send a jquery alert to the user to say the download was successful. Ideally the message would be created by create_file.php.
All while staying on index.php?
you can use ajax. please check below link that will alert text which dies in the create_file.php .. check it once
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="get">
<input type="number" id="numLines" name="num_lines">
<button id="button" type="button">Download File</button>
<form>
<script>
$(document).on('click','#button',function(){
var val=$('#numLines').val();
$.post('create_file.php',{val:val},function(r){
alert(r)
});
});
</script>
create_file.php
<?php
$num_lines = $_GET['num_lines'];
die($num_lines);
?>
Client-side approach:
http://jsfiddle.net/uselesscode/qm5ag/
Or, you could do something like:
<?php
$num_lines = $_GET['num_lines'];
$ext = '.txt';
$tmpfname = tempnam("./", "numLines_");
if (file_exists($tmpfname)) {
unlink($tmpfname);
file_put_contents($tmpfname . $ext, $num_lines);
echo json_encode(array('fileUrl' => basename($tmpfname) . $ext));
} else {
echo 'err';
}
?>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function(){
$.get('create_file.php', {'num_lines': 42}, function(res){
var response = $.parseJSON(res)
if(typeof response =='object') {
var downloadableFileLink = $('<a></a>').attr('href', response.fileUrl).html("Click here to your file, yo.")
$('#downloadTheRapper').append(downloadableFileLink)
console.log('Oh snap.')
} else {
console.log('err')
}
});
});
</script>
</head>
<body>
<div id="downloadTheRapper"></div>
</body>
</html>
Related
When the user submits the form, the result should be displayed without page refreshing. The PHP script is also in the same HTML page.
What is wrong withe $.post jQuery?
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btn").click(function(event) {
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $("#testform").serialize()
);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform">
<!-- $_SERVER['PHP_SELF'] array -->
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
You need to use event.preventDefault in your javascript
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $( "#testform" ).serialize()
);
});
Yes, you need e.preventDefault. Also, I think these var myname and myage variables are unnecessary since you're serializing the entire form in $.post.
Try this:
$(document).ready(function() {
$("#btn").click(function(e) {
e.preventDefault();
$.post(
"23.php", $("#testform").serialize()
);
});
});
Hope this helps.
Peace! xD
This is my finalized complete code after following your all suggestions. But it is still refreshing when getting results. Let's see if I have made any further error in the code. Thanks for your all helps.
UPDATE! - All these HTML and PHP scripts resides in the same file called 23.php
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform"> <!-- $_SERVER['PHP_SELF'] array -->
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
<input type="submit" name="submit" id="btn"/>
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { //was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
I have a HTML form which reads some data and saves in the text file with help of PHP. The form's HTML code looks like below.
What is happening now:
1. once i click on submit button it redirects to the 'myprocessing.php'
2. successfully saving in data.txt
The help i required on
1. when i click on submit it shouldn't redirect me to the php page, it should stay on the HTML form page
2. it should show the php file's output on the same HTML page
In simple words, I want to stay on the HTML page itself. Since I'm pretty new to HTML and PHP, struggling much to do these. Thanks in advance :-)
<html>
<head>
<title></title>
</head>
<body>
<form action="myprocessing.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
This is my data prcoessing PHP file.
<?php
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
?>
Try below. Call refresh_div() on button click :-
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'YOUR PHP page url',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
</script>
Write php code in same html file and use isset() function to check for $_POST data
Try this
<?php
if(isset($_POST['field1']) && isset($_POST['field2']))
{
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="current_page.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST" name="testForm" id="testForm">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
<div class="result"></div>
</body>
</html>
add the name and id for form tag. if you keep action as blank, it will submit your form to current page itself.
You need a ajax call to perform as per your requirement.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$( "#testForm" ).on( "submit", function( event )
{
$.ajax({
url:'myprocessing.php',
type:'POST',
data: $("#testForm").serialize()
success:function(results) {
jQuery(".result").html(results);
}
});
return false;
});
</script>
Dont forget to put a return false at the end. If we dont put return false, it will submit your form after the ajax call.
I want to upload multiple files and have a file called test.php with this code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.8.0.min.js"></script>
<script>
$(function(){
var myVar;
$('form').submit(function(){
myVar = setInterval(ajax, 1000);
});
var ajax = function() {
$.ajax({
url: 'test2.php',
type: 'post',
success: function(ajax_result){
$('.result').html(ajax_result);
if (!ajax_result) {
clearInterval(myVar);
}
},
error: function(){
alert('error');
}
});
};
});
</script>
</head>
<body style="width:100%; height:100%;">
<form action="test2.php" target="iframe" method="post" enctype="multipart/form-data" >
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="fil" />
<input name="file[]" type="file" multiple />
<input type="submit">
</form>
<iframe id="iframe" name="iframe"></iframe>
<div class="result" style="width:100%; height:100%;"></div>
</body>
</html>
and a file called test2.php with this code:
<?php
session_start();
if (isset($_FILES['file'])){
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
move_uploaded_file($_FILES['file']['tmp_name'][$i],'a/'.$_FILES['file']['name'][$i]);
}
}
if (isset($_SESSION[$key = ini_get("session.upload_progress.prefix") . 'fil'])) {
var_dump($_SESSION[$key]);
} else echo false;
?>
Now I want before sending files to server to detect the number of files selected via their names in the client side.
How can I do this?
$('form').submit(function() {
var numberOfFilesAboutToBeSubmitted = $("[name='file[]']", this ).prop("files").length;
});
Note that you are not submitting any files with your ajax request, it has no association with your form at all.
Also note that this doesn't work in IE < 10
The following codes are HTML and php code. I want if submit button is pressed than execute practice.php file(make test.txt file). But if I pressed the button php doesn't make file. Anyone know about this??
<HTML>
<HEAD>
</HEAD>
<BODY onLoad="tid=setInterval('refresh()',1000);">
<div id="outputDiv"></div>
<form method=post action="practice.php">
<script language="JavaScript">
function refresh()
{
var HTML = "";
HTML += "<input type=submit value=makefile>";
document.getElementById("outputDiv").innerHTML = HTML;
}
</script>
</form>
</BODY>
</HTML>
<html>
<head><meta http-equiv="Content-Type" content="text/html" charset="utf-8">
</head>
<body>
<?
$fp = fopen("test.txt", "w") or die("cannot open file");
$data = "!!!!!!!!!!!!!!!!!!!";
fwrite($fp, $data);
fclose($fp);
echo "!!!!!!!!!!!!!!!";
?>
</body>
</html>
Use "a" flag, If file is not there it will automatically be created.
$fp = fopen("test.txt", "a")
Use JQuery, It would be simple.
<input type="submit" value="Load file" id="button"/>
<script>
//If document is ready.
$(document).ready(function(){
//If button is clicked.
$("#button").click(function(){
//Load a file in "outputdiv" div.
$("#outputDiv").load("test.txt");
//Assuming you are trying to refresh div after 1000 ms sec, Therefor:
setInterval(function(){
$("#outputDiv").load("test.txt");
},1000);
});
});
</script>
You must put the submit button inside the form element. The script puts the submit button inside the <div id="outputDiv"></div> element which is outside of the form element. When you press submit the browser does not know which form to submit.
For example this would work better:
<HTML>
<HEAD>
</HEAD>
<BODY onLoad="tid=setInterval('refresh()',1000);">
<form method=post action="practice.php" id="form">
<script language="JavaScript">
function refresh()
{
var HTML = "";
HTML += "<input type=submit value=makefile>";
document.getElementById("form").innerHTML += HTML;
}
</script>
</form>
</BODY>
</HTML>
I have a problem with my very simple chat. The page is constanly refreshing with AJAX with an timeout of 750ms. If I press or use enter to submit my 'reaction', the page refreshes: is there an way to remove that, so that you can instantly see what you've posted?
You can see the chat at my website: chat
The code:
Index.php
<!DOCTYPE HTML>
<?php include 'config.php'; ?>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.js">
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
</script>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
enter code here
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="text" value="" name="username" />
<input type="submit" value="verstuur" name="submit" onKeyPress="return submitenter(this,event)" />
</form>
<?php include 'send.php'; ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 750 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
chat.php
<?php
include 'config.php';
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
send.php
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
if my question is not clear say it please.
And is there a topic/question/post about good spacing? google translated it as "indent".
Thanks
Replace
<form method="post">
With
<form onsubmit="event.preventDefault()" method="post">
You may also use your callback function here like:
<form onsubmit="event.preventDefault();return submitenter(this,event);" method="post">
Working demo: http://jsfiddle.net/usmanhalalit/5RCwF/2/
Add e.preventDefault(); in JS.
Your desired action is to prevent the onSubmit action as the other answers have mentioned. Currently your script isn't quite ready to block submit as you don't have an ajax post method.
You need ajax functionality for the submission side of the application still. For this you can use jQuery post().
You want to create something like
function send() {
$.post(); // Fill in appropriate post() code.
return false;
}
And then call it from your event handlers like onsubmit="return send()" and in place of myfield.form.submit() in your keypress handler.