I'm using php to generate an html page that displays blog/thread items, and I am using javascript to show/hide some of the details. The problem is that I am generating unique IDs for each set of hidden content, which contains a form to process the input. In processing the form, I need to know which blog item was edited - I want to use $_POST. I'm pretty new to javascript, and I'm thinking that there is probably a solution I can use there.
I want the post to save the text to the mysql database (so call one of my php functions that I have working) and tell me what the text was and what the threadId is.
Here is the php code snipet, where $threadDetailItem is an array that has my thread data in it.
foreach ($threadData as $threadDetailItem)
{
// display main line (a bunch of code here ...)
// append button to edit or delete the post for admin
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// edit link opens content, and delete pops up a confirmation box
$el = sprintf ("editThreadLink_%d", $threadDetailItem['blogThreadId']);
$ec = sprintf ("editThreadContent_%d", $threadDetailItem['blogThreadId']);
$link1 = sprintf ("<a id=\"%s\" href=\"javascript:toggle('%s', '%s');\">+</a>", $el, $ec, $el);
$msg .= sprintf ("<li id=\"field6\">%s</li>\n", $link1);
}
$msg .= "</ul>\n";
echo $msg;
// now that the row is printed, lets add the hidden content if admin so they can edit
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// hidden content to enable editing of the posting
$msg = sprintf ("<div id=\"%s\" style=\"display: none\">\n", $ec);
echo $msg;
echo "<form name=\"form\" method=\"post\" action=\"\">\n";
$msg = sprintf ("<textarea id=\"%s\" name=\"%s\">%s</textarea>\n",
$ec, $ec, $threadDetailItem['threadTitle']);
echo $msg;
$msg = sprintf ("<button type=\"submit\"> %s</button>\n", $lang->get('BLOG POST'));
echo $msg;
echo "</form>\n";
echo "</div>";
}
}
Suggestions on good ways to handle this event are much appreciated. Thanks in advance.
The fields in the data are: blogThreadId, threadTitle, username, createdOn, lastUpdated, displayed (not used) and threadDetails (array containing the posting information).
I was able to use $_POST along w/ the ID in a hidden field to enable my php scripts to know which thread was being edited. It is working
Related
I have five unique forms each on a page of HTML. They then go to a PHP file to send the e-mail of data. Next they go to the HTML thank you page. I am hoping to change the heading according to which form they just submitted.
For example, if they submit a review, the should read "Thank you for your review" etc.
Technically all of these are saved as php files but only the e-mail page has php items.
Like <?php echo("<p>". $mail->getMessage()."</p>"); ?>
You should redirect to another php file and pass a parameter on url. Example:
sendemail.php
<?php
/** After send the email, check what kind form is (I don't know how do you check this).
This example is just to show you: */
if ($formType == 'review') {
$type = 'review';
} else if ($formType == 'anothertype') {
$type = 'anothertype';
}
header('Location: /thankspage.php?type=' . $type);
?>
thankspage.php
<?php
$type = $_GET['type'];
if ($type == 'review') {
echo '<h1>Thanks for your review</h1>';
} else if($type == 'anothertype') {
echo '<h1>Thanks for your anothertype</h1>';
}
?>
One way put a hidden field in your forms that'll get passed with the other form data. Then put an if statement on the thank you page and echo the appropriate message.
However, that'll only work either if you change the thank you page to php or change the page that receives and processes the form data to echo the thank you message as well
I have made an ordering system that right now goes from the product form to a review page. I have the page set up to use PHP loops to show what products they selected form the prior page and it works great. Now I need to have a "order" button that emails the order on. I the practice of writing less code, I would like to not have to re write all the code to email this form on another php form. Is there a way to have email headers on this page and dump the generated html into the body of the email to send?
Here is how I loop the form contents from the previous page. Basically it goes though all the products and if its there, show them on the review. If not, dont.
for ($i=0; $i<8; $i++) {
if (!empty($_REQUEST['driver'][$i]['select'])) {
//add the club to the total of clubs
$club = $_REQUEST['driver'][$i]['select'];
array_push($club_total, $club);
//add the price to the cost
list($shaft, $price) = explode(":", $_REQUEST['driver'][$i]['shaft']);
array_push($cost, $price);
//show the user
echo '<h3>' .$_POST['driver'][$i]['name']. ' - $'. money_format('%i', $price).'</h3>';
echo '<ul>';
if (!empty($_REQUEST['driver'][$i]['left'])) {
echo '<li><strong>Left Handed</strong></li>';
}
echo '<li>Length: '.$_POST['driver'][$i]['length']. '"</li>';
echo '<li>Shaft: '.$shaft. '</li>';
if (!empty($_REQUEST['driver'][$i]['hossel'])) {
echo '<li>Purist Hossel: ' .$_POST['driver'][$i]['hossel'].'</li>';
}
if (!empty($_REQUEST['driver'][$i]['color'])) {
echo '<li>Purist Color: ' .$_POST['driver'][$i]['color'].'</li>';
}
echo '</ul>';
}
You could capture your html in the output buffer, then store it in a variable for later use (as in, putting it into the body of an email).
ob_start();
for ($i=0; $i<8; $i++) {
// ... your code
}
$my_html = ob_get_contents();
ob_end_clean();
then put $my_html as your email body and send it along.
The idea of putting it all in a variable the first time around also works, but this might save you some effort of rewriting everything.
Instead of echoing out the html, build up a string, so $out .= "your html" etc, then you can easily set that lump of html to the body of the email function.
I am assuming you know how to code that, else I'll add code example for you.
I have a page which allows the user to "create a topic", open submitting this the form goes to another through a verification process which inserts the topic into the database and re-directs to back to the main page. However I want my verification page "add topic" to display an error message if all fields are not filled in. here is a my code, please can you tell me where I would need to add this validation code to notify the user to fill all fields:
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['name'];
$email=$_POST['email'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, email, datetime)VALUES('$topic', '$detail', '$name', '$email', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
My suggestion would be create a separate php file called validation and inside the validation file add a function. Of course you can create this function inside the same php file. If you made the separate use an include statement to place it on your page. Also a quick post-back to itself would be good since you could easily be able to get access to the posted variables and already be on the page to show errors. Otherwise you would have to return the Errors in a get, post or session. If everything was successful you could post or redirect right after the postback (maybe to a success page) and the user would only see the postback if errors present.
include_once("Validation.php");
as shown above.
validateNewTopic($topic, $detail, $name, $email, $datetime)
{
}
Then inside you could use if statements to check conditions. If you want a quick solution you can create a variable to hold all the errors.
$Error = "<p class='errors'">;
if ($topic == "")
{
$Error+="topic is required";
}
if ($Error != "<p class='errors'">)
{
return $Error +"</p>";
}
else
{
return "";
}
Since you are posting the values you can catch them in a variable on postback to validate.
$topic = $POST['topic'];
$Error=validateNewTopic($topic);
if ($Error != "")
{
?>
echo $Error
<?php
}
else {
//run sql code and show success
}
By putting the paragraph tags inside the $Error messages we can just echo and it will already be in the paragraph tag with the class errors. You can make it prettier by using an un-ordered list and when adding an error using list items. I'm not sure how familiar you are with php but at anytime you can stop writing php code by closing the tags. (< php ?> and reopen < ? php) as shown above in the if statement. I know this was not 100% clear but this is something you should try/research and practice since it is used so often. Good luck!
You can send the error to the main page by using php GET request, and then display it.
I can't think of an easy way to explain what I'm trying to accomplish..
Inserting data into MySQL using php is simple, yet I need to be able to give users the option to add more text inputs in one form...
Just for example purpose...
Users can create a shopping list, the page loads with 15 inputs for 15 items they wish to insert into their shopping list...
At the bottom, they can have the option to add another item, and when clicked, it will show an additional text input..
I've looked for examples but off the top of my head I can't think of any...
if(isset($_POST['createList']){
$item=addslashes(strip_tags($_POST['item']));
}
mysqli_query("INSERT INTO shoppingLists (id,itemName) VALUES (``,`$item`)");
How do insert multiple items with a simple POST?
I was hoping it's possible to use JQuery to add additional input fields.. but how is something like this accomplished on the PHP side?
I do hope I've explained this well enough haha.
You can use an array for your input name attribute
<input type="text" name="item[]" />
And you can browse it by looping through your variable $_POST['item'], that now contains an array with an entry for each field in your form.
I use jQuery .clone() for this.
html:
<div id=="ShoppingList">
<input class="item" name="item[]" />
<input type="button" onclick="addAnotherItem()" />
</div>
js:
function addAnotherItem(){
$("#ShoppingList input.item:first").clone().val("").appendTo("#ShoppingList");
}
I use .val("") so that whatever value the first input has isn't copied to the new one.
Sample Code For This inserting multiple images
if(isset($_POST['addSpace'])){
$spaceTitle = mysql_real_escape_string($_POST['title']);
$spaceBody = mysql_real_escape_string($_POST['text']);
if($_FILES['SliderImage']['tmp_name'] != "" ){
if (($_FILES["SliderImage"]["type"] == "image/jpeg")
&& ($_FILES["SliderImage"]["size"] < 2000000))
{
if ($_FILES["SliderImage"]["error"] > 0)
{
echo "<div class='error_box'><p>Error :: " . $_FILES["SliderImage"]["error"] . ".</p></div>'";
}else{
$path = "../images/prisma-img/demo/services/";
$path2 = "images/prisma-img/demo/services/";
$num = mt_rand();
if (file_exists($path . $num.".jpg" ))
{
echo "<div class='error_box'>"."(".$num .")".
" already exists. "."</div>";
}else{
if(move_uploaded_file($_FILES["SliderImage"]["tmp_name"],$path . $num.".jpg" )){
$mysqlPath = $path2. $num.".jpg" ;
$result = $db->insert("pages","pageTitle, pageImage, pageBody, pageSlug ", "'$spaceTitle','$mysqlPath','$spaceBody','services'");
if($db->affected_rows()){
$id=mysql_insert_id();
echo '<div class="valid_box"><p>Success :: Services successfully Added.</p></div>';
echo "<meta http-equiv='refresh' content='1; url= add-services-slide.php?id=".$id."' />";
}
}
}
}
}else{
echo '<div class="error_box"><p>Error :: Only JPEG file allowed.</p></div>';
}
}
}
?>
Hope that this will help u.
I have a situation where a user fills out 1 of 2 forms on a registration page and is sent to a software download page. If they sign up as a new user, form is processed inserted into a MySQL database and they go to the page no problem.
Here is my issue. If they are a returning user and enter a license key, the processor script checks to see if its valid against the database and if it is it sends them to the software download page. If it is NOT a valid license key (heres what I dont like) the screen goes to the url of the script, page is white, an alert pops down telling them its not a valid license key and they are returned to the registration page to try again. I hate this. I need to figure out a way to either pop the alert on the registration page w/o leaving it or better yet display some kind of message on the page. One drawback is that the script is and always will be on a different server than my forms. Ive tried curl and had success with other situations but can't close the MySQL connection on this one. Is there another way to achieve some semblance of "cross domain AJAX" I would really like it to not go to the script url/white page/alert then return them. I would like it to happen all on one page. Here is that part of my script:
if ($_POST['license_code'] != "")
{
$result = mysql_query("(//mysql stuff here)");
if (($row = mysql_fetch_assoc($result)))
{
header("Location: http://" . $redirect);
}
//here is the part I dont like
else
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The license ID you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
}
mysql_close($link);
}
//I use jquery valiadate.js for CS validation, but realize this is necessary and would like it to behave like the desired result for the above
else
{
if (strpos($_POST['email1'], '#') === false)
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The email address you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
return;
}
thx
Is it possible to remove the alert and when you redirect to registrationpage.php also send a parameter using the redirect url and popup an alert or error message after the redirect ?
Look into using AJAX. jQuery has a great API for this:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/load/
EDITIED - For cross-domain
You could do something like this:
<div id="results"></div>
<script type="text/javascript">
$("#the_form").submit(function() {
$.getJSON("http://remote.domain/script/to/validate.php?data=" + escape($(this).serialize()) + "&callback=?", function(data) {
$("#results").html(data);
});
return false;
});
</script>
This will (once the IDs are pointed at the correct elements) intercept the form submission, pull together the values from the form (through the serialize() function), and shoot it out to the validation script via AJAX. The output of the script is displayed in the #results div.
Hope this helps!