I am writing a program that gets information from forms using AJAX, and I was wondering if there was a way to make a button that clears the form and sort of resets the form. Right now if you press a button, the text won't disappear, but Im hoping to make a home button that would make the text disappear. I am just going to post my .html file because I think thats all we need. Let me know if there is more code you need. I tried making a reset button but it didn't seem to work.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + "period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<button type="reset" value="Reset"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
Your reset-button should already do this, if its within the <form></form> or has the "form"-attribute, see here
You can either use the default reset button, if it is in between the form tag or you can use jquery to do this for you.
You just have to add an event on the click event of the home button and u can achieve what you want.
this is a reference which u can take
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], input[type="password"], textarea").val("");
});
Add all other fields which u want to clear on click of the home button
Related
So, I have a HTML form and I need to send it's value as a parameter to a php function, but I also need a different value, that's not even inside the HTML.
For example:
<form action="methods.php" method="register">
<input type="text" placeholder="EventID">
<input type="submit" value="Register">
</form>
This form would get the event id and send it as a parameter to register the user into the event. But I need to send the user as a parameter also (function register($user, $eventid)) and I have no idea on how to do so.
I did find some similar things around here, but they were related to POST and GET and I'm not sure they work for me and I could not understand how to use in them in my case, so if anyone could help me out, pleaaaaaase, i'd be really thankful
Its very simple you just need to take care of few things.
1: every input field should have a name.
2: set form method either GET(to send values visible in the url) or POST(to send data without showing in the url)
3: on methods.php receive form data if send via GET then $_GET['input_field_name'] or via POST then $_POST['input_field_name']
Look for the explanation in comments below:
//<![CDATA[
// external.js
var post, doc, bod, htm, C, E, T; // for use on other loads
addEventListener('load', function(){ // load
// used in post function below to create String from Object
function phpEncode(obj){
var r = [];
if(obj instanceof Array){
for(var i=0,l=obj.length; i<l; i++){
r.push(phpEncode(obj[i]));
}
return '%5B'+r.join(',')+'%5D';
}
else if(typeof obj === 'object' && obj){
for(var i in obj){
if(obj.hasOwnProperty(i)){
var v = obj[i], s;
if(typeof v === 'object' && v){
s = encodeURIComponent('"'+i.replace('"', '\\"')+'":')+phpEncode(v);
}
else{
v = typeof v === 'string' ? '"'+v.replace('"', '\"')+'"' : v;
s = encodeURIComponent('"'+i.replace('"', '\\"')+'":'+v);
}
r.push(s);
}
}
return '%7B'+r.join(',')+'%7D';
}
else{
r = typeof obj === 'string' ? '"'+obj.replace('"', '\\"')+'"' : obj;
return ''+r;
}
}
// used in post function below to evaluate (make into code) JSON String that comes back from PHP
function phpAccept(url){
return eval('('+decodeURIComponent(url)+')');
}
// here is an example of a post AJAX function
post = function(send, where, success, context){
var x = new XMLHttpRequest;
var c = context || this;
x.open('POST', where); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200){
if(success)success.call(c, phpAccept(x.responseText));
}
}
if(typeof send === 'object' && send && !(send instanceof Array)){
var r = [];
for(var p in send){
r.push(encodeURIComponent(p)+'='+phpEncode(send[p]));
}
x.send(r.join('&'));
}
else{
throw new Error('send must be an Object');
}
return x;
}
// yes, you can do this - just remember that non-primitive values are the actual Object through assingment
doc = document; bod = doc.body; htm = doc.documentElement;
// simple way to create an Element by tag
C = function(tag){
return doc.createElement(tag);
}
// simple way to document.getElementById()
E = function(id){
return doc.getElementById(id);
}
T = function(tag){
return doc.getElementsByTagName(tag);
}
var form = E('form'), sub = E('sub'), i1 = E('i1'), i2 = E('i2');
// prevent old school submission
form.addEventListener('submit', function(ev){
ev.preventDefault(); // prevents submission
});
// just for testing remove below
var tS = E('test_out').style;
// remove above
// ajax submisson
sub.addEventListener('click', function(){
/* note that if the Elements are not removed from or added
to the DOM you don't need to get them again Element.value
will probably be different so you'll want to get them
on every click
*/
post({phpProp1:i1.value, phpProp2:i2.value}, 'yourPHPajaxResponsePage.php', function(data){
/* before data comes back yourPHPajaxResponsePage.php may look like this:
<?php
session_start(); // super common - read up on it - not needed here - but won't hurt
if(isset($_POST['phpProp1'], $_POST['phpProp2'])){
// usually you affect MySQL using PHP at this point
// we'll just send them back in this lame example
$res = array('jsProp1' => $_POST['phpProp1'], 'jsProp2' => $_POST['phpProp2']);
// makes results come back as JSON
echo json_encode($res);
}
?>
*/
if(data){ // may want more conditions
E('out').innerHTML = data.jsProp1+'<br />'+data.jsProp2;
}
}, this);
// just for testing - remove below
tS.display = 'block';
E('temp_res').innerHTML = i1.value+'<br />'+i2.value;
// remove above
});
// testing only remove below
var ins = doc.querySelectorAll('input[type=text]');
for(var i=0,l=ins.length; i<l; i++){
ins[i].addEventListener('focus', function(){
tS.display = 'none';
});
}
// remove above
form.addEventListener('keydown', function(ev){
// if user hits enter
if(ev.keyCode === 13)sub.click();
});
}); // end load
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
#form{
width:266px; color:#fff; background:green; padding:10px;
}
#form>div>label{
display:block; float:left; width:57px;
}
#form>div>input{
width:203px;
}
#form>div{
margin-bottom:10px;
}
#form>#sub{
display:block; margin:0 auto;
}
/* remove below - testing only */
#test_out{
display:none;
}
#test_out>div:first-child{
color:red;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>AJAX Example</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='form'>
<div><label for='i1'>Input 1</label><input id='i1' name='i1' type='text' value='' /></div>
<div><label for='i2'>Input 2</label><input id='i2' name='i2' type='text' value='' /></div>
<input id='sub' type='button' value='submit' />
</form>
<div id='out'></div>
<!-- for testing remove below -->
<div id='test_out'><div>Must have PHPServer code in JavaScript Comments to get real results</div><div id='temp_res'></div></div>
<!-- remove above -->
</div>
</body>
</html>
What do you think?
you can use hidden field or you can use session or cookie for user
<form action="methods.php" method="post">
<input type="hidden" name="txtuser" value="abc">
<input type="text" placeholder="EventID">
<input type="submit" value="Register">
</form>
if you use cookie or session then there is not need to pass it as parameter its a global variable so you can access its value at any page directly, you just need to store value to it and access it any where in your project.
I've successfully wrote a working Ajax code, but the problem is that i can add an input field only once. I have a submit input, that calls Ajax script, everything works, the input text field appears, but after this if i want to add another text field by clicking on the submit input, it does not work. You only load once (YOLO). How do i write more awesome code that lets me add as many text fields as needed? Thanks for every reply. Here is my code:
index.php:
<head>
<script>
function ajaxobj(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('asd').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajaxAddInput.php',true);
xmlhttp.send();
}
</script></script>
</head>
<body>
<input type="submit" onclick="ajaxobj();">
<div id="asd"></div>
</body>
the php file:
<?php
echo '<input type=\"text\">';
?>
Simply use a standardized library, just like jQuery. With this in mind, you might use the following code:
$("#asd").on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
Alternatively, you can use the library with classes as well:
$('input[type=text]').on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
I am having problems with a really basic request to a php file from AJAX. I am running all this stuff through XAMPP. What I'm trying to do with this code is to echo the name typed into the textbox once the submit button is clicked and the results to be posted in the div "results". I am doing this to try and weed out errors in another script and so far it hasn't gone too well.
<html>
<head>
<script type="text/javascript">
function go() {
var request;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var uname = document.getElementById("name").value;
request.onreadystatechange= function() {
if(request.readyState == 4) {
document.getElementById("result").innerHTML = response.Text;
}
}
url = "win.php?name="+uname;
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body>
Name:<input type="textbox" name="jesus" id="name" />
<input type="button" value="Submit" onlick="go()" />
<div id ="result"> Result:</div>
</body>
</html>
<?php
$name = $_GET['name'];
echo $name;
?>
You don't have an object called response, you are looking for the responseText property on the request object.
document.getElementById("result").innerHTML = request.responseText;
Also:
avoid using globals
don't send your HTTP request before the target div exists, you run the risk of it still not existing when the response comes back
you probably should check that the HTTP status of the response is 200 (OK) as well as being finished (readyState 4).
Don't put raw user input in URLs, escape it with encodeURIComponent first
Use that
document.getElementById("result").innerHTML = response.responseText;
I'm trying to pull photos from specific tag. Found an awesome tutorial and I've managed to pull photos from Instagram with pagination.
The problem I'm facing now is duplicate photos being displayed if it reaches to the end of the photos.
HTML Source
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-1.7.2.min.js' type='text/javascript' charset='utf-8'></script>
<script src='javascripts/application.js' type='text/javascript' charset='utf-8'></script>
<link rel='stylesheet' href='stylesheets/application.css' type='text/css' media='screen'>
<title>Photo Stream </title>
<meta name="description" content="Search for instagram images online.">
<meta name="author" content="Omar Sahyoun">
</head>
<body>
<!--<form id='search'>
<button class="button" type="submit" id="search-button" dir="ltr" tabindex="2">
<span class="button-content">Search</span>
</button>
<div class='search-wrap'>
<input class='search-tag' type='text' tabindex='1' value='cats' />
</div>
</form>-->
<h2 id="search">Photo Stream </h2>
<div id='photos-wrap'>
</div>
<div class='paginate'>
<a class='button' style='display:none;' data-max-tag-id='' href='#'>View More...</a>
</div>
</body>
</html>
Javascript File
// Add trim function support for IE7/IE8
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
// Instantiate an empty object.
var Instagram = {};
// Small object for holding important configuration data.
Instagram.Config = {
clientID: 'xxxx',
apiHost: 'https://api.instagram.com'
};
// Quick and dirty templating solution.
Instagram.Template = {};
Instagram.Template.Views = {
"photo": "<div class='photo'>" +
"<a href='{url}' target='_blank'><img class='main' src='{photo}' width='250' height='250' style='display:none;' onload='Instagram.App.showPhoto(this);' /></a>" +
"<span class='heart'><strong>{count}</strong></span><span class='comment'><strong>{count2}</strong></span>" +
"<span class='avatar'><iframe src='//www.facebook.com/plugins/like.php?href={url}&send=false&layout=button_count&width=40&show_faces=true&action=like&colorscheme=light&font&height=21&' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:80px; height:21px;' allowTransparency='true'></iframe></span>" +
"</div>"
};
Instagram.Template.generate = function(template, data){
var re, resource;
template = Instagram.Template.Views[template];
for(var attribute in data){
re = new RegExp("{" + attribute + "}","g");
template = template.replace(re, data[attribute]);
}
return template;
};
// ************************
// ** Main Application Code
// ************************
(function(){
function init(){
bindEventHandlers();
}
function toTemplate(photo){
photo = {
count: photo.likes.count,
count2: photo.comments.count,
avatar: photo.user.profile_picture,
photo: photo.images.low_resolution.url,
url: photo.link
};
return Instagram.Template.generate('photo', photo);
}
function toScreen(photos){
var photos_html = '';
$('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id)
.fadeIn();
$.each(photos.data, function(index, photo){
photos_html += toTemplate(photo);
});
$('div#photos-wrap').append(photos_html);
}
function generateResource(tag){
var config = Instagram.Config, url;
if(typeof tag === 'undefined'){
throw new Error("Resource requires a tag. Try searching for cats!");
} else {
// Make sure tag is a string, trim any trailing/leading whitespace and take only the first
// word, if there are multiple.
tag = String(tag).trim().split(" ")[0];
}
url = config.apiHost + "/v1/tags/" + tag + "/media/recent?callback=?&count=10&client_id=" + config.clientID;
return function(max_id){
var next_page;
if(typeof max_id === 'string' && max_id.trim() !== '') {
next_page = url + "&max_id=" + max_id;
}
return next_page || url;
};
}
function paginate(max_id){
$.getJSON(generateUrl(tag), toScreen);
}
function search(tag){
resource = generateResource(tag);
$('.paginate a').hide();
$('#photos-wrap *').remove();
fetchPhotos();
}
function fetchPhotos(max_id){
$.getJSON(resource(max_id), toScreen);
}
function bindEventHandlers(){
$('body').on('click', '.paginate a.button', function(){
var tagID = $(this).attr('data-max-tag-id');
fetchPhotos(tagID);
return false;
});
// Bind an event handler to the `click` event on the form's button
$('form#search button').click(function(){
// Extract the value of the search input text field.
var tag = $('input.search-tag').val();
// Invoke `search`, passing `tag`.
search(tag);
// Stop event propagation.
return false;
});
}
function showPhoto(p){
$(p).fadeIn();
}
Instagram.App = {
search: search,
showPhoto: showPhoto,
init: init
};
})();
$(function(){
Instagram.App.init();
// Start with a search on cats; we all love cats.
Instagram.App.search('hwplus');
});
Please help me to find a way to disable the 'View More' button if photos have reached the end.
And is there a way to add cache in JSON object and fetch variables from Javascript?
Thanks and appreciate.
Once you reach the end of the photos, the next_max_tag_id won't exist. You'll need to check if next_max_tag_id exists and if not, disable the button. You'll implement your new code on this line, maybe make a variable for photos.pagination.next_max_id and when the user clicks the button, check if the variable is defined.
Untested code:
var next_max = photos.pagination.next_max_id;
if (next_max == 'undefined') {
var next_max = 'end';
$('.paginate a').addClass('disabled');
}
//define .disabled in your CSS
$('.paginate a').attr('data-max-tag-id', next_max).fadeIn();
My goal is to have input field that will take value of whats was typed and echoed through. The js function will grab the value of the input box two seconds after user stops typing and post it. The issue seems to be with the php not echoing the value of the input box. When I take out the js function and use a button that forces refresh then
it works fine. How come php is not taking the value posted by js function?
Example SITE
JS
<script type="text/javascript">
$(document).ready(function() {
var timer;
$('#video-input1').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#ytVideo").submit()
//alert('submitted:' + value);
}, 2000);
});
//then include your submit definition. What you want to do once submit is executed
$('#ytVideo').submit(function(e){
e.preventDefault(); //prevent page refresh
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php', form, function(data){
});
return false;
});
});
</script>
PHP
<?php
if($_POST)
{
$url = $_POST['yurl'];
function getYoutubeVideoID($url) {
$formatted_url = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})
(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','http://www.youtube.com/watch?v=$1',$url);
return $formatted_url;
}
$formatted_url = getYoutubeVideoID($url);
$parsed_url = parse_url($formatted_url);
parse_str($parsed_url['query'], $parsed_query_string);
$v = $parsed_query_string['v'];
$hth = 300; //$_POST['yheight'];
$wdth = 500; //$_POST['ywidth'];
$is_auto = 0;
//Iframe code with optional autoplay
echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
}
?>
form
<html>
<form method="post" id="ytVideo" action="">
Youtube URL: <input id="video-input1" type="text" value="<?php $url ?>" name="yurl">
<input type="submit" value="Generate Embed Code" name="ysubmit">
</form>
</html>
It's because you are not returning your php result anywhere. It's simply lost...
$.post('index.php', form, function(data){
var x = $(data);
$("body").html(x);
});