I am using JQuery to test the size of an input after submitting a form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page 1</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form method="post" action="essai.php">
<input type="text" name="mail" id="email" placeholder="mail"/><br />
<input type="submit" name="submit" value="Validate" />
</form>
<?php
if (isset($_POST['submit'])){
echo($_POST['mail']);
if(isset($_POST['mail'])){
$data=789;
}
}
?>
<script>
$(function(){
var data = <?php echo json_encode($data); ?>;
$("form").on("submit", function() {
if(data.toString().length < 4) {
alert(data);
return false;
}
});
});
</script>
</body>
</html>
The problem is that the alert (if I enter only 1 caracter for instance) does not pop up after the 1st submitting but only after the others.
Thank you
First, it's terribly insecure to embed PHP code within JavaScript. I can't think of one reason why you will want to use server-side code on the client-side. As an alternative, echo the javascript code from PHP, not the other way round.
Now your problem comes up because the first time the page is loaded, nothing is posted. You have some chunk of code which executes only after something gets posted. If your PHP script can display errors, you will see an undefined variable notice thrown the first time you load the code. You can work around that by declaring the variable before using it in the condition:
$data = 0; // Initialize variable here
if (isset($_POST['submit'])){
echo($_POST['mail']);
if(isset($_POST['mail'])){
$data=789;
}
}
Related
I want to ask,, how to call sweet alert in process.php?
example if in html:
<!DOCTYPE html>
<html>
<head>
<title>Sweet Alert</title>
<link rel="stylesheet" type="text/css" href="plugins/sweetalert/sweetalert.css">
<script type="text/javascript" src="plugins/sweetalert/sweetalert.min.js"></script>
</head>
<body>
<button onclick="sweet()">Sweet Alert</button>
<script>
function sweet (){
swal("Good job!");
}
</script>
</body>
</html>
Well, how if placed in process.php?
Example there are 2 fields:
tes.php :
<form method="post" action="proses.php">
<label>NIK</label><br>
<input type="text" name="nik"><br>
<label>Confirm NIK</label><br>
<input type="text" name="confirmnik"><br><br>
<button type="submit" name="submit">Cek</button>
</form>
process.php :
<?php
$nik = $_POST['nik'];
$confirmnik = $_POST['confirmnik'];
if ($nik<>$confirmnik)
{
echo "<script language='javascript'>alert('nik and confirm nik do not match !');window.history.back();</script>";
}
else
{
echo "<script language='javascript'>alert('ok');window.history.back();</script>";
}
?>
result :
How to change javascript default alerts by using sweet alerts in process.php file?
You should be able to seamlessly replace alert with swal.
Your only issue is going to be calling the window.history.back function. You need to put it in a callback as sweet alert does not block the thread like alert does.
You can use promises for that:
So your JS code would look something like:
swal('nik and confirm nik do not match !').then(() => {window.history.back()});
And the full PHP code would look like:
<?php
$nik = $_POST['nik'];
$confirmnik = $_POST['confirmnik'];
if ($nik<>$confirmnik)
{
echo "<script language='javascript'>swal('nik and confirm nik do not match !').then(() => { window.history.back(); });</script>";
}
else
{
echo "<script language='javascript'>swal('ok').then(() => { window.history.back(); });</script>";
}
?>
I am trying to bring up a javascript alert with my variables from php. My upload.php file so far is:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+')');
</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
I then have my html code which looks like (only the relevant part included):
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
The purpose of this script is to upload a picture to a server and then display the markdown code for the user to use that image. I am aiming to output the following if the file uploads correctly:
![Alternative Text](http://www.example.com/folder/photo.jpg)
I have tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in a working webpage that uploads the file but does not show the js alert.
I have also tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+folder+'/'+pic+')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in an http error 500
Any advice?
Many thanks,
You can create a function in php and call it where ever you need to call alert.
Function :
function alertMsg($str) {
print("<script>alert('$str')</script>");
}
And call in php as
//string
alertMsg("Success");
//php variable
$alertMsg = "Some alert message";
alertMsg($alertMsg);
//even you can concatenate both
alertMsg("This is an alert. ".$alertMsg);
Hope this helps.
Thanks.
In both attempts you're trying to mix PHP, HTML, and JavaScript as though they were all the same language. They are not. From the perspective of any one of them, code in another one of them is nothing but a string. They can't directly share variables and logic.
See how this line:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');
is attempting to use PHP code (both the variables and the syntax) directly in JavaScript. This is simply resulting in syntax errors in your JavaScript, which your browser's development console is pointing out to you. Instead, enclose the PHP code in <?php ?> tags and echo the result:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+'<?php echo $folder.'/'.$pic ?>'+')');
The second attempt has the same problem, you're putting HTML/JavaScript directly in your PHP:
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
This is resulting in PHP syntax errors, which your PHP logs are telling you about (as well as the 500 Internal Server Error you're getting).
PHP code needs to be in <?php ?> tags. Always. So this would be something like:
$folder="uploaded_files/";
?>
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
<?php
if(move_uploaded_file($pic_loc,$folder.$pic))
Note also that in HTML/JavaScript you don't need a <script> tag for every line of JavaScript code. You can have multiple lines of code in a single <script> element.
Using variable PHP in JS
<?php
if (isset($_POST['btn-upload'])) {
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder = "uploaded_files";
if (move_uploaded_file($pic_loc, $folder . '/' . $pic)) { ?>
<script>
alert("File successfully uploaded! " +
"\n" +
location.hostname +
"<?php echo '/' . $folder . '/' . $pic; ?>");
</script>
<?php
} else { ?>
<script>alert("Sorry, error while uploading file. Please try again");</script>
<?php
}
}
?>
location.hostname = $_SERVER['HTTP_HOST'] // localhost
I am learning jquery.ajax but I cant understand something
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
var cacat = $("#nam").val();
$("#stage").load('/jquery/result.php', {"name":cacat} );
alert(cacat);
});
});
</script>
</head>
<body>
<p>Enter your name and click on the button:</p>
<input type="input" id="nam" size="40" /><br />
<div id="stage" style="background-color:blue;">
STAGE
</div>
<input type="button" id="driver" value="Show Result" />
</body>
</html>
and here is the Php FIle
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
I don't understand what is this $("#stage").load('/jquery/result.php',{"name":cacat});
because it's also working with $("#stage").load('result.php', cacat );
So here comes the question:
What's the difference between {"name":cacat} and cacat? Also both scripts do the same thing, the jQuery gets the value of the input and the PHP also gets the value of the input, why so?
The difference is that the first one sends a JSON object which gets to $_REQUEST whereas the other one sends the value, without the JSON form.
I am trying to use jQuery/AJAX to run a PHP file on a server. This PHP simply adds a row with some constants to a database. Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit Application</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("http://.../submitApp.php");
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="javascript:doSomething()">
<p>
<label for="programName"></label>
<input type="text" name="programName" id="programName" />
</p>
<p>
<label for="greQuant"></label>
<input type="text" name="greQuant" id="greQuant" />
</p>
<p>
<label for="greVerbal"></label>
<input type="text" name="greVerbal" id="greVerbal" />
</p>
<p>
<input type="submit" name="submitApp" id="submitApp" value="Submit" />
</p>
</form>
</body>
</html>
Upon pressing the submit button on the above form, nothing seems to happen. I should mention I am running this locally via DreamWeaver. I know for a fact that the code is reaching the JavaScript method and that the PHP code is functional. Anyone know what's wrong?
Use POST instead of GET to do this work.
function doSomething() {
var programName = $('#programName').val();
var greQuant = $('#greQuant').val();
var greVerbal = $('#greVerbal').val();
$.ajax({
type: "POST",
url: "submitApp.php", //URL that you call
data: { programName: programName, greQuant:greQuant, greVerbal:greVerbal } //var in post: var from js
}).done(function(msg) {
alert(msg);//change to something to indicate action
}
});
and with your php, handle like this
<?php
$programName = $_POST['programName'];
$greQuant = $_POST['greQuant'];
$greVerbal = $_POST['greVerbal'];
//do something important
?>
this is just a simple example, you need apply some security to this php code
I am trying to get the user to put something into the text area and the output should be what he wrote repeapiting x amount of times, but I get an error "document.forme is undefined".
Can you please help me understand why it is undefined?
My code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>input home work</title>
<script type="text/javascript">
var help= document.forme.tryout.value;
for (x=1; x<=10;x++){
function numberCheak (){
document.write("this is"+" "+help++);
}
}
</script>
</head>
<body>
<form name="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onClick="numberCheak();"/>
</form>
</body>
</html>
Ok, you have a few problems. The first is that you are trying to access a form element that doesn't exist yet: the script is above the form element, so the form doesn't exist when you try to get it. If you move the script to the bottom of the page it will work better.
Second, the loop should be inside the function, not wrapped around the function.
Third, document.write has weird side effects and causes the document to be rewritten and will stop the script from continuing correctly.
Here's my revised script
function numberCheak() {
var help = document.forme.tryout.value;
for (var x = 1; x <= 10; x++) {
document.getElementById("output").innerHTML += help;
}
}
and the HTML form that goes with it
<form name="forme" id="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onclick="numberCheak();" />
<span id="output"></span>
</form>
You can see it in action on jsFiddle.
Forms are stored in collection and can be accessed like this:
var form = document.forms[i];
or
var form = document.forms[name];
In your case, i is 0 and name is forme.