PHP return empty json string? - php

My html page sends an ajax request (POST) to PHP, PHP echo a json object.
Code has been tested and worked fine at my development view.
However, after they are uploaded to a VPS hosting server, the returned json string is empty (I used alert() at the response function to display the responseText and found out it was empty).
any idea about the problem?
I am new here. I have not figured out how to add a comment. (Please let me know.)
I changed the PHP code to return a string, it worked. so the problem is after json encoding.
new test.php (worked).
if(!isset($_POST['A'])||!isset($_POST['B']))
{
echo "Failed";
}
else
{
echo "OK";
}
HTML:
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
var NORMAL_STATE = 4;
function ajax_create_http()
{
var xmlHttp = 0;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return 0;
}
}
}
return xmlHttp;
}
var http_req_inst = ajax_create_http();
function sendHttpRequest(params)
{
if( !http_req_inst ) return;
http_req_inst.open('POST', 'test.php', true);
http_req_inst.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_req_inst.onreadystatechange = handleHttpResponse;
http_req_inst.send(params);
alert("Request sent");
}
function handleHttpResponse()
{
if( !http_req_inst ) return;
if (http_req_inst.readyState == NORMAL_STATE)
{
alert(http_req_inst.responseText);
}
}
</script>
</head>
<body>
<div>
<input type="button" value="click" onclick="sendHttpRequest('A=a&B=b')"/>
</div>
</body>
</html>
PHP:
<?php
if(!isset($_POST['A'])||!isset($_POST['B']))
{
$rc = 1;
$arr = array ('rc'=>(integer)$rc,'msg'=>'Testing failed.');
echo json_encode($arr);
}
else
{
$rc = 0;
$arr = array ('rc'=>(integer)$rc,'msg'=>'Testing passed.');
echo json_encode($arr);
}
?>
When I tested, the responseText is empty.

Just check the php configuration on both machines. Like on my machine $text will work on my provider I have to write like $_GET['text'] due to security settings. The PHP configuration will give you an idea of what's wrong, or what packages need to be installed.

Related

Validating with Ajax

I wrote some ajax code that sends values to a php file for validation but I have a problem with it. This is my ajax code:
<html>
<body>
<style>
#displayDiv{
background-color: #ffeeaa;
width: 200;
}
</style>
<script type="text/javascript">
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById("displayDiv").innerHTML=httpxml.responseText;
}
}
var url="username_exists.php?username=";
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<input type="text"
onkeyup="ajaxFunction(this.value);" name="username" /><div id="displayDiv"></div>
</body>
</html>
and the above code send values to username_exists.php :
<?php
$username = trim($_REQUEST['username']);
if (usernameExists($username)) {
echo '<span style="color:red";>Username Taken</span>';
}
else {
echo '<span style="color:green;">Username Available</span>';
}
function usernameExists($input) {
// in production use we would look up the username in
// our database, but for this example, we'll just check
// to see if its in an array of preset usernames.
$name_array = array ('k','steve', 'jon', 'george', 'admin');
if (in_array($input, $name_array)) {
return true;
}
else {
return false;
}
}
?>
My problem is that when any username is put in the textbox returns "Username Available"! What did I do wrong?
You are sending an empty string as username to check thru your ajax call.
var url="username_exists.php?username=";
I would suggest you to start using jQuery to help you in handling this case.You don't need to worry about the cross browser issue and you dont need to write all these lines of code.
jQuery is a wonderful javascript library. http://www.jquery.com
Include jquery library (i will use the CDN Version) in your head section of HTML document and change your code like this.
HTML
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id=txtUserName" />
</body>
javascript
$("#txtUserName").keyUp(function(){
if($("#txtUserName").val()!="")
{
$.ajax({
url: 'username_exist.php?username'+$("#txtUserName").val(),
success: function(data) {
alert(data);
}
});
}
}

How to create a JSON rest webservice in php without using any library?

I want to create a hello world json rest webservice in test.php:
<?php header("Content-type: application/json; charset=utf-8");
$test[] = "hello";
$test[] = "world";
$json = json_encode($test);
echo $json;
?>
But nothing is returned when I test it with ajax below why ?
<html>
<head>
<script>
function test()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
alert(xhr.responseText);
else
alert("Error code " + xhr.status);
}
};
xhr.open(GET, "test.php", true);
xhr.send(null);
}
</script>
</head>
<body>
<script>
test();
</script>
</body>
</html>
You have spaces before your PHP code starts, so the header call will error
You're setting a text/html Content-Type for JSON data, it should be application/json
You are are replacing the reference to the input element in the form with a string, you probably want to set it's .value property instead. (For that matter, you should probably be accessing it as document.forms.id_of_form.elements.dyn.value for clarity) (Using an input to display output is a rather dubious practice in the first place though)

Call php from javascript and return an array from php to Javascript function

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.

How to pass value from JavaScript to PHP and get return of PHP back to JavaScript [duplicate]

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.

Unable to call javascript from PHP

On the click of a button this Javascript is called:
var xmlhttp;
function register()
{
xmlhttp=GetXmlHttpObject();
alert("pass");
if(xmlhttp==null)
{
alert("Your browser does not support AJAX!");
return;
}
var url="register.php";
url=url+"?id="+uniqueid+"&name="+name+"&passwrd="+passwrd1+"&email="+email;
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
//alert("statechanged function");
if(xmlhttp.readyState==4)
{
//alert(xmlhttp.responseText);
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function testing()
{
document.getElementById("mainbody").innerHTML="This is my first JavaScript!";
}
And then this PHP script is called:
<?php
echo "<script type=\"text/javascript\">testing();</script>";
?>
The HTML has two DIV tags with IDs of mainbody and response:
<HTML>
<HEAD>
<SCRIPT SRC=javascriptname.js></SCRIPT>
</HEAD>
<BODY>
<DIV ID=mainbody>
<DIV ID=response>
</DIV>
</DIV>
</BODY>
</HTML>
I am unable to call the javascript from my php.
If anyone know what I am doing wrong or has an idea what I should do, it will be very helpful.
I don't think changing the innerHTML of an object and inserting a script will cause it to fire. I certainly wouldn't want to depend on that behavior.
Why not just do some kind of string comparison on the responseText, (in a case statement, for example) and then call the appropriate function?
EDIT: You could also remove the script tags, and call eval on the responseText, but eval is not the nicest function in the world.
I've successfully done this by passing the script tags within the string
Example:
<?php
function outputResults($var1)
{
$jsStringOut = "
<script type='text/javascript'>
document.write('".$var1."');
</script>
";
return $jsStringOut;
}
echo outputResults("Hello Stackers");
?>

Categories