Preface: this will eventually expand to a signup sheet, but I am more concerned with getting one portion completed first.
Now you will not be able to connect to my server, but I do need help, or at least an explanation of why this code isn't working. I have been working on this for a week or so, and have found nothing really similar to my problem.
HTML:
<html>
<head>
<script type="text/javascript" src="checking.js"></script>
</head>
<body>
<span id="conTest">
<?php
$con = mysqli_connect("L28-6","turkey","supersecretpassword","stored");
if (mysqli_connect_errno($con))
{
echo"Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "success";
}
?>
</span>
Email: <input type="text" id="email" onkeyup="emailCheck(this.value)"/>
<br/>
<span id="emailError"></span>
</body>
</html>
The main error is somewhere in the js which looks like:
function emailCheck(inputvalue)
{
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var span=document.getElementById("emailError");
if(pattern.test(inputvalue))
{
span.innerHTML="true..checking";
var myRequest = new XMLHttpRequest();
var response = myRequest.reponseText;
myRequest.onreadystatechange = function()
{
if(myRequest.readyState == 4 && myRequest.status == 200)
{
if(response.test(inputvalue))
{
span.innerHTML="already in use";
}
else
{
span.innerHTML="valid";
}
}
myRequest.open("POST", "email.php", true);
myRequest.send();
}
}
else
{
span.innerHTML="not valid email";
}
}
The problem is definitely with the ajax call but here is the php portion (which isn't in working condition yet):
<?php
mysqli_query($con,"select user_email from email");
?>
I know its a lot of code, but I really appreciate any input.
Also here is the page's response when a properly formed email is used:
Email:asdfasdf#yahoo.com
true..checking
so I know for certain it isn't even dropping into the myRequest.readystatechange function, because if it where it should, at least, return "not valid email".
Your ajax request is inside the readystatechange. This means the ajax request will never be called.
try something like :
function emailCheck(inputvalue)
{
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var span=document.getElementById("emailError");
if(pattern.test(inputvalue))
{
span.innerHTML="true..checking";
var myRequest = new XMLHttpRequest();
var response = myRequest.reponseText;
myRequest.onreadystatechange = function()
{
if(myRequest.readyState == 4 && myRequest.status == 200)
{
if(response.test(inputvalue))
{
span.innerHTML="already in use";
}
else
{
span.innerHTML="valid";
}
}
}
myRequest.open("POST", "email.php", true);
myRequest.send();
}
else
{
span.innerHTML="not valid email";
}
}
I can see another issue with your code. The email will be valid even before finish to be filled
something#domain.c will be valid even if i need to informe something#domain.com. Use a button to request the validation
Related
I found this helpful example:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
that shows how to work with data using Ajax. However, the article does not give details about what the PHP file should contain to make the example actually work.
I have tried this:
<?php
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
echo json_encode($computedString);
?>
And variations thereof, to no avail. The result is a message box that says undefined. What should be in the PHP file for this example to make it work?
Here is the HTML page, complete with the JS:
<label>Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function()
{
var userName = document.getElementById("ajaxTextbox").value;
makeRequest('test.php',userName);
};
function makeRequest(url, userName)
{
httpRequest = new XMLHttpRequest();
if (!httpRequest)
{
alert('Giving up - cannot create an XMLHTTP instance.');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('userName=' + encodeURIComponent(userName));
}
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
try
{
var response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
})();
</script>
EDIT:
The alertContents() function was modified as follows:
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
console.log(response);
console.log(httpRequest.responseText);
var response = "default message";
try
{
response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
The first console.log line is line #44 in the script. Rerunning the program and looking in the Console here is what happens:
When
console.log(response);
is commented out this is the result:
ANOTHER EDIT:
The problem does indeed appear to have been in the PHP script. Here is the updated PHP script and the result:
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['computedString' => $computedString];
echo json_encode($array);
A further improvement:
$array = ['userData' => $name, 'computedString' => $computedString];
results in:
Updated:
Based on my understanding with your comments, it looks liek your PHP file is not returning the JSON response. It is returning the text whihc you passed from your form. So your responseText is simple string.
Hence, when you are trying to read it's property, it is undefined. Try the following code now.
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
if(httpRequest.responseText == '')
{
alert('Error in code');
return;
}
alert(httpRequest.responseText);
}
else
{
alert('There was a problem with the request.');
}
}
}
Original:
There is an issue with the variable scope in your code.
var response = JSON.parse(httpRequest.responseText);
Here, you are defining response as a variable inside the try block and then trying to alert outside the block. That is why it is undefined.
Either you should move the alert statement inside the TRY block or define the variable outside.
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
var response = "Some default message";
try
{
response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
I'm working on ajax for the first time and I feel like I'm close to solving this problem but I need some help. I have my webpage file first below, that has an input field for an email address. When the user submits, the ajax doWork() function should be called which creates the request and processes the request. I have fixed the initial issue of the request being created so I'm positive that the correct object has been created based on the browser. My issue is there's no response text being submitted back and no email is created. The goal is for the user to enter the email, then an introductory email sent back to that address, when this is successful, a response string should be submitted back letting the user know that they have successfully been added to the mailing list and the submission has worked. Thanks for any help, it is greatly appreciated.
<?php include('../includes/educateHeader.php');?>
<script type="text/javascript" charset="utf-8" src="ajax.js"></script>
<div class="involve">
<h1>How to Get Involved In OEC</h1>
<span>Want to become more involved in Operation:Educate Children and don't know how? Share your email address with us, like our facebook page, or check out blog out to learn more about how you can join and help children obtain the education they deserve</span><br></br>
<form method="get">
Email: <input type="email" name="email" id="email" required><br></br>
<input type="submit" value="Send" onclick="doWork()">
</form>
</div>
<div id="outputResponse">
</div>
<?php include('../includes/educateFooter.php');?>
So here is the ajax.js file that creates the request and prints out the data recieved from the email.php file
function getHTTPObject() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function setOutput() {
if (httpObject.readyState == 4 && httpObject.status == 200) {
document.getElementById('outputResponse').value = httpObject.responseText;
}
}
function doWork() {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "email.php?email=" + document.getElementById('email').value, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
var httpObject = null;
Lastly here is the email.php script which should accept the ajax request and echo back whether a success has occurred or not.
<?php
if (isset($_GET['email'])) {
$mail = trim($_GET['email']);
$subject = 'Welcome!';
$message = 'Thank you for joining the Operation:Educate Children email list. In the future, we will send you updates about new opportunities to become more involved in the activities that we run here at OEC and you could make a difference on children\'s futures. Thank you and best wishes!';
mail($mail, $subject, $message);
echo 'Success! Thank you for your interest in Operaton:Educate Children. Stay tuned for updates!';
}
?>
First add return false; at the end of your function doWork and change onclick="doWork()" to onclick="return doWork()"
Then also change below line
document.getElementById('outputResponse').value = httpObject.responseText;
to
document.getElementById('outputResponse').innerHTML = httpObject.responseText;
Read this question too :) Setting innerHTML vs. setting value with Javascript
JQuery makes this really easy:
$.ajax({
url:'email.php',
type: "POST",
data: 'email='+$('input[name=email]').val(),
success:function(html) {
$('#mydiv').html(html);
}
});
Or for GET, even easier:
$.ajax({
url:'email.php?email='+$('input[name=email]').val(),
success:function(html) {
$('#mydiv').html(html);
}
});
I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.
I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript.
GetFilenme.php is another file and I am trying to access this from Config.html
PHP :
Getfilename.php
<?php
$dir = 'uploads/';
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file)
{
if ($file!='.' && $file!='..' )
{
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'<br>';
$Counter = $Counter + 1;
}
}
return $filesArray;
?>
This is assuming you download and include the jQuery javascript library:
$(function() {
$.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
});
This should be your PHP (although very insecure):
<?php
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
?>
Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script.
For example, using the Prototype framework's Ajax.Request, say you have an HTML element with id="notice" and you want to update that based on the script's output (a simple "true" or "false" string).
new Ajax.Request('/validate.php', {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText == 'true')
notice.update('Validation successful');
else
notice.update('Validation failed');
}
});
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function CallSomePHP(username, password)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="myPhp.php";
url = url+"?username="+username+"&password="+password;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText); // this will alert "true";
}
}
myphp.php
<?
// Get the values of username and password
$username = $_GET['username'];
$password = $_GET['password'];
echo"true";
?>
You should try JQuery. I send and receive from JS to PHP the following way, assuming this is the form.
<div id="form">
<input type="text" id="email" /><br />
<button id="submit">Submit</button>
</div>
<div id="response">
</div> <!-- load jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>
// put this in script type="text/javascript" tags
$(document).ready(function(){
var emailValue;
$("#submit").click(function(){
// when the user clicks the submit button
// get the value of email and put it in the variable we made above
emailValue=$("#email").val();
/* am going to send a post variable called "email"
* with the value of "emailValue" to a script called receiver.php
*/
$.post('receiver.php',{email:emailValue},function(e){
// "e" is variable that contains the echoed string
// check if it's true or false
if(e=="true")
alert ("valid email");
else
alert("invalid email");
});
});
});
receiver.php
$email=$_POST['email'];
// checkMail is a fictional function that returns a bool
$valid=checkMail($email);
if($valid)
{
// email is valid
echo "true";
}else{
// email is invalid
echo "false";
}
Note: if you are not sending data to the PHP script you should use $.get instead of $.post, it's a little bit faster.
You can also use the JavaScript variable e and load its contents in the response division in your form like this
$("#response").html(e);
This would accomplish the same thing as if you used JQuery's load() function like Coder mentions below.
At the end, do this:
print json_encode($filesArray);
and it will send back a json object, which Javascript can read easily.
If you're just using JavaScript, probably the simplest solution is to include that as a <script> tag.
eg:
<script src="Getfilename.php" type="text/javascript"></script>
Then in your PHP, instead of:
return $filesArray;
have it write some JavaScript.
echo "var result = ".json_encode($filesArray).";";
Your $filesArray value will now be in your javascript as the variable result.
<script>alert(result)</script>
The PHP should be stored on a remote server and called using a scripted HTTP request. Read up on AJAX for details of how this works and how to perform such tasks.
You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output.
If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up.
Something like the following:
function GetHttpObject()
{
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return false;
}
You can get it easily by ajax. Even you can use Jquery to post the value to php and get the ajax response within a single line of code like below.
p['value']=2;//some input value to be posted
$('#data').load('http://example.com/validator.php',p,function(str){} );
html:
<div id="data">
</div>
In this piece of code you are posting p['value'] as 2 to the validator.php and getting the response and load that value to data div in the same page.
In our php code
//get the posted value into some $value
and
if($value==2)
echo 'true I got 2'
else
echo 'I didnot got 2 You posted wrong value';
This will print true I got 2 in the div #data.
This may not be your exact requirement but its very helpful.
I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript.
GetFilenme.php is another file and I am trying to access this from Config.html
PHP :
Getfilename.php
<?php
$dir = 'uploads/';
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file)
{
if ($file!='.' && $file!='..' )
{
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'<br>';
$Counter = $Counter + 1;
}
}
return $filesArray;
?>
This is assuming you download and include the jQuery javascript library:
$(function() {
$.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
});
This should be your PHP (although very insecure):
<?php
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
?>
Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script.
For example, using the Prototype framework's Ajax.Request, say you have an HTML element with id="notice" and you want to update that based on the script's output (a simple "true" or "false" string).
new Ajax.Request('/validate.php', {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText == 'true')
notice.update('Validation successful');
else
notice.update('Validation failed');
}
});
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function CallSomePHP(username, password)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="myPhp.php";
url = url+"?username="+username+"&password="+password;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText); // this will alert "true";
}
}
myphp.php
<?
// Get the values of username and password
$username = $_GET['username'];
$password = $_GET['password'];
echo"true";
?>
You should try JQuery. I send and receive from JS to PHP the following way, assuming this is the form.
<div id="form">
<input type="text" id="email" /><br />
<button id="submit">Submit</button>
</div>
<div id="response">
</div> <!-- load jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>
// put this in script type="text/javascript" tags
$(document).ready(function(){
var emailValue;
$("#submit").click(function(){
// when the user clicks the submit button
// get the value of email and put it in the variable we made above
emailValue=$("#email").val();
/* am going to send a post variable called "email"
* with the value of "emailValue" to a script called receiver.php
*/
$.post('receiver.php',{email:emailValue},function(e){
// "e" is variable that contains the echoed string
// check if it's true or false
if(e=="true")
alert ("valid email");
else
alert("invalid email");
});
});
});
receiver.php
$email=$_POST['email'];
// checkMail is a fictional function that returns a bool
$valid=checkMail($email);
if($valid)
{
// email is valid
echo "true";
}else{
// email is invalid
echo "false";
}
Note: if you are not sending data to the PHP script you should use $.get instead of $.post, it's a little bit faster.
You can also use the JavaScript variable e and load its contents in the response division in your form like this
$("#response").html(e);
This would accomplish the same thing as if you used JQuery's load() function like Coder mentions below.
At the end, do this:
print json_encode($filesArray);
and it will send back a json object, which Javascript can read easily.
If you're just using JavaScript, probably the simplest solution is to include that as a <script> tag.
eg:
<script src="Getfilename.php" type="text/javascript"></script>
Then in your PHP, instead of:
return $filesArray;
have it write some JavaScript.
echo "var result = ".json_encode($filesArray).";";
Your $filesArray value will now be in your javascript as the variable result.
<script>alert(result)</script>
The PHP should be stored on a remote server and called using a scripted HTTP request. Read up on AJAX for details of how this works and how to perform such tasks.
You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output.
If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up.
Something like the following:
function GetHttpObject()
{
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return false;
}
You can get it easily by ajax. Even you can use Jquery to post the value to php and get the ajax response within a single line of code like below.
p['value']=2;//some input value to be posted
$('#data').load('http://example.com/validator.php',p,function(str){} );
html:
<div id="data">
</div>
In this piece of code you are posting p['value'] as 2 to the validator.php and getting the response and load that value to data div in the same page.
In our php code
//get the posted value into some $value
and
if($value==2)
echo 'true I got 2'
else
echo 'I didnot got 2 You posted wrong value';
This will print true I got 2 in the div #data.
This may not be your exact requirement but its very helpful.