I'm learning web design and have run into a difficulty that I can't figure out by myself.
I want to dynamically load a form into a using jQuery. My code looks like this:
From within the main file:
$('#left_colum').click(function(e) {
e.preventDefault();
$('#column_left').load(create_album.php);
});
create_album.php -> it contains the actual form, as well as the php script that handles it on POST. It's very basic. If I load up my_form.php by its own, it works fine. If I dynamically load it as above; the HTML works but the POST php script doesn't execute.
There is also another interesting behavior; if I click the submit button on the dynamically loaded form, it all disappears (unlike the "properly" loaded one).
I've gone through a lot of posts and tutorials, and I haven't been able to find a solution other than using iframes. It seems that people generally don't dynamically load anything other than basic HTML that doesn't have to talk back to the server. I'm new to this : P
Is there a fix or another way of doing it? Thanks!
Edit:
albums.php:
<?php
include 'init.php';
if(!logged_in()) {
header("Location: index.php");
exit();
}
?>
<h3>Albums</h3>
<?php
/*Output albums*/
$albums = get_albums();
if(empty($albums)) {
echo("You don't have any albums");
} else {
/*Changed: uploading images is now part of the albums sections*/
foreach($albums as $album) {
echo '<p><a class="album_view" id="'.$album['id'].'" href="">', $album['name'], '</a> (', $album['count'], ' images)<br/>Description: ', $album['description'], '...<br/><a class="album_edit" id="'.$album['id'].'" href="">Edit</a> / Delete / <a class="upload_image" id="'.$album['id'].'" href="">Upload</a></p>';
}
}
?>
<script type="text/javascript">
$(document).ready(function() {
/*Creating albums*/
$('#create_album').click(function(e) {
e.preventDefault();
$('#column_left').load(album.php);
});
});
create_album.php:
<h3>Create Album</h3>
<?php
if(isset($_POST["album_name"], $_POST["album_description"])) {
echo 'got here';
$album_name = $_POST["album_name"];
$album_description = $_POST["album_description"];
$errors = array();
if(empty($album_name) || empty($album_description)) {
$errors[] = "Album name and description required";
} else {
if(strlen($album_name) > 55 || strlen($album_description) > 255) {
$errors[] = "Name/description too long";
}
}
if(!empty($errors)) {
foreach($errors as $error) {
echo $error, "<br/>";
}
} else {
echo 'got here, too';
//create_album($album_name, $album_description);
//header("Location: albums.php");
}
}
?>
<form action="" method="post">
<p>Name:<br/><input type="text" name="album_name" maxlength="55"/></p>
<p>Description:</br><textarea name="album_description" rows="6" cols="35" maxlength="255"></textarea></p>
<p><input type="submit" value="Create"/></p>
</form>
I think that's:
$('#column_left').load('my_form.php');
right?
Anyways:
Is the form showing up correctly?
Try having a look at the generated source, by using firebug, in order to see if the loading was successful
Make sure that "my_form.php" returned html isn't the whole <html> but just <form> and its content
What's the form action? Is it an absolute path or not? If it is relative, it may point to different locations when called from the ajax-loading page or from my_form.php
Are you submitting the form vja ajax, or "the standard way"?
What does exactly happen when you click on form submit? Where do you get redirected?
because your form action would be to a different page so every time you click submit button it redirect you to that page , you can try using iframe it will work that way or if you want to use jquery only than paste some of your code so that we can understand what's actually happening... though iframe is the best solution for you as if now
With your code, you load only the html part of you form. So when user push submit button, your fields had sended to original page and not to "my_form.php", where I suppose you manage POST datas.
The easiest solution is to use IFRAME to load you form code.
Your form action is missing try this, i have tried and working on my end
album.php
<h3>Create Album</h3>
<?php
if(isset($_POST["album_name"], $_POST["album_description"])) {
echo 'got here';
$album_name = $_POST["album_name"];
$album_description = $_POST["album_description"];
$errors = array();
if(empty($album_name) || empty($album_description)) {
$errors[] = "Album name and description required";
} else {
if(strlen($album_name) > 55 || strlen($album_description) > 255) {
$errors[] = "Name/description too long";
}
}
if(!empty($errors)) {
foreach($errors as $error) {
echo $error, "<br/>";
}
} else {
echo 'got here, too';
//create_album($album_name, $album_description);
//header("Location: albums.php");
}
}
?>
<form action="album.php" method="post">
<p>Name:<br/><input type="text" name="album_name" maxlength="55"/></p>
<p>Description:</br><textarea name="album_description" rows="6" cols="35 "maxlength="255"></textarea></p>
<p><input type="submit" value="Create"/></p>
yourmainfile.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#create_album').click(function(e) {
e.preventDefault();
$('#column_left').load('album.php');
});
});
</script>
</head>
<body>
<div id="mainWrapper">
<div id="column_left"></div><!-- end column left -->
Create New Album
</div><!--end mainWrapper-->
</body>
</html>
Related
I have a short sample php code above:
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput"><br/>
<br/><input type="submit" name="submit" value="Check"/>
</form>
</body>
<?php
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string))
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
</HTML>
Imagine that the code is saved under file sample.php and located at localhost/sample.php.
I want to fill the form and trigger the submit button through this link:
localhost/sample.php?stringInput=abc&submit=Check
How can I do that? Thanks for help.
I need to use POST method because the actual form has many inputs not just one and I want to know how it will work with POST. And using PHP only if possible. (Javascript, jQuery are not the first choices). Cheers.
This is a good example to demonstrate what I need.
http://image.online-convert.com/convert-to-jpg?external_url=jhjhj&width=333
I tried GET method and the form doesn't display value.
If you want to include the parameters in the URL you cannot use POST
From wikipedia:
the POST request method requests that a web server accept the data enclosed in the body of the request message
Whereas in a GET request (from w3schools):
the query string is sent in the URL of a GET request
Try this:
You can assign your post values to variables & echo them in your input.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<?php
$string = "";
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string) )
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput" value="<?php echo $_REQUEST['stringInput'];?>"><br/>
<br/><input type="submit" name="submit" value="Check" />
</form>
</body>
</HTML>
You are using the wrong http method instead of POST you should use GET
"Note that the query string (name/value pairs) is sent in the URL of a
GET request"
Check more about these two methods here: POST vs GET
I'm trying to write a simple PHP web page that asks the user to input a domain and then click the SUBMIT button. When the user clicks SUBMIT the page should display the name of the domain that they typed in.
I have XAMPP installed on my computer and I have a file named test234.php in my htdocs directory. This PHP file contains the following PHP and HTML code:
<?php
$message = "";
if (!isset($domain)) {
$message = "<br>Enter a domain<br>";
} else {
$message = "You typed in $domain as the domain";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<h1 align="center">
Some title
<?php print $message ?>
</h1>
<form method="POST" align="center">
Domain: <input type="text" name="domain"><input type="submit" align="center"><br>
</form>
</body>
</html>
When I type in a domain and click SUBMIT it just reloads the same page asking for the user to type in a domain. I want it to output the text "You have typed in $domain as the domain" but can't seem to get it to work. Any help would be appreciated.
The value of $domain was never declared. If you would like to get form data you need to use the $_GET, $_POST, or $_REQUEST object(s), in your case you are using the post method in your form so instead of $domain use $_POST["domain"]:
<?php
$message = "";
$domain = $_POST["domain"];
if (!isset($domain)) {
$message = "<br>Enter a domain<br>";
} else {
$message = "You typed in $domain as the domain";
}
?>
I'm building a referral-based site and only want it to be accessed by people who enter a valid referral code. The landing page will just be a simple input box and a go button. Once they type in a correct code, they will then be redirected to a certain URL depending on what code they type in. Otherwise they will get an error message.
I have written the code all in one page using HTML and PHP.
It works as planned except for one thing... regardless of what is typed they just get redirected to the home page. Even if you type nothing you end up on the home page.
Any advice on what I'm doing wrong, or perhaps a better way would be greatly appreciated.
<?php
/*
Template Name: landingpage1
*/
?>
<?php
if (isset($_POST['suche'])) {
if ($_POST['suche'] == ‘REFERRAL3’) {
echo '<script type="text/javascript">
window.location = “MY-URL-1”
</script>';
} elseif ($_POST['suche'] == ‘REFERRAL1’) {
echo '<script type="text/javascript">
window.location = “MY-URL-2”
</script>';
} elseif ($_POST['suche'] == ‘REFERRAL2’) {
echo '<script type="text/javascript">
window.location = “MY-URL-3”
</script>';
} else {
echo 'Error: You put in the wrong code.';
}
} else {
echo '';
}
?>
<div id="page" class="page">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter referral code: <input name="suche" type="text"><br>
<input type="submit" value="Go">
</form>
</div>
Why not use php's header() function for redirect? It's mutch saver too. Beside this, your error message only show whenever $_POST['suche'] is set. You can move it just after the if, because header will redirect otherwise.
if (isset($_POST['suche'])) {
if ($_POST['suche'] == "REFERRAL3") {
header("Location: MY-URL-1");
} elseif ($_POST['suche'] == "REFERRAL1") {
header("Location: MY-URL-2");
} elseif ($_POST['suche'] == "REFERRAL2") {
header("Location: MY-URL-3");
}
echo 'Error: You put in the wrong code.';
}
Or use switch instead of many if. It's better to maintain.
if (isset($_POST['suche'])) {
switch( $_POST['suche'] ) {
case "REFERRAL1":
header("Location: MY-URL-1");
break;
case "REFERRAL2":
header("Location: MY-URL-2");
break;
case "REFERRAL3":
header("Location: MY-URL-3");
break;
default:
echo 'Error: You put in the wrong code.';
break;
}
}
In your code <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> will return index.php, Your form doesn't submitted to the same template file. It is submitted to index.php.
In order to stay on the same page on submit you just fill in action="" into the form tag.
Change
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
to
<form method="post" action="">
You can use header('Location: http://www.example.com/'); for redirect in php
just like this
if ($_POST['suche'] == ‘REFERRAL3’) {
header('Location: MY-URL-1');
}
I want to create a confirm yes/no box in php
my code like this:
<?php
if(isset($_REQUEST['id']))
{
?>
<script>
var cf=confirm("do you want to delete Y/N");
if(cf)
{ i want to call code edit of php
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name="frm" method="post" action="edit.php">
Edit <br>
Edit <br>
Edit <br>
</form>
</body>
</html>
I Want to when press Yes i call code edit in PHP
But it do not work.
Can you help me ?
Thanks you
Just use inline onclick event.
This is a simple techique, you can use it in your PHP page.
Edit
In your code, you have mentioned PHP but, have used JavaScript.
If you want to do a confirm with PHP,
Create an intermediate page for confirmation.
Post form data there.
On confirmation page, add two submit buttons:
Yes: If pressed this, redirect/post to edit page.
No: If pressed this, redirect back to form
So, your confirmation page should be:
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['confirm'])) {
if ($_POST['confirm'] == 'Yes') {
header("Location:edit.php?id=1");
}
else if ($_POST['confirm'] == 'No') {
header("goBack.php");
}
}
?>
<form method="post">
<?php
if(isset($_REQUEST['id']))
{
?>
<input type="submit" name="confirm" value="Yes"><br/>
<input type="submit" name="confirm" value="No"><br/>
<?php
}
?>
</form>
Put an id on your form:
Create an event listener for the form's onsubmit event
<script>
function onFormSubmission(e){
return confirm("do you want to delete Y/N");
}
var frm = document.getElementById('frm');
frm.addEventListener("submit", onFormSubmission);
</script>
When the user submits a form they will be prompted with your message. If they click Yes the function will return true and the form will be submitted. Otherwise the function will return false and the form submission will be cancelled
I think this is what you want to do:
<?php
//YOU MUST BE SURE THAT YOUR URL CONTAINS THE $_REQUEST['id'] PARAMETER, OTHERWISE IT WON'T WORK FROM YOUR CODE... IF YOU WANT IT TO WORK REGARDLESS OF THAT, JUST COMMENT OUT THE IF(ISSET(... BLOCK...
$editURL = "edit.php"; //EDIT URL HERE
if(isset($_REQUEST['id'])) {
//ASSIGN THE ID TO A VARIABLE FOR BUILDING THE URL LATER IN JS...
//THE DEFAULT ID IS 1 BUT YOU CAN DECIDE WITH YOUR OWN LOGIC
$defaultID = ($dID = intval(trim($_REQUEST['id']))) ? $dID : 1;
?>
<script>
function confirmEdit(evt){
evt.preventDefault();
var cf=confirm("do you want to delete Y/N");
var id=<?php echo defaultID; ?>;
if(cf){
//i want to call code edit of php
//HERE'S THE CODE YOU MAY NEED TO RUN;
if(id){
//RETURN TRUE SO THAT THE SCRIPT WITH LINK TO THE APPROPRIATE URL
return true;
// OR REDIRECT WITH JAVASCRIPT TO EDIT PAGE WITH APPROPRIATE ID
//window.location = "" + <?php echo $editURL; ?> + "?id=" + id; //YOU ALREADY HAVE THE EDIT URL... JUST APPEND THE QUERY-STRING WITH ID TO USE IN THE EDIT PAGE
// You might also just (without redirecting) return true here so to that the page continues like you just clicked on the link itself...
}
}
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<!-- THE FORM TAG IS NOT NECESSARY IN THIS CASE SINCE YOUR ANCHOR TAGS HAVE THE EXACT URL YOU WANT ASSOCIATED WITH THEM... AND YOU DON'T EVEN NEED JAVASCRIPT IN THIS CASE... BECAUSE THE HREF OF THE LINKS ARE HARD-CODED... -->
<!-- <form name="frm" method="post" action="edit.php"> -->
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-1' href="edit.php?id=1">Edit Page 1 </a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-2' href="edit.php?id=2">Edit Page 2</a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-3' href="edit.php?id=3">Edit Page 3</a> <br>
<!-- </form> -->
</body>
</html>
So, now clicking on any of the Links will Ask me to confirm if I want to delete the Resource or not. If I choose yes, then the appropriate page is loaded for the Process...
not sure if the other answers really answered your question, this was my problem too, then I experimented and here's what I came up with:
.
confirmation in php :
$Confirmation = "<script> window.confirm('Your confirmation message here');
</script>";
echo $Confirmation;
if ($Confirmation == true) {
your code goes here
}
that's all, other people might look for this, you're welcome :)
I was looking to simply have a confirmation box in php before triggering POST isset without going through javascript:
echo "<input id='send_btn' type='submit' value='previous'
name='previous' OnClick=\"return confirm('Are you sure you want to go
to previous');\" >";
This appeared for me to be the easiest solution.
I don't know if something like this has already been asked and answered, but since no matter what search query I make, nothing seems to be close to what I am looking to do. I am working on a project where the user will upload a file. Once the file has been uploaded it will show the user a success message as well as some file info. I am trying to keep this all within one page, if possible, but can't seem to get it to work. File gets uploaded, but the info does not show.
Here is something like what I am working with:
<?php
if(isset($_POST['uploadFile']) && isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], "files/" . $_FILES['file']['name']);
$message = "\"" . $_FILES['file']['name'] . "\" uploaded successfully...";
}
?>
<html>
<head>
<title>Upload File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".uploaded-file-info").hide();
$(".uploadForm").submit(function() {
$(".upload-form").hide();
$(".uploaded-file-info").show();
});
});
</script>
</head>
<body>
<div class="upload-form">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" class="uploadForm" >
<input type="file" name="file" /><br />
<input type="submit" name="uploadFile" value="Upload File" />
</form>
</div>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
</body>
</html>
Like I said, the file gets uploaded, but the form doesn't hide and the file info ($message) doesn't show. Any suggestions?
The problem is the JQuery part :
$(".uploadForm").submit(function() {
$(".upload-form").show();
$(".uploaded-file-info").show();
});
coupled with this line :
<form method="post"
The JQuery part is saying : As soon as the form on the page is submitted, Show the information DIV.
The "Form" part just say : Submit the form.
So, when you click the button, the form is submitted and at the same time, the JQuery is executed. But then the form that you just posted needs to "refresh" the page to get the response back from the server. Basically, the JQuery you wrote display your div while you submit it. Meaning that it will work for a fraction of a second but will display an empty div because the response of the server is not there yet.
What you probably want to do is something like :
When the page loads
And there is content in the uploaded-file-info
Show the info and hide the form.
Add a Style tag with the following :
<style>
.uploaded-file-info {
display: none;
}
</style>
It will always hide the uploaded-file-info when the page loads.
Then, change your JavaScript code with :
<script>
$(document).ready(function() {
if ($('.uploaded-file-info > p').html() != "") {
$(".uploaded-file-info").show();
}
});
</script>
It says that when the page loads, if something is present inside the children of the element "uploaded-file-info", then show it. Otherwise, do nothing.
An easier solution would be to display the block, with php (so on the server side), only if a file was uploaded. No need for JQuery (client side) code.
Remove all the JQuery code and code within "<style>" tags and replace surround your "div class="uploaded-file-info" with an IF like this :
<?php if ($message != '') { ?>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
<?php } ?>
Here's what will happen then:
you post (from your browser) the form
the server receives your post
if there is a file uploaded, it will initiate your "message" variable
and if the message variable exists, the server will put the "div uploaded-file-info" into the response. If not, everything surrounded by the "if" won't be put into the response.
your browser will receive the response and display it on screen.