Dynamically and Permanently Adding an Element to Your Page - Javascript/jQuery - javascript

I'm working on a website project from scratch. The content section of the main page has a form and a div of class "blog". When the user is logged in on the admin account, the form shows up. This allows you to pick a title and content to post in the blog. The current code works well, except for the fact that the posts are removed when the page is refreshed. How I can permanently add this to the page?
Here's my code:
<script type="text/javascript">
function addtext() {
var title = document.blogform.title.value;
var content = document.blogform.content.value;
var $blogTitle = $('<div class="blogtitle">' + title + '</div>');
var $blogContent = $('<div class="blogbody">' + content + '</div>');
$('#blog').prepend($blogContent);
$('#blog').prepend($blogTitle);
}
</script>
<h2>Submit New Blog Post</h2>
<div class="blogtitle">Submit a new blog post:</div>
<div class="blogbody">
<form name="blogform">
<fieldset class="fieldsetoffset"><legend>Post</legend>
<div>Title of Post:</div>
<input type="text" name="title">
<div>Content of Post:</div>
<textarea name="content" class="comment" rows="6" cols="88"></textarea>
<hr>
<input type="button" value="Add New Text" onClick="addtext();">
</fieldset>
</form>
</div>
<div id="blog"></div>

You should use a database (or flat-files, but not recommended..) to store those extra parts. On your page, create a database connection (php.net/PDO), fetch any existing records from the database and when the admin stores it you should insert it into your database.
HTML is flat, you can add and delete elements dynamically by altering the DOM but that's only on your screen and nobody elses :)

I assume that this is a static HTML page. Otherwise you would be refreshing from a server-based data source. If you are going to be doing this, then the only other way would be to store the data as client-side cookies.

You can't do this by Javascript or jQuery because they are client side languages.
for this which you want to achieve you have to use a Server Side Language and database

Javascript is client side, meaning when you add content to the page with jQuery it's local to your browser only, not on the server-side (it's not actually changing the website, it's just changing what your browser is rendering).
You will need to either use cookies (there is a great jQuery cookies plugin that's incredibly simple to use) or, preferably, have some kind of server-side script store it in the database and retrieve the values later, i.e. with PHP/mySQL, since cookies are still going to be specific to you rather than anyone who might visit the website. If nothing else you could use PHP to write it to a text/html file on the server that is then displayed later but that's a really ugly solution and a database is really where you should be going here.
I would probably use jQuery's AJAX functions to call a PHP function when addtext() is triggered that passes it the content and title values to write to the database. Then add a bit of php code on the page to check the database for existing posts and display them.

Related

How to run a PHP function due to a button click (with button 'data' passed)?

I know that AJAX could solve my issue. I need help how I can solve it in my specific case however. I manage some sortiment items on a page, they get displayed with a PHP script (checks the database, if the item is available, and if so, it gets displayed). I now want an admin page where I can kind of "toggle" via a sortiment table to display or not display an item (set it as available or non available.
What I need is: if the button is clicked, I would like to start a php-skript. There should be an value passed to that script (the button id). The script itself should open an SQL connection, change a DB value based on the passed ID of the button. Then close the connection. Optionally also refresh the table (or one value) from where the button was clicked.
Can someone help me, at least telling me what I need to do this? (jQuery, Ajax?). The passing of the ID would be important, else I'd need to do function for every button.
An table entry looks like this:
<tr>
<td>Himbeerhonig</td>
<td id="himbeerhonig">Ja</td>
<td><button type="button" id="himbeerhonig" onclick="function()">press me to execute function</button></td>
</tr>```
(possible PHP pseudocode)
open SQL connection
look for database entry based on the passed ID
change the value of the found entry (!currentValue)
close SQL connection
*optionally*
refresh the <td id="himbeerhonig"> with the updated value.
I appreciate any help very much! Just need some hints as to how to do it properly. It's just a concept that currenty is hard to grasp for me so far.
1- If you want to do this with ajax (without browser refresh), you should create a separate php file, and put your php scripts in there. it's called api (api has special format for output, so search create api in php if you want to do this). then on javascript, you should do an ajax call to that php address, on onclick event of button. and then javascript will return data and you can create elements based on that data.
2- however you can do this without ajax(it will refresh browser). just write your inline phps as you wrote :
<html>
<!-- your html codes-->
<?php
if($_GET['buttonClicked']){
//put your php codes here to run when button clicked
?>
<!-- you can even put html here, even it can be on php loop. -->
<?
}
<!-- your html codes-->
<!-- turn your button to a form-->
<form action="/" method="get">
<input name="buttonClicked" hidden value='1'>
<input type="submit" value="Submit">
</form>
</html>
it's as easy as this. when button clicked, a get request will send to current page, and php will handle it, for example it will render additional html elements to the page.

global variable not displayed in div

I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery

Update content of div using javascript/jquery/php

I am currently making a webpage where I want the user to view different database results depending on which result they pick. The results will either be picked through a button, or by a query typed in by hand into a textarea.
I have the connection to the database and everything set up in an external PHP script which I am currently linking in to my site using "require".
Within this PHP script I have a "query" variable.
I would like for this variable to be dependent on whatever value is entered by the user.
I suppose this should be doable using some sort of $query = $POST['entry'] and some kind of Ajax call in a javascript? I just don't know how this whole thing should be fitted together.
If we assume that my menu and container looks something like this, where getData.php is where the $query variable is and what returns the database data.
<div id="menu">
<textarea class="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input class="menuButt" type="button" value="Submit" onclick="JavaScript:ChangeDivVal();"/>
</div>
<div id="container">
<?php
require 'getData.php';
?>
</div>
Here is a picture if that helps my explanation of what I want to do.
I'm very grateful for any help I could possibly get!
//Ambrose
There are neat and simple mechanisms to pass the input of your textarea (the query string) to php and return the database output back to javascript. From there you then can easily attach it to any dom node you wish.
I personally do stuff with jQuery since its so handy. You might wanna use the load function for your simple purpose:
$( document ).ready(function() {
$('#querySubmitButton').click(function (evt)
{
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
// load data received from php script into the dom container
$('#container').load('getData.php', { query:myQuery, anotherVar:null });
});
});
The load function simply loads everything the desired script outputs into the given domnode. You can add as many parameters as you want in the second argument and could even use a callback to perform some more js after loading.
For details see http://api.jquery.com/load/.
Oh and by the way I changed your html to this:
<div id="menu">
<textarea id="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input id="querySubmitButton" type="button" value="Submit"/>
</div>
<div id="container"></div>
In your getData.php (which I assume produces plain html) you can then use php's $_POST var to get the query.
$query = $_POST['query'];

Yahoo Merchant Store Catalog Tags Insert Dynamically with Javascript, Jquery, or Ajax

I opened up a yahoo store through their Merchant Service. They have a pretty good store catalog that I have used on a business site that I own. I like it so I decided to use the service again on another business I own. I got the site built but have ran into a few issues with calling the Yahoo Catalog Tags. The tags are basically comments. EX: (<!--#ystore_order id=item_id -->). When the site is loaded it is parsed and the page loads the product details in place of this tag/comment.
I can get everything to work except for the action attribute of my form.
I have tried a bunch of things but I cannot seem to get the action set for my form. If I hard code the tag then it works fine but obviously if I did that then I would have to create a page for every single product.
My form:
<div id="list">
<form method="post">
<input id="btnSubmit" type="submit" value="Add To Cart">
</form>
</div>
Trying to add the comment/tag to form action attribute. I've done it this way(below) and also by getting rid of the variable and just paring the url in the jquery attr function.
<script language="javascript">
$.ajaxSetup({cache: false});
$(document).ready(function(){
//Get URL from URL Query String.
var obj = getUrlVars()["Object"];
//Set form action attribute
$('form').attr('action', '<!--#ystore_order id='+ obj +' -->');
});
</script>
I've also tried creating the form dynamically.
<script language="javascript">
$.ajaxSetup({cache: false});
$(document).ready(function(){
//Get URL from URL Query String.
var obj = getUrlVars()["Object"];
var new_form = '<form method="post" action="<!--#ystore_order id='+obj + ' -->">' +
'<input type="submit" value="Add To Cart" id="btnSubmit">' +
'</form>';
$('#list').append(new_form);
});
</script>
I have tried to escape some characters but have had no success there either.
"\<\!--#ystore_order id='+obj + ' --\>"
I know the issue has something to do with the comment syntax but if I can add it manually then I should be able to do it dynamically. I know this is a hard one to test but if anyone thinks they may have a solution I would be happy to set up an ftp account on my site so you can test and I will provide the product ID's for testing. I've fought with this for about 30+ hours.
Yahoo store tags are populated server-side. Adding a store tag on the client side using Javascript won't do anything, because the code that recognizes the store tag and appends the appropriate html will never see the tag you drop in on the client side. There's no client-side solution possible
The best solution here would be to write a server side program to populate a template with the appropriate tag in response to http requests. I'm not super-familiar with the Yahoo store, so I don't know what the best language for this would be, but it would be a very simple program given how straightforward it sounds like your template is. Since this is already embedded in a site you own, I'd just use whatever backend language you are already working in.
Once you have a server side script that executes and returns the html you need, you could use AJAX to populated it with the appropriate product details as needed.

Can i use JS to replace a GET-parameter with a Post in a link?

I'm working with an old ASP WebForms page in which there is a link which opens in a new windo using javascript. This link includes a GET-parameter, like this:
<href="javascript:window.open(http://myurl.com?MyId=123).focus()">
Search for object
</a>
What I would like to do is replace this GET-parameter with a Post-variable in order to avoid the value of MyId being stored in the browser-history. Possibly something like:
<input type="hidden" id="MyId" name="MyId" value="123">
<a href="submitSearchCriteria()">
Search for object
</a>
Note: Since this is a webforms page, the whole contents of the page is within a pair of <form>...</form> tags which post back to the page itself, and I don`t want to mess with these. The page I would like to link to is another page.
My question: Is there some fairly simple, clean and safe way to pass along a Post-variable from within a link like this? I would prefer to do this without including any third-party java script libraries if possible (I want to minimize the necessary changes to an aging system).
Any ideas?
Add your MyId in your form:
<input type="hidden" id="MyId" name="MyId" value="123">
Then your hyperlink:
Search for object
Then use javascript to change your form action:
function submit(){
[Your Form].action = "[Your Action]";
[Your Form].submit();
}
The form submits but as the page refreshes, the form action goes back to what it was before. But this could depend to where you point back your new action. You could add something to handle the response. This is the easiest solution if you ask me. But for the cleanest, you should try reading about AJAX.

Categories

Resources