I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
Related
I know that this is impossible via PHP supervars, but see this website:
When we navigate on the pages, the title and meta just changes and this affect the facebook too, see:
How he is doing it? I have a ajax navigation system too, and need to set og, but I don't know how to do dinamically as he did.
Just a comment, he have hidden INPUTS with values of the meta:
But I still don't know how he can parse this before the website being rendered.
The URL fragment is NEVER sent to the server. It is used as a reference by the browser. "Traditionally" it is used to scroll to an element with the ID referenced by the fragment, however more recently it has been given some more exotic uses.
In particular, #! is a shebang, and has the meaning that "this page is being loaded by AJAX, but if you load the following relative to the domain, you will get the full page anyway" - this is particularly useful for search engines.
Basically, use AJAX combined with location.hash to get it to work.
it's just some js(jQuery)
<script type="text/javascript">
var current_page = '';
$("a").live("click", function(){
return change_hash(this,1);
});
function change_hash(el,type) {
if(type==1) {
var link = $(el).attr("href");
}
else
{
var link = el;
}
var link_ar = link.split('/#!');
if(link_ar[1]!=undefined) {
if((link_ar[1].length>3)&&(link_ar[1].substr(0,1)=='/')) {
window.location.hash = '#!'+link_ar[1];
return false;
}
else
{
return true;
}
}
else
{
return true;
}
return false;
}
$(function(){
$(window).hashchange( function(){
address = location.hash.replace("#!","");
var skip=false;
if((address.substr(0,1)=='/')&&(address!=current_page)) {
$("#content").html('<div class="content-box"><div class="ajax-loading">carregando...</div></div>');
$("html, body").animate({ scrollTop: 0 }, "slow");
if (address.indexOf(".php") == -1) {
var newaddress = address.replace(/[^a-zA-Z0-9_\.]+/g,"");
if('/'+newaddress!=address) { change_hash('/#!/'+newaddress,2);skip=true; }
address='/PerfilDetalhe.php?user='+newaddress;
}
if(skip==false) {
$.get('http://www.suamusica.com.br'+address, function(htmldata) {
$("#content").html(htmldata);
document.title = $('#metaTitle').val();
$('meta[name=description]').attr('content', $('#metaDescr').val());
$('meta[name=keywords]').attr('content', $('#metaKeywords').val());
$('meta[property="og\\:description"]').attr('content', $('#metaDescr').val());
$('meta[property=og\\:title]').attr('content', $('#metaTitle').val());
$('meta[property=og\\:url]').attr('content', $('#metaURL').val());
$('meta[property=og\\:image]').attr('content', $('#metaImage').val());
$('meta[property=og\\:type]').attr('content', $('#metaType').val());
$('meta[name=DC\\.title]').attr('content', $('#metaTitle').val());
$('meta[name=DC\\.description]').attr('content', $('#metaDescr').val());
$('meta[name=DC\\.subject]').attr('content', $('#metaKeywords').val());
}).fail(function() { $("#content").html('<div class="content-box error-box"><h1>Ooops!</h1><p>A página acessada não existe ou não foi encontrada.</p></div>'); });
current_page = address;
}
$.get('http://www.suamusica.com.br/msg_check.php', function(resp) {
if(resp==1) {
$('#msg-notify').show();
}
else $('#msg-notify').hide();
})
$('.tipsy-s').remove();
}
});
var loc_h_n = window.location.hash.replace("#", "").replace("!", "").replace(".do", ".php")
if(window.location.hash!='#!'+loc_h_n&&window.location.hash!='') {
window.location.hash = '#!'+loc_h_n;
}
$(window).hashchange();
});
</script>
as you can see he returns false on clicks and acts based on the hashtag value
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Call php function from javascript
I understand that php is server side and JavaScript is client side. But I would like to know how to run a PHP method when a JavaScript function is called. Below is my code, I know the error is but how can I perform the php method?
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
<?php Category::addCategory($inCatName)?>
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
Thanks for your help.
Using the Prototype library (www.prototypejs.org):
Javascript:
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var options={
method: 'get',
parameters: 'inCatName='+ele.value,
onSuccess: function(xhr) {
// TODO: Whatever needs to happen on success
alert('it worked');
},
onFailure: function(xhr) {
// TODO: Whatever needs to happen on failure
alert('it failed');
}
};
new Ajax.Request('addCategory.php', options);
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
addCategory.php:
<?php
$inCatName=isset($_REQUEST["inCatName"]) ? $_REQUEST["inCatName"] : null;
Category::addCategory($inCatName);
?>
The idea is that the Javascript sends a GET (or it could be POST) request to the addCategory.php page behind the scenes, passing it whatever info it needs to create the category.
Hopefully this is enough to get you going. There's a lot missing from my code - you'll need to validate the variables addCategory.php receives and perform any other pertinent security checks before letting it anywhere near the database. addCategory.php will also require any include files, etc so that it knows about your Category class. Finally, addCategory.php should really return some form of variable back to the Javascript code that called it so that it knows what the outcome was.
You can use an Ajax request to an endpoint that triggers your PHP and then perform Category::addCategory($inCatName)
With Jquery:
$.ajax({
url: "addCategory.php",
context: document.body,
success: function(){
// whatever you need to do
}
});
This might help. Use ajax to call you php file (categories.php was used in the example). Send a parameter called "function" and set it as "addCategory". In your php file write code to detect if $_GET['function'] is set and also to detect if it is set as "addCategory". If it is, have the code call the function. I also saw that you were trying to pass the $inCatName parameter to the php function. To send this just add it into the url below.
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","categories.php?function=addCategory",true);
xmlhttp.send();
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});
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.