I have some html pages about movies, all containing the same search form. When the user types something in the form, I want the site to jump to movies-overview page. I already made a search function without ajax, but with a simple post request that searches the database en echos a movielist. But now I want the same to happen everytime a user presses a key.
this is the search form:
<form action='films.php' method='post'>
<input id="ZoekBalkSearch" type="search" name="zoekparameter" placeholder="Geef een zoekterm in." onkeyup="gaNaarFilm(this.value)"/>
<input id="ZoekButton" type="submit" value="Zoek"/>
</form>
and this is my ajax code:
function gaNaarFilm(str)
{
if (str.length==0)
{
document.getElementById("ZoekBalkSearch").innerHTML='';
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("ZoekBalkSearch").innerHTML=str;
}
}
xmlhttp.open("POST",'films.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('zoekparameter='+str);
}
the function is called but it doesn't seem to do anything, could someone please help me? thanks in advance.
fist of all you pass this and not this.value
then a short function i use for ajax is this
var ajax=function(a,b,c){c=new XMLHttpRequest;c.open('GET',a);c.onload=b;c.send()}
this has low support (no ie5 and ie6) but can be extended.
then as u lauche the code directly from your element you can access your value directly inside the ajax.
so:
JS
FormData() stores the whole content of your form
the ajax() function posts to film.php
in film.php u can retrieve the value with $_POST['zoekparameter']
the response executes fu()
this is done by adding a eventListener in javascript to the input field which is keyup.
var ajax=function(){
var fd=new FormData(document.querySelector('#form'));
var c=new XMLHttpRequest||new ActiveXObject("Microsoft.XMLHTTP");
c.open('POST','film.php');
c.onload=fu;
c.send(fd)
},
fu=function(){
document.getElementById("ZoekBalkSearch").innerHTML=this.response;
}
window.onload=function(){
var i=document.querySelector('#form').childNodes[0];
i.addEventListener('keyup',ajax,false)
}
as u can see no need for extra id's, lots of code or passing each input field to a variable in this case every function can access everything without passing parameters... and so it's
easier to modify the code later...
html
<form id="form"><input type="search" name="zoekparameter" placeholder="Geef een zoekterm in."></form>
if you wanna add more fields like year or whatever you just have to add a input and a name
<input type="text" name="year">
you don't need to edit the javascript as FormData does everything for you.
if you don't understand something ask ...
if wanna check compatibility
use caniuse.com
http://caniuse.com/xhr2
http://caniuse.com/queryselector
bonus
shortest way
window.onload=function(){
var s=function(){
var a=new XMLHttpRequest;
a.open('POST','film.php');
a.onload=function(){console.log(this.response)};
a.send('zoekparameter='+i.value);
},
i=document.createElement('input');
i.type='search';
i.addEventListener('keyup',s,false);
document.body.appendChild(i);
}
Related
I just built a web site by using this script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function loadpage(page)
{
document.getElementById("pageContent").innerHTML="Yükleniyor...";
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("pageContent").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",page,true);
xmlhttp.send();
}
</script>
It can load any page thanks to AJAX. But yet there is a question: when I load any page containing any HTML form, when i click "submit", it leaves the main page, I mean I can't send form variables by AJAX. the only thing I need is to pass form variables by using "href" and the loadpage() function I mentioned above.
How can I do get form input's values and send to another PHP file?
you can use jQuery.
$(document).ready(function(){
$("#div_load").load("page.html");
});
whit this code you can open any page (Ex: page.html) in any div(Ex:div whit id=div_load).
and for sending data use it:
$(".class_div").click(function(){
$.post("ajax.php",
{
name:"naser",
age:"23"
},
function(data,status){
// do something when done
});
});
As you are using jQuery, you can do:
$('form').submit(funciton() {
var data = $(this).serialize();
// Call Ajax
return false;
});
I advice you to read about:
http://api.jquery.com/category/ajax/ and http://api.jquery.com/serialize/.
I have been working on this code for a while and I am finally stumped and cannot figure out what the heck to do to get this issue fixed.
I have a jquery code that works beautifully for the get profile, but when i need to return the values in a div, it only shows the first profile of the user, but if a user posts more then once on the blog, it will not show the profile information. I have tried to append more information for each profile div to be different, but its still not working.
Here is the jQuery code for the GET user profile and return response.
function showUser(str)
{
var profileDiv = document.getElementById("profile_"+ 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)
{
profileDiv.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
Also here is the PHP script that i am using to pass the information
"<div id=\"info\" onmouseover=\"showUser(" .$blogrow['id_user'].")\"><imgalign= \"left\" style=\"vertical-align:top;\" class=\"imgb\" height=\"41\" width=\"41\" src=\"profilepics/".$blogrow['pic']."\" />".$blogrow['author']." <br>".$blogrow['timestamp']."<br></div><br>";
echo "</div>";
here is the div part as well that stores the information
echo "<div id=\"txtHint\"><div id=\"profile_".$blogrow['id_user']."\"></div></div>";
The problem relies on your HTML markup, which is invalid. Element ids must be unique in a HTML page but I see a lot of repeated ids such as #info, #theDiv, #txtHint and #profile_X
A quick fix for your problem would be to change all those and any other repeating ids to a class and then use the ajax code provided by #Rohan Kumar but using a class selector to append the content to every mention of the user in the page
function showUser(str)
{
$.ajax({
url:'getuser.php',
data:{q:str},
type:'GET',
success:function(data){
$(".profile_"+ str).html(data);
}
});
}
This is definitely not the most efficient or elegant solution but I think it would work. If you were to try and improve your code I would suggest binding all divs of class .info to a mouseenter handler, using data-attributes to get the user id and maybe maintaining a list of the profiles retrieved so you don't end up making redundant calls to your php
Using $.ajax it will more simple like,
function showUser(str)
{
$.ajax({
url:'getuser.php',
data:{q:str},
type:'GET',
success:function(data){
$("#profile_"+ str).html(data);
}
});
}
But, before this you need to add any version of jQuery
I have a script which uses AJAX to connect to a PHP script which queries a database and returns some values. The code of which is below:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxphp.php?ID="+str,true);
xmlhttp.send();
}
</script>
<select id="users" name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<!-- PHP populates this dropdown box -->
</select>
<div id="txtHint"><b>Selected user info will be listed here.</b></div>
Right now the txtHint div will return anything the ajaxphp.php script prints. This isn't very flexible, however. What I want to do is create an array in ajaxphp.php and use json_encode() to pass the results back.
The problem I'm having is I don't know how to get the original script to grab the results so I can do useful things with them. Right now I can make it return a JSON array which will appear in the txtHint div but I've no idea how to get PHP to actually read that information so I can do something with it.
Try using jQuery Ajax...
$.ajax({
url : 'ajaxphp.php?ID='+str,
type: 'get',
dataType:'json',
success : function(data) {
console.log(data);
}
});
Data in success function parameter is your encoded result that you return from php.
echo json_encode($result);
Then you can access it with something like this from javascript.
data.result1
data.result2
data.result3....
Use $_GET method to See what ever the user send you in php see here:
http://php.net/manual/en/reserved.variables.request.php
Maybe the json_decode() php method is the solution of what you want.
http://www.php.net/manual/en/function.json-decode.php
This method takes a JSON encoded string (from the json_encode method for example) and converts it into a PHP variable... so you can use this variable like an object and simply access to its attributes.
Maybe this other post will help you : How to decode a JSON String with several objects in PHP?
Hope this helps ! Bye !
trying to insert a record in my DB using AJAX for the very first time. I have the following...
Form
<form>
<input type="text" id="salary" name="salary">
<input type="button" onclick="insertSalary()">
</form>
AJAX
<script type="text/javascript">
function insertSalary()
{
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('current-salary').innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}
</script>
PHP
$uid = $_SESSION['oauth_id'];
$monthly_income = mysql_real_escape_string($_POST['salary']);
#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
Nowmy data is being inserted into the table BESIDES the 'salary' which is being inputted as '0'
Once inserted I also have a div 'current-salary' that should then be populated with there inputted value only it isnt, Can anybody help me to understand where im going wrong?
If you want to save your self a lot of time, effort, and heartache, use the jquery library for your ajax requests. You can download it at http://jquery.com/
After adding a reference(Script tag) to the jquery script your javascript for the ajax request would become:
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert_salary.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
Also keep in mind that using "insert_salary.php" as the url means it is a relative path and must be in the folder of the current running script.
Your php script needs to echo whatever you would like to be injected into your current-salary tag also.
I have a very simple form.I want to insert the form data in mysql database.using ajax.
I need to pick data from form and send them as xml to the server.
the form is as :
<form>
Name:<input type="text" id=name/>
Contact<input type="text" id=contact/>
</form>
And i am picking the data from my form using js as :
function GetData(form)
{
var name=document.getelementbyid('name');
vat contact=document.getelementbyid('contact');
}
function Ajax
{
" Here i want to send the form datas as an xml to the server"
}
Can any one help me how to do this .And also how to receive the the request from server as xml and insert to database.
Just give me the proper way.Not Query string or json or jquery.I want to use xml using ajax
Thanks,
function GetData(form)
{
var name=document.getelementbyid('name');
var contact=document.getelementbyid('contact');
Ajax(name,contact);
}
function Ajax(name,contact)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;
}
}
//var datas='?name='+name+'&contact='+contact;
var xmlval='<name>'+name+'</name><contact>'+contact+'</contact>';
var datas='?xmlvalue='+xmlval;
xmlhttp.open("GET",'phpfile.php'+datas,true);
xmlhttp.send();
}
Important question: Why do you need XML to submit?
Also, to use XML, look up SimpleXML, and to save to database, there are a lot tutorials.
Update: if you meant the response as XML? That's just like the same as in JS. And to use it in JS, look at this. However, in that case, uncomment the commented line and comment the next 2.