in SO you can search for tags without pressing enter.
i want to know:
are the tags retrieved from the database or from a XML file?
is ajax involved?
i am new at front end. if ajax is involved. how should i write the code?
i want it to access a php file which returns the data. but im not familiar with how it works practically.
should the code look something like this:
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
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)
{
document.myForm.time.value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","time.php",true);
xmlhttp.send(null);
}
</script>
<form name="myForm">
Name: <input type="text" name="username" onkeyup="ajaxFunction();" />
Time: <input type="text" name="time" />
</form>
</body>
</html>
how do i send the text the user typed after he released the key to php? and how should i return the values after php has fetched the tags with SELECT. echo?
plz guide me a little. im so confused when front end is involved.
You can actually find that out yourself by using Firebug. You'll notice that typing a letter in the tag textbox will trigger a request to the server.
For example, the entry "C" will give you the following response from the server:
c#|48259
javascript|18318
c++|16999
asp.net-mvc|7224
c|6948
css|6563
The results are then interpreted within SO and then displayed with jQuery.
Using Firebug as you write an answer, you'll also notice that the client sends requests every minute or so:
POST answer-activity-heartbeat
This is also why you get notice that the question you are currently working on has been updated with new answers.
In general, using FireBug will really help you out understand how websites work. I recommend you start using it if you want to see a bit better how SO was conceived.
Regards
Looking at the firebug console, you can see that its sending and receiving data with ajax. Most likely to a script that fetches the data from a database.
You can do this with jQuery pretty easily.
<script type="text/javascript">
$("#username").autocomplete("search.php");
</script>
<form name="myForm">
Name: <input type="text" name="username" id="username" />
Time: <input type="text" name="time" />
</form>
<?php
//search.php
$q = $_GET['q']
$result = $db->query("SELECT username, id FROM users WHERE username LIKE '%$q%'");
while($user = $result->fetch_assoc()){
echo $user['username']."|".$user['id']."\n";
}
You can download the plugin here: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
and jQuery: http://jquery.com
I recommend that if your really need to know how it works take a look to JS documentation, but if what you need is doing if fast, use jquery and read the documentation (or buy a book like jQuery Reference Guide). It really simplifies the way to do AJAX and you could send back from the server anything you want, from JSON to HTML.
BTW, the way to know when a input box value has change to trigger the JS which does the AJAX request is using the onchange event of the input.
Related
Please forgive the basic question, I'm very new to Javascript and web development in general. I want to use a script on one page of my site to programmaticaly press a button to submit a form on another part of the site, making a POST request. The html I have to access is the following:
html
<form action="thing.jsp" method="post"> // Beginning of form
...
<input type="submit" id="submit" value="Do something"> // Button code
...
</form>
And I think the Javascript should look something like this:
JS
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', "/stuff.jsp", true);
var params = "???????"; // What do I need to put here?
xhr.send(params);
</script>
From reading around online, my suspicion is that I may just need to get the right value for params? Though if there's another way of achieving the same result (e.g. by just sending a POST request without doing anything to the button), I'd be perfectly happy to go with that.
Thanks in advance for your time and wisdom.
You don't need to use ajax, just use this:
<input type="button" value="GO" id="buttonId" />
<script>
function go() {
document.location.href = 'http://google.com';
}
document.getElementById('buttonId').onclick = go;
</script>
please notice the button type should be 'button', not 'submit'
Using jQuery - a JS library - you can simply send a HTTP GET Request. This can then be picked up in PHP using $_GET['key'] which will hold the value.
$(function() {
$('#unique-id-btn').click(function() {
$.get('file.php', { key: $('unique-id-input').val() }).done(function(response) {
alert(response);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="unique-id-input" placeholder="enter something...">
<button type="button" id="unique-id-btn">Click me</button>
Note, you will need to create the file.php. Inside, it will control what happens with that data being sent across, ie:
$data = $_GET['key'];
echo $data == "foo" ? "bar" : "tell me foo!";
Also note you can only run PHP in a .php file extension, not JSP.
I am trying to grab text from a text field and then use that to update my db with it. I have tried using session, get, post and cookie to grab the value using php and this doesn't work. I am new to php so I am thinking this comes out blank because it is server side. I did this with javascript and it grabs the value but I am not sure how to use it with php or to update mysql. any help is appreciated. here is some sample code of mine: I have the update on a seperate php page but the input of my text area is not even being grabbed
<?php
function update_db(){
// echo $_POST["comment"];
$nenabled = $_GET['enabled'];
$comments_new = htmlspecialchars($_GET['comment']);
$nemail = $_GET['email'];
echo ("<script>console.log('$comments_new')</script>");
?>
<form method ="get" action ="update_user.php">
<input type="hidden" name = "enabled" value = "nenabled">
<input type="hidden" name = "comments" value = "comments_new">
<input type="hidden" name = "email" value = "nemail">
<input type="submit" >
<script>
function doFunction() {
var com = document.getElementById("comment");
alert(com.value);
// var comment = '<?php update_db(); ?>';
}
</script>
You have something like :-
<input type="hidden" name = "comments" value = "comments_new">
Then how can you expect
document.getElementById("comment");
will work?
You should add the id in your html, like:-
<input type="hidden" id="comment" name = "comments" value = "comments_new">
You won't be able to call a PHP function from inside the javascript function. Once the page is rendered PHP can no longer modify the page since it is a server side language exclusively. There are two common ways to do this however, the first is to wrap your text input in a form and include a submit button that calls a php file with your code to insert the value into your database. There are plenty of good tutorials out there if you google them but http://html.net/tutorials/php/lesson11.php is a pretty good one.
The other way, and the way that sounds like it would work best for you, is to use AJAX to make a call to a php function. You never navigate away from your page and you can handle success and error conditions. AJAX supports GET and POST data to your php file. Again, not reinventing the wheel here is a great AJAX tutorial that spells out using GET and POST, single data, multiple items, return data, etc. http://hayageek.com/jquery-ajax-post/
Hope that helps!
If you want to update your database on submit of the form, then no need to import yout php code within javascript. You just need to send an AJAX request to your php server on submit your form. For the AJAX request you can also use jQuery.
At first you've to modify your html form like:-
<form onsubmit="return false;">
<input type="hidden" id="name" name = "enabled" value = "nenabled"></input>
<input type="hidden" id="comments" name = "comments" value = "comments_new"></input>
<input type="hidden" id="email" name = "email" value = "nemail"></input>
<input type="button" onclick="update()" value="Submit">
</form>
So, on click of the submit button the update function will be called. The update function will take the input values and call another function to send the AJAX request. So I wrote:-
<script type="text/javascript">
function update(){
var data = {
name : document.getElementById("name").value,
comments : document.getElementById("comments").value,
email : document.getElementById('email').value
};
loadXMLDoc(data);
}
//Ajax request function
function loadXMLDoc(data)
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","updateDB.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+data.name+"&comments="+data.comments+"&email="+data.email);
}
</script>
The AJAX request will send a POST request to
your base url + 'updateDB.php'
with data:-
name:nenabled,
comments:comments_new,
email:nemail,
So, now you can do the rest of the thing in the server side php code to update the database.
I have a promotion page. I want that page to can be visited only by users that have a code from me sent by email.
So I have this form:
<form accept-charset="UTF-8" action="promotion.php" method="post" onSubmit="return checkcode(this);">
<input name="code" type="text" id="code" maxlength="15" placeholder="Confirmation Code" required="required" />
<input type="submit" value="Submit" />
</form>
And this Javascript:
function checkcode ( form )
{
var pattern = /name="code" value="|2222|1234|8888|"/g
if (!pattern.test(form.code.value)) {
alert( "The code is incorrect." );
form.code.focus();
return false ;
}
return true ;
}
This javascript code not functioning properly: if I write a bigger code with more characters will redirect; also I can't add many, if the numbers from value line come down when I write more codes/numbers will redirect, I need to add more than 100 codes. Is there any other way to get this to functioning properly? Maybe there is a PHP code that can read the codes from a file and redirect only if the code exist in that file?
And on JSFiddle redirect in any case, the javascript code just doesn't working. But if I upload on my server seems to work, but still has the error that I writed below. http://jsfiddle.net/focusoft/e9DHg/
Do like Akhil Sidharth suggests:
Make AJAX call to PHP page passing the promocode. Do validaton within the PHP and return true or false...
You do not need DB for this.
Oke, first thing, NEVER do validating like this in the javascript. This is visible for everyone! so UNSECURE! :)
How you should do this:
create a database table called codes with fields: code, email(if personal code) and code_active(boolean).
send the code (and email) using AJAX or just post it to the backend.
check in the backend if the code is valid and return true/false.
(if you don't want to use a database, then just hardcode the codes in a php array)
NO DATABASE:
<?php
$a_codes = array(1111,2222,3333,4444,5555);
if(isset($_POST['code'])){
if(in_array($_POST['code'], $a_codes)){
echo "VALID CODE";
}else{
echo "INVALID CODE";
}
}
?>
Please dont do this way, try to put all codes in DB & then using AJAX to validate the code will be a better idea. if validation success try making a changing a hidden input value to something for further population. Using JS like this is a very bad idea as its client side validation. please use server side validation.
check this code, if you use Jquery, it will shorten the code & make it better. I just used plain old simple Ajax.
index.php
<script type="text/javascript">
function GetXmlHttpObject(){
var xmlHttp=null;
try{
xmlHttp=new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function search_code(){
var parameter1= document.getElementById('code').value;
if (xmlHttps1==null){
alert ("Your browser does not support AJAX!");
return;
}
var url="ajax_validate.php?para1="+encodeURIComponent(parameter1)+"&search=search";
xmlHttps1.onreadystatechange=result_search_code;
xmlHttps1.open("GET",url,true);
xmlHttps1.send(null);
}
function result_search_code(){
if (xmlHttps1.readyState==4){
document.getElementById('Promotion_validation_Status').innerHTML="";
document.getElementById('Promotion_validation_Status').innerHTML=xmlHttps1.responseText;
}
}
var xmlHttps1=GetXmlHttpObject();
</script>
<form accept-charset="UTF-8" method="post" onSubmit="return validate()">
<input name="code" type="text" id="code" maxlength="15" placeholder="Confirmation Code" required="required" />
<input type="button" value="Submit" onClick="search_code()" />
</form>
<div id="Promotion_validation_Status" />
ajax_validate.php
<?php
if($_REQUEST['search']=='search'){
$promotion_code=mysql_real_escape_string($_REQUEST['para1']);
$sql="select count(*) from table where feild_name='".$promotion_code;
$res1=mysql_query($sql1);
$res1=mysql_fetch_array($res1);
if($res1['count(*)']>0){
echo "Sucess";
} else {
echo "Validation Failed";
}
}
?>
I think, this should give you an idea. Before you use ajax i will request to validate the format of your code using JS. so it will be easier for you to compare it with DB. This is just a basic outline for you to start this. There are so many things which i havent taken care of.
assuming your code and work, and just want to expand it.
You only need to change your regular expression.
/name="code" value="|2222|1234|8888|"/g
instead of this: |2222|1234|8888|
try this: [0-9]{4}
where: {number} (is the number of characters you admit)
this way you have a rando from 0000-9999 to validate codes.
name="code" value="[0-9]{4}"
I have a textarea in my html page and I wish I could do this:
<textarea id='myTextArea' src='data.txt' />
==============
Unfortunately I can't do that. "src" does not work for a textarea.
So I have to recur to some javascript to make an ajax call (http get for data.txt) and then populate myTextArea.
Is ajax the only way to resolve this ?
Many Thanks
A better option might be to output the content of that file via a server-sided language. Since the content in static, the extra HTTP request isn't really necessary.
In PHP, you could do it like this:
<textarea id='myTextArea'><?php include "data.txt" ?></textarea>
Edit: As Quentin noted, you may want to parse the included file before injecting it into the HTML, especially if the file included can easily be modified by a third party. Functions like htmlspecialchars can be used to validate the file content accordingly:
<textarea id='myTextArea'><?php htmlspecialchars(file_get_contents("data.txt")); ?></textarea>
This should work:
<script>
function loadFile()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","foo.txt",false);
xmlhttp.send();
var value = xmlhttp.responseText;
document.getElementById("myTextarea").value=value;
}
</script>
And html:
<body onload="loadFile()">
<textarea id="myTextarea" cols="20">
</textarea>
</body>
Ok, I am developing a simple program to do xmlhttprequests so I can get a handle on how they work. On that page I have a simple text box, a label, and a button. When the button is clicked it sends out a request to another page via the javascript method, and it stores the response in the label.
(this is all the code in the body)
<form id="form1" runat="server">
<div>
<input type="text" id="text1" value="StuffInTheBox" name="text1"/>
<label id="label1">Please Enter Name.</label>
</div>
</form>
<button id="button1" onclick="checkName(text1.value,'')">BUTTON</button>
This works perfectly in google chrome. But when it came time to try it out in IE7 it gave me an error. It said "Error: 'text1' is undefined". I've been trying to tweak everything I can to see if it makes a difference but now I'm kind of lost.
Any help would be much appreciated
edit: checkname function per request
The method calls loadXMLDoc which creates the xmlhttprequest object, forking the construction for older IE who use ActiveX and modern browers who have it native. It also creates a method to watch the status change, and if it is done successfully it recalls checkname with checkName('',results)
function checkName(input, response)
{
if (response != ''){
// Response mode
message = document.getElementById('label1');
message.innerHTML = response;
}else{
// Input mode
loadXMLDoc("http://localhost/xmlTest/Return.aspx","input="+input);
}
}
In your JavaScript "checkName(text1.value,'')" it is unclear what text1.value is referencing. You're assuming it's referencing the DOM Object you've declared in your HTML and FireFox seems to make that assertion as well however IE doesn't. text1 could have easily been a reference to an object declared earlier in your JavaScript code.
var text1 = {value: ""};
Frankly I'm surprised that FireFox didn't throw an error.
When referring to DOM objects (i.e. HTML elements) you need to use the document.getElementById or document.getElementsByName methods.
The following example was tested and works in both FireFox and IE and I would assume to work in Chrome, Safari and Opera as well.
<form id="form1" runat="server">
<div>
<input type="text" id="text1" value="StuffInTheBox" name="text1"/>
<label id="label1">Please Enter Name.</label>
</div>
</form>
<button id="button1" onclick="checkName(document.getElementById('text1').value,'')">BUTTON</button>
"text1" is the id of the input, but you haven't declared that the text1 variable in the JavaScript refers to that.
Perhaps this will work for you:
<button id="button1" onclick="checkName(document.getElementById('text1').value,'')">BUTTON</button>
It uses document.getElementById to retrieve the input before trying to find its value.