In my HTML I have an article containing clickable lists. I also have a form that adds data to my database. Once it's done adding the data I want my PHP to send a new list based off the data given in the form to the article in my HTML with my other lists.
How can I do this? I know how to display data from PHP in HTML but I don't know how to display that data in existing articles in HTML.
My function that updates and refreshes my page after every click on a link is called MyFnc and this is the JavaScript for it:
function myFnc(x) {
if (x == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else { //if a link is clicked
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
//readyState = 4: request finished and response is ready
//status = 200: "OK"
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "get_data.php?q=" + x, true);
xmlhttp.send();
}
}
And get_data.php is where I display the data from the database to the webpage. I know that displaying the link must be done in get_data since that is where I display everything to the page. But for now I just want to know how to send the data retrieved from add_records and make a list out of it.
This is my article in my HTML:
<article>
<ul class="lists" style="list-style-type:none">
<li>Tiger</li>
<li>Hammerhead</li>
<li>Bull</li>
<li>Great White</li>
<li>Mako</li>
<li>Greenland</li>
<li>Whale</li>
<li>Thresher</li>
<li>Oceanic WhiteTip</li>
<li>Goblin</li>
</ul>
</article>
Here is my form in my HTML:
<form method="post" action="add_to_records.php">
<input type="hidden" name="addshark" value="true" />
<fieldset>
<label>Name:<input type="text" name="Name" /></label>
<label>SpeciesID:<input type="text" name="speciesID" /></label>
<label>Genus:<input type="text" name="genss" /></label>
<label>Family:<input type="text" name="famly" /></label>
<label>Order:<input type="text" name="ordr" /></label>
<label>Class:<input type="text" name="clss" /></label>
<label>Create New Shark</label>
<input type="submit" value="add shark" />
</fieldset>
<br />
</form>
Here is my add_to_records.php:
<?php
include 'connect.php';
if (isset($_POST['addshark']))
{
include 'connect.php';
$Namee = mysqli_real_escape_string($connect,trim($_POST['Name']));
$specID = mysqli_real_escape_string($connect,trim($_POST['speciesID']));
$gens = mysqli_real_escape_string($connect,trim($_POST['genss']));
$fam = mysqli_real_escape_string($connect,trim($_POST['famly']));
$ord = mysqli_real_escape_string($connect,trim($_POST['ordr']));
$cls = mysqli_real_escape_string($connect,trim($_POST['clss']));
if (!mysqli_query($connect, "INSERT INTO Species
(SpeciesID,Genus,Family,Order_,Class)
VALUES ('$specID','$gens','$fam','$ord','$cls')"))
{
die('error inserting new record');
}
//I would like the list it returns to look like this if the Name entered was Hello
//and the speciesID entered was Something
//<li>Hello</li>
//echo "shark was added";
header('Location: ProjectMainAdmin.html'); exit;
}
mysqli_close($connect);
?>
Just use jQuery's AJAX, it's a lot simpler and easier to implement. Data will be passed to server, then once completed you need to append the data into your list.
something like this:
$("form").submit( function(){
$.ajax({
url: "add_to_records.php",
success: function(result){
$(".lists").append("<li><a href=''>" + result.name + "</li>");
}
});
return false;
});
Related
STRANGE BEHAVIORS
No matter how I organize the code:
Submit button makes the loader and then the confirmation message appears even if you dont fill the email input form
Sometimes refresh the page , sometimes dont
What I want is simple:
a) If the email input form is unfilled then dont do nothing just expect the html5 input validation message.
b) If all is ok and the email input is correctly filled then have the loader appears and then the confirmation message.
I have 3 days in a row, experimenting. I'm STUCK.
Thanks in advance
AJAX / JS
function ajaxFunction() {
var form = document.getElementById("contactForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('email_suscribe', handleForm);
var ajaxRequest;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("loading").innerHTML = ''; // Hide the image after the response from the server
document.getElementById("ajaxDiv").innerHTML = xmlhttp.responseText;
}
}
document.getElementById("loading").innerHTML = '<img src="images/loading.gif" />'; // Set here the image before sending request
xmlhttp.open("GET", "includes/suscripcion.asp?email_suscribe=<%=request.form("email_suscribe")%>", true);
xmlhttp.send();
}
FORM
<form id="contactForm" name="contactForm">
HTML
Email Input Form
<input name="email_suscribe" type="email" autocomplete="on" required="required" class="footer_suscribir" placeholder="Correo Electronico" maxlength="60">
Submit Button
<button name="submit" onclick="ajaxFunction();" class="footer_suscribete"><strong>Suscribete</strong></button>
Loader
<span id="loading"></span>
Real Time Confirmation Message
<div id="ajaxDiv"></div>
You can check this.
HTML
<input name="email_suscribe" type="email" autocomplete="on" required="required" class="footer_suscribir" placeholder="Correo Electronico" maxlength="60">
<input type="button" onclick="subscribe()">
<span id="loading"></span>
<span id="ajaxDiv"></span>
JS
<script>
function subscribe() {
var email=$(".footer_suscribir").val()
if (isEmail(email)===true) {
$("#loading").fadeIn("fast")
$.ajax({
type: 'POST',
crossDomain: true,
url: "postdata.asp",
data: {
"email": email
},
success: function (resp) { //resp: return from postdata.asp
$("#ajaxDiv").html(resp)
$("#loading").fadeOut("fast")
},
error: function (e) {
$("#ajaxDiv").html("AN ERROR OCCURRED")
$("#loading").fadeOut("fast")
}
});
}
else {
$("#ajaxDiv").html("EMAIL FORMAT ERROR")
}
}
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
</script>
POSTDATA.ASP
<%
'...
'DB CONNECTION
'...
' SAMPLE DB EXECUTION
email=request.form("email")
Set rsa=Server.CreateObject("Adodb.Recordset")
Sorgu="Select TOP 1 email from subscribers WHERE email='"&email&"'"
rsa.Open Sorgu, bag, 1, 3
if rsa.bof then
rsa.addnew
rsa("email")=email
rsa.update
response.write "SUCCESS"
else
response.write "ALREADY EXISTS"
end if
rsa.close
set rsa=nothing
%>
I am having trouble in submitting radio input values using PHP and AJAX. I've constructed the code below, but I can't seem to get it to work. Any ideas? The values of the radio fields need to pass only when the button is pressed
<script>
function showUser(str) {
if (str == "myvalue") {
document.getElementById("txtHint").innerHTML = "";
/// location of new code -start
document.querySelector('input[name="users"]:checked').value;
/// location of new code -end
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
<form>
<input type="radio" name="users" value="1">
<input type="radio" name="users" value="2">
<!-------unable to pass value----------->
<input type="button" value="myvalue" onclick="showUser(this.value)">
<!-------unable to pass value----------->
</form>
<div id="txtHint">echo results here</div>
ajax-php.php
<?php
$q = intval($_GET['q']);
echo $q;
?>
Thank you.
Your 'this.value' parameter being passed to your showUser function is scoped to the element with the onclick function.
So it is trying to send the value of the button element which has no value.
What you are doing is fine.
<input type="button" onclick="showUser(this.value)">
The function showUser is called by the button type input field. And the field has no value.
If you want to send any value then use value attribute. For example:
<input type="button" value="mayValue" onclick="showUser(this.value)">
To access the radio button value you can use this code.
document.querySelector('input[name="users"]:checked').value;
To send the radio button value follow the code bellow
//xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.open("GET", "ajax-php.php?q=" + document.querySelector('input[name="users"]:checked').value, true);
I have been new to AJAX and i am unable to display the fetched data to 2 different elements of datepicker startdate and enddate but i was able to fetch only 1 value from ajax response.
My HTML is given below
<div class="control-group" id="startingdatee">
<label class="control-label" for="form-field-1">
Start Date
</label>
<div class="controls" style="width:265px;" id="startingdate">
<input class="span10 date-picker" id="startdate" value="" type="text" data-date-format="dd-mm-yyyy" name="startdate">
</div>
</div>
<div class="control-group">
<label class="control-label" for="form-field-1">
End Date
</label>
<div class="controls" style="width:265px;">
<input class="span10 date-picker" id="enddate" type="text" data-date-format="dd-mm-yyyy" name="enddate">
</div>
</div>
Java Script is given below which is used to get the response from the dateshow.php file and could update only 1 value that is startdate only. I used document.getElementById("startdate").value = response..
function showDate(str)
{
if (str=="")
{
return;
}
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("startdate").value = xmlhttp.responseText;
}
};
xmlhttp.open("GET","dateshow.php?q="+str,true);
xmlhttp.send();
};
and php file is dateshow.php used to get minimum date and maximum date.
<?php include('includes/db.php');
$q = $_REQUEST["q"];
//echo $q;
//$q = 41;
$query = "SELECT MIN(datetime) AS MIN,MAX(datetime) AS MAX
FROM transactions
WHERE farm_id = $q";
$run = mysqli_query($con, $query);
while($row = mysqli_fetch_array($run))
{
$mindate = $row['MIN'];
$maxdate = $row['MAX'];
}
$mindatefor = strtotime($mindate);
$startdate = date('d-m-Y',$mindatefor);
$maxdatefor = strtotime($maxdate);
$enddate = date('d-m-Y',$maxdatefor);
echo $startdate;//."#".$enddate;
?>
Try creating an array in the php script and json encoding it.
$returnData = ['start'=> $startDate, 'end'=> $endDate];
echo json_encode($returnData);
Then, when you retrieve the data using AJAX, do JSON.parse(xmlhttp.responseText)
This will return a javascript object that should look like this
{
start: some start data,
end: some end data
}
Is possibile achieve your goal using json response in example suppose that you have your page which return a json object in example :
<?php
/*do some stuff here and implementing you query, iteration and so on so
forth then provide a response with the result that you have from your
task and suppose in this case in example that $startdate="01-01-2015" and
$maxdatefor="02-02-2015"
*/
header('Content-Type: application/json');
echo json_encode(array('datepicker1' => $startdate,'datepicker2' => $maxdatefor,));
?>
it will return a json object into your javascript like
{datepicker1:01-01-2015,datepicker2=02-02-2015}
Now get those data is really simple and you can use jquery ajax request which, at my personl advice is more simple to use which use this schema
//Make your check in your function before make an ajax request in order to
//be sure that all the information, input or any other stuff is in the right
//place as well then make this call below
$.ajax({
type:"POST / GET", //IN YOUR CASE GET
url: "youurl" + "yourparamenter",//DONT FORGET TO ENCODE QUERY STRING
data: '', //NOT NECESSARY IN YOUR SPECIFIC CASE
success: function (data) {
//data is the json returned value within the reponse and you can access in this way
$("#startdate").val(data['datepicker1']);
$("#enddate").val(data['datepicker2']);
},
error: function () {
alert('Something is gone wrong!!!!');
}
});
Don't Forget: add jquery script reference in your page in head tag in order to be able to call Jquery function.
I hope that this could help you
Regards
I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>
I am try to have a forum submits more then once when a user clicks the submit button. Why? I am try to add more then one idem to a shopping cart, The shopping cart software I am using doesn't support adding more then one product at a time and I don't want to edit there core code. The hidden forum would have the product ids like '1,2,3' I'd then need the JavaScript to separate the values and post each one using AJAX to the cart. I am not great a JavaScript but I coded what I think should work but its just giving me a alert: 'There was a problem with the request.' twice. I can't see whats wrong with it, any and all help and suggestions are welcomed! Here the code:
JS
<script type="text/javascript">
function testResults (form) {
var product_id = form.product_id.value;
var quantity = form.quantity.value;
var brokenstring=product_id.split(",");
for ( var i in brokenstring )
{
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
var poststr = "product_id=" + encodeURI( brokenstring[i] ) +
"&quantity=" + encodeURI( quantity );
makePOSTRequest('post.php', poststr);
}
}
</script>
HTML
<form action="javascript:testResults(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="product_id" id="product_id" />
<input type="hidden" name="quantity" id="quantity" value="1" />
<br />
<input type="submit" name="button" value="Submit" />
</form>
<span name="myspan" id="myspan"></span>
post.php
<?php
print_r($_POST);
?>
If you want to add two items to the cart shouldnt you be doing two posts with the same item? I can just see one post per item there. You are not taking the quantity into account. But this is not the problem. In this case this is only a logic error.
For the javascript side I would recommend you to use jQuery to treat the ajax stuff because it will make your life WAY easier than regular javascript that might event not work with all browsers.
This is the link related to the POST method of jQuery: http://docs.jquery.com/Post
Hope it helps
It is against all the programming logics to post a form several times instead of having a more complex form. From what I can see or understand from your code you are trying to loop through your splitted (brokenstring) string. Your loop is not constructed where and how it should be. Anyway, if I were you, I would consider migraton to another free cart o the possibility to write one myself. From what I see you will be able to do so with a little bit of help from here.