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.
Related
Here I have a script which help me to get places from google places API. So now I want to store all this into mysql but how? I'm new to mysql and php, and how to store data that I get from google places to database?
What I need to do here? Can someone show me on my example...
How to combine php and javascript;
CODE: http://jsbin.com/AlEVaCa/1
So I need to store data which I got from google:
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
I want to store all place.name,website ... etc. data to mydatabase. How to do that?
Is there any way to store this data?
Use AJAX to send data to PHP file.
Use jQuery $.post()-AJAX method to send data to php file
data = "name="+name+"&place="+website;
$.post('file_to_store.php', data, function(data) {
//Here you can get the output from PHP file which is (data) here
});
Pure javascript way
function loadXMLDoc()
{
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;
}
}
data = "name="+name+"&place="+website;
xmlhttp.open("POST","file_to_store.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
In file_to_store.php receive all data from $_POST[] global array
if(isset($_POST)){
$name = $_POST['name'];
$website = $_POST['website'];
//Do same for all other variables
//Steps to insert Data into Database
//1. Connect to database
//2. Select Database
//3. Generate Database Insert Query
//4. Run mysql Query to insert
// Return appropriate return back to Javascript code - Success or Failure
}
Use serialize($data) then put it into database, use unserialize() after getting data from db.
Addition: this will store raw data, you'll probably need a parser also.
Addition 2: sorry I assumed that you got an array.
Alternative solution if you got non-array data:
you can use base64_encode($raw_data) to store and base64_decode($encoded_data) to use the encoded data coming from SQL.
Fundamentally, your JavaScript program, executing on the client side, does not have direct access to the SQL database on the host. You must use AJAX to issue requests to the host, and the host-side software must be programmed to handle them. Lots(!) of existing tutorials on this subject are already out there ... everywhere.
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);
}
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 !
I want to make it so that new input boxes only appear if information in the previous box is correct, by checking it with a mysql_query can I adapt this code
function show(id){
if(document.getElementById(id+"-link").style.display=="none") {
document.getElementById(id+"-link").style.display="block";
document.getElementById(id+"-input").style.display="block";
}
}
<tr>
<td><input type="text" id="a1" name="em_1"></td>
<td>and</td>
</tr><tr>
<td><input type="text" id="b1-input" name="em_2" style="display:none"></td>
<td><a href="#null" style="display:none" id="b1-link"</a></td>
</tr><tr>
so somewhere in here I need to add :
$userCheck=mysql_query(SELECT email FROM users WHERE name = "em_1")
$row=mysql_num_rows($usercheck)
if($row!==0){"show('b1')";}
or something to that affect, without refreshing the page. Is this possible?
Ajax:
function XMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// xmlhttp.responseText -> return value from php file , so from here you can do your action
}
};
xmlhttp.open("POST","yourfile.php?email={value}",true); // from here send value to check in server side
xmlhttp.send();
}
Php:
if (isset($_POST['email'])){ // which is variable from `yourfile.php?email`
$userCheck=mysql_query("SELECT email FROM users WHERE name = 'em_1'");
$row=mysql_num_rows($usercheck);
if ($row==0){
echo "no";
} else {
echo "yes";
}
}
Pass in yourfile URL of your server side script which checks if email exists or not and return for example yes or no => Then with help of Ajax it will be return in current document
Note: Don't use mysql extension , use mysqli or PDO instead
Yes it is possible, but you need to know how to use ajax or jquery-ajax
which will help you get the data from php to javascript and then appended to html.
You need AJAX to make this work without a refresh. Check out this page on W3Schools:
http://www.w3schools.com/php/php_ajax_database.asp
It's almost exactly what you want, but instead of returning a block of text, just enliven the b1 pieces.
I have a main page, call it Main.php. On this page, is a button that when clicked, sets a div's innerHTML (already on Main.php, called divResults) with the results from Results.php.
When Results.php is called, the returned HTML "These Are The Results" is properly received and set as the contents to divResults on Main.php. However, any javascript from Results.php is not executed. As an example, I attempt to do a simple window.alert. Here is example code:
Main.php link button to begin the action:
<img src="$MyImageSource" onclick=\"ExpandDropdownDiv()\" />
Main.php javascript function ExpandDropdownDiv():
function ExpandDropdownDiv(){
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("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Results.php",true);
xmlhttp.send();
}
Results.php code example:
<script type="text/javascript">
alert("Success");
</script>
These Are The Results
------------------ Edit - Update ------------------
The simple alert, from Results.php is just an example. If I were able to get this to work, I believe I could solve the rest of my problem on my own. However, I noticed a few comments suggesting to just place the alert in Main.php's javascript after i set the div's innerHTML. So, let me explain what I truly want to do with the javascript, after the div is set.
Image 1, shows some normal "Select" html elements, that have been transformed using jquery and the dropdown-check-list extension (.js). When the user clicks the colorful down arrow at the bottom, the div expands, (image 2) and two more "Select" elements are generated within this other .php file... the html is returned, and placed in the div. Thus, i do not need to reload the entire page, and can place the new select dropdowns just beneath the existing ones.
The problem is, to "transform" these normal select elements, there is some javascript that needs to be executed against that HTML:
$(document).ready(function() {
$(".MultiSelect").dropdownchecklist( {firstItemChecksAll: true, maxDropHeight: 300 , searchTextbox: true, width: 100, textFormatFunction: function(options) {
var selectedOptions = options.filter(":selected");
var countOfSelected = selectedOptions.size();
var size = options.size();
switch(countOfSelected) {
case 0: return "All";
case 1: return selectedOptions.text();
/* case size: return "All"; */
default: return countOfSelected + " selected";
}
}
}
);
}
So, somehow I need to be able to execute javascript against the HTML that is generated from this other .php file. And simply calling the above code, after my divs innerHTML is filled, only re-generates the already existing dropdowns, not the two new ones.
Example Images
Here is a good read on understanding what you are doing: Eval embed JavaScript Ajax: YUI style
Making your code work with using eval(); but its not recommend for various reasons:
Let's take your php and modify it like this:
<script type="text/javascript">
function result() {
alert("Success");
}
</script>
These Are The Results
and This is the callback function from AJAX. result(); is not executed because it doesn't get evaluated, and thus does not exist. which is in your case
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
result(); // this function is embedded in the responseText
// and doesn't get evaluated. I.e. it doesn't exist
}
in order for the browser to recognize the result(); you must do an eval(); on all the JavaScript statements with in the script tags that you injected into the div with id divResults:
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
var myDiv = document.getElementById("divResults");
var myscripz = myDiv.getElementsByTagName('script');
for(var i=myscripz.length; i--;){
eval(myscripz[i].innerHTML);
}
result(); //alerts success
}
Easy Way:
The easiest way i would do it is basically remove the JavaScript from the php and display the content, and after callback just do the rest of the JavaScript within the callback function
php:
echo 'These Are The Results';
JavaScript:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
alert('success'); // or whatever else JavaScript you need to do
}
}
try to wrap the javascript code from Result.php in a function and call it after inserting it like :
<script type="text/javascript">
function result() {
alert("Success");
}
</script>
These Are The Results
and
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
if(result) result();
}
Your results.php needs to be something like...
echo 'eval("function results() { alert(\'success\'); }");';
And then call the results function.