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'];
Related
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.
I'm searching for the best solution to display information which I store in PHP variable (which I get from a MySQL DB).
I was thinking to use jQuery. My questions:
With the input field I receive the number of the Member.
I store a new variable called $imgMember with the img name.
Questions:
I want to display this image each time a user enters a number at <div class="boxImageMember"> (which I already validated through PHP and made a variable ($imgMember) of it.
How should I access it? Do I need to store those variable with AJAX? Internal/external jQuery? Or do I need to think otherwise? Im stuck in my head.
Im totally stuck with the way I how to process this.
HTML:
<div id="header">
<div class="header-content">
<img src="img/logo-dqmih.png" width="60px">
</div>
</div>
<div class="container">
<div class="boxImageMember">HERE I WANT TO DISPLAY A USER IMAGE</div>
<div class="boxInformationMember"></div>
<form action="" method="post">
<input type="text" id="MemberNumberEntry" name="staffNumber">
<button type="submit" name="action">
</form>
</div>
jQuery:
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
console.log(MemberNumberEntry);
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
Your jQuery script would do something like this
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
//console.log(MemberNumberEntry);
$.ajax({
url: '/your-php-script.php',
method: 'POST',
data: {
MemberNumberEntry: MemberNumberEntry
},
success: function(response){
//If call goes well, you use the image here.
}
});
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
You're basically sending an HTTP POST request to your PHP script that will accept the image ID like a normal post request, using $_REQUEST or $_POST.
There are tonnes of options to configure with jQuery, you can look at the docs here. For more information on working with images in PHP and AJAX, this answer is useful.
I have a html web page which I use to get some user input. This input is then posted using jquery to a php script which in turn sends a get request to a REST API to receive json data.
My question really is: is it possible to change my php file into another webpage with embedded php and redirect to this while posting the variables to the same script, so I could display the json results in a table on a new page simultaneously.
I already receive the json in the javascript file and I know I could use this to create a table, I was just interested if I could in fact do it all in one go on the php page as I already have script written to populate a table using the json data.
I have included some basic fragments of my code to help explain what I am doing.
HTML:
<head>
<script type="text/javascript" src="collect_User_Input.js"></script>
</head>
<p> What is the unique id of the beacon? </p>
<form> <input type="text" id="uniqueId" /> </form>
<button onclick="collect_User_Input();" >Send Request</button>
JS:
var uniqueId = document.getElementById('uniqueId');
$.post("send_Request.php", { uniqueId: uniqueId.value },function(result) {
alert(result);
PHP:
$uniqueId = $_POST["uniqueId"];
(GET request using curl)
echo ($uniqueId);
I tried skipping the javascript step and submitting the form directly, but this always gave me forbidden error messages. as you may have guessed I am very new to this so any advice is welcome.
In your PHP you will most likely want to return some JSON using json_encode:
http://php.net/manual/en/function.json-encode.php
Within your JSON, you could return a success value - then depending on the value of that you can redirect using:
window.location
You could even have a second attribute that returns what page you want the user redirected to if it isn't the same as the uniqueID:
{"success":true,"location":"/your/path/here.html"}
The flip side being, if there is an error you can return this to your page with a relevant message:
{"success":false,"message":"ID not found"}
I use this process to check something is valid on the server before doing the redirect, which sounds more or less the same as what you want to do?
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.
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.