Get Javascript variables to a PHP file using AJAX - php

I am a newbie in web base applications development and Im learning AJAX. Here is my problem, I'm trying to make an AJAX request with some variables (user inputs) and get the php file with the same variables. Below is my code, if there something I am missing or I am doing wrong please let me know, I will appreciated any help! Thank you.
Javascript code:
<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
document.getElementById("Alert").innerHTML= "*Your browser broke!";
document.getElementById("Alert").style.color = '#E00000 ';
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('display');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
var input_building = document.getElementById('building').value;
var input_room = document.getElementById('room').value;
var queryString = "?building=" + input_building + "&room=" + input_room;
ajaxRequest.open("GET", "map.php" + queryString, true);
ajaxRequest.send();
}
</script>
HTML:
<select id="building" name="building">
<option value="#" default >Select</option>
<option value="Luis C. Monzon">Luis C. Monzon</option>
</select>
<input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" >
<input id="submit" type="button" value="submit" onclick="ajaxFunction()" >
<p id="display"></p>
PHP file:
<?php>
$building = $_GET['building'];
$room = $_GET['room'];
echo "<h1>".$room." ".$building."</h1>";
?>

You are setting a value property on a <p> element. You should be setting its innerHTML. Value is used for input fields.
document.getElementById('display').innerHTML = ajaxRequest.responseText;

As requested, I will post my comment
In your code you need to change ajaxDisplay.value to ajaxDisplay.innerHTML - as elaborated by Juan, form fields have values and container tags have innerHTML.
To defend the use of jQuery a little - I basically agree that for simple JavaScript, loading an external library can be overkill - in the case of Ajax, I trust jQuery to cover all browsers needs.
Your code with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>Get building</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() { // run onload
$("ajaxbutton").on("click",function() {
var input_building = $('building').val();
var input_room = $('room').val();
var queryString = "?building=" + input_building + "&room=" + input_room;
$("#display").load("map.php" + queryString); // get the room
});
});
</script>
</head>
<body>
<select id="building" name="building">
<option value="#" default >Select</option>
<option value="Luis C. Monzon">Luis C. Monzon</option>
</select>
<input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" />
<input id="ajaxbutton" type="button" value="Find Building" />
<p id="display"></p>
</body>
</html>
NOTE: for more control over the result you can change the load to
$.get("map.php" + queryString,function(data) {
// do something with data here - for example if you use JSON
$("#display").html(data);
});

Related

Unexpected end of JSON input - Retrieving Data from server issue

I am trying to create a page whereby you can submit some text and then retrieve it on button press, I have managed to get it to submit to my server, however on retrieval I keep getting the error "unexpected end of JSON input" and have no idea what to do about it, my knowledge of PHP/JSON is very limited, any criticism / pointers are greatly appreciated.
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("DataSubmitted");
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var data = JSON.parse(this.responseText);
alert(data);
}
}
xxhttp.open("GET", "gethint2.php", true);
xxhttp.send();
}
PHP/HTML:
<php? session_start(); ?>
<html>
<script type="text/javascript" src="main.js"></script>
<head>
</head>
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
</html>
Sending Data:
<?
$_SESSION["input_data"] = $_POST;
echo $_POST["input"];
?>
Retrieving Data:
<?php
$_SESSION["input_data"] = json_encode($_POST);
?>

how can i change the output of JavaScript to go to directly to another page instead of an alert window?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('yep')
}
}
</script>
</head>
<body>
<form>
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Check My Zipcode"
onclick="IsValidZipCode(this.form.zip.value)" />
</form>
</body>
</html>
I need to use this to allow the user to go either to a page that says sorry we cannot service your area or to another page that says yes we can service your area based on wheter their zipcode is listed.
also how can i add more than one zip code in the isValid = line?
Setting window.location.href = "your url here"; answers the first part of your question.
"also how can i add more than one zip code in the isValid = line?"
If you want to stick with a regex test you can use the regex or |:
var isValid = /^(20132|20133|20200|90210|etc)$/.test(zip);
Note that I've also added ^ and $ to match the beginning and end of the entered string - the way you had it you'd also get matches if the user entered a longer string containing that code, e.g., "abc20132xyz" would match.
I'd be more inclined to do this validation server-side though.
if (isValid)
document.location.href="validzipcode.html";
else {
document.location.href="yep.html";
}
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
document.location.href="valid_zip.html";
else {
document.location.href="not_valid_zip.html";
}
}
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
window.location = baseurl."/valid.php"
else {
window.location = baseurl."/invalid.php"
}
}
</script>
You can redirect it in javascript with following code , that can be put in your example instead of alert()
window.location.href = "http://stackoverflow.com";
You can try ajax for this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function IsValidZipCode(zip){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//alert(ajaxRequest);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//var ajaxDisplay = document.getElementById('ajaxDiv');
//ajaxDisplay.innerHTML = ajaxRequest.responseText;
alert(ajaxRequest.responseText);
if(ajaxRequest.responseText=="")
{
alert("sorry we cannot service your area");
}
else{
window.location = "Page.php?zip="+zip+"";
}
}
}
//var age = document.getElementById('age').value;
//var wpm = document.getElementById('wpm').value;
//var sex = document.getElementById('sex').value;
var queryString = "?zip=" + zip;
ajaxRequest.open("GET", "zip_check.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
</head>
<body>
<form name="form1" method="post">
<input id="txtZip" name="zip" type="text" /><br />
<input type="button" id="Button1" value="Check My Zipcode"
onclick="IsValidZipCode(document.form1.zip.value)" />
</form>
</body>
</html>

submit a form via Ajax and update a result div

I was using a self submitting form to process the data but I now need to process it separately so now I need to submit a form, return the results and place it in a div. It seems using AJAX is a good way to do this to have the data return to the original page where the form is. I have had a look at alot of examples and I don't really understand how to do it or really how its working.
Say I wanted to send this form data from index.php to my process page twitterprocess.php what do I need to do and get it to return to display the data processed.
<form method="POST" action="twitterprocess.php">
Hashtag:<input type="text" name="hashtag" /><br />
<input type="submit" value="Submit hashtag!" />
</form>
This is what I have been using to display the results.
<?php foreach($results as $result) {
$tweet_time = strtotime($result->created_at);?>
<div>
<div class="tweet"> <?php echo displayTweet($result->text),"\r\n"; ?>
<div class="user"><?php echo "<strong>Posted </strong>" . date('j/n/y H:i:s ',$tweet_time) ?><strong> By </strong><a rel="nofollow" href="http://twitter.com/<?php echo $result->from_user ?>"><?php echo $result->from_user ?></a></div>
</div>
<br />
<? } ?>
I'm new to AJAX but any guidance would be greatly appreciated
*When you use AJAX the output generated on other page is the result for this page.
*Now when you want to post data and retrieve results through the use of AJAX then in form part of your html don't use type="submit" for button, but simply go for type="button".
*action attribute should be left blank as you are going to trigger the action through your AJAX code.
*Well rest all your solution in the code snippet below:
Below is the HTML code along with AJAX
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Form Handling Through AJAX</title>
<script type="text/javascript">
function loadXmlDoc(fname, lname){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=" + fname + "&" + "lname=" + lname);
}
</script>
</head>
<body>
<p>
<span id="ajaxify"> </span>
</p>
<form id="frm" action="#">
<input type="text" name="fn" />
<input type="text" name="ln" />
<input type="button" name="submit" value="submit" onclick="loadXmlDoc(fn.value, ln.value)" />
</form>
</body>
</html>
Below is the PHP code that is used in above code
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
echo "Hello " . $fname . " " . $lname;
?>
Assign some id to your submit button, i'd use id="submit" and some id for your text field (i use id="text");
Client-side js:
$("#submit").click(function () {
var postData = new Object(); //for complex-form
postData.hashTag = $("#text").val();
$.ajax({
type: 'POST', //or 'GET' if you need
contentType: "application/json; charset=UTF-8", //i use json here
dataType: "json",
url: "some_url",
data: JSON.stringify(postData), //or smth like param1=...&param2=... etc... if you don't want json
success: function (response) {
//handle response here, do all page updates or show error message due to server-side validation
},
error: function () {
//handle http errors here
}
});
return false; //we don't want browser to do submit
});
So, if user has js enabled = your code will do ajax request, otherwise - regular post request will be made;
On a server-side you have to handle ajax and regular submit different to make it work correct in both cases. I'm not good in php so can't do any advise here
You can use jQuery, for example,
function doPost(formdata){
var url="/twitterprocess.php";
var senddata={'data':formdata};
$.post(url,senddata,function(receiveddata){
dosomethingwithreceiveddata(receiveddata);
}
your php will get senddata in JSON form. You can process and send appropriate response. That response can be handled by dosomethingwithreceiveddata.
I find the Ajax Form plugin a good tool for the job.
http://www.malsup.com/jquery/form/#tab4
A basic code example could be:
$(document).ready(function() { // On Document Ready
var options = {
target: '#output1', // ID of the DOM elment where you want to show the results
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
// the callback function
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
All your PHP file have to do is echo the html (or text) back that you want to show in your DIV after the form has been submitted.
If you do not want to use jquery try this in pure javascript
function SendData(Arg) {
xmlhttp=null;
var uri = "/twitterprocess.php";
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null) {
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
if(xmlhttp.status==200) {
var xmlDoc = xmlhttp.responseXML;
var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue;
var Xml2String;
if(xmlDoc.xml) {
Xml2String = xmlDoc.xml
} else {
Xml2String = new XMLSerializer().serializeToString(xmlDoc);
}
document.getElementById("CellData").value=Xml2String;
} else {
alert("statusText: " + xmlhttp.statusText + "\nHTTP status code: " + xmlhttp.status);
}
}
}
}

How to pass looping data from html page to php page via AJAX

How to send looping data from html page to php page using ajax. I am trying so hard but i don't get any way passing looping data into php page.
order.html page code are described in the below:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age[]').value;
var queryString = "?age=" + age ;
ajaxRequest.open("GET", "example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='age[]' Name='age[]' /> <br />
Name: <input type='text' id='age[]' Name='age[]'/>
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>result will display here</div>
</body>
</html>
example.php page code are described in the below:
<?php
$len = count($_GET['age']);
for($x=0;$x<$len;$x++)
{
echo $service[$x]=$_GET['age'][$x];
}
?>
the [] should be append to the query string, not to the input name
var queryString = "?age[]=" + age1 + "&age[]=" + age2 + "&age[]=" + age3 ;
ajaxRequest.open("GET", "example.php" + queryString, true);

How to get checked radio button value using AJAX in PHP?

I'm going to get the checked radio button value using AJAX in PHP. I have done the following code, but i can't continue.
I need your help.
ajax_radio.php
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" name="radio1">Blue</input>
<input type="radio" name="radio2">White</input>
<input type="radio" name="radio3">Red</input>
<input type="button" name="btn" value="Click" onClick="hello('a')"></input><br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
ajax.js
var xmlHttp;
function GetXmlHttpObject(){
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
try{
xmlHttp = new ActiveXObject(Msxml2.XMLHTTP);
}
catch(e){
try{
xmlHttp = new ActiveXObject(Microsoft.XMLHTTP);
}
catch(e){
alert("doesn't support AJAX");
return false;
}
}
}
}
function hello(a){
GetXmlHttpObject();
xmlHttp.open("GET","ajax_radio.html?",true);
xmlHttp.onreadystatechange = response;
xmlHttp.send(null);
}
function response(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var radio_text = xmlHttp.responseText;
document.getElementById('btn_get').innerHTML = radio_text;
}
}
}
Do you know how to complete this? Thanks in advance. :)
Edit:
I can't post the code here right now, because of the low speed of network. I'm sorry.
I have shared it in rapidshare. Can you download it firstly, and help then? Thanks a lot.
I have to update it when i go back home. Too bad.
because I mostly use Jquery I wrote here a jquery snipped that checks radio button values because it is much easier and cleaner:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.0");
</script>
<script type="text/javascript">
$(function() {
$('#buttoncheck').click(function () {
var var_name = $("input[name='radio1']:checked").val();
$('#btn_get').val(var_name);
});
});
</script>
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" value="Blue" name="radio1">Blue</input>
<input type="radio" value="White" name="radio1">White</input>
<input type="radio" value="Red" name="radio1">Red</input>
<input id="buttoncheck" type="button" name="btn" value="Click"></input>
<br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
Take a look for jquery here: Jquery
Explanation:
This part selects the item with the ID #buttoncheck and checks if its ran: $('#buttoncheck').click(function () {
Then it will run the code in the function. This code gets the value of a input box with the name radio1. the ':checked' makes sure that it only selects the value of the checked radio button:
var var_name = $("input[name='radio1']:checked").val();
And last. This puts the value of the variable into the item with #btn_get as id:
$('#btn_get').val(var_name);

Categories