Hi i am trying to send Json via Ajax to PHP using Javascript. The data is sent correctly by index.html when I view it on firebug. It shows Json type with the correct data.
However, it seems that I am unable to read the JSON on php. I am unable to access it using $_POST.
I tried using $_POST['name'] and there is not response.
When i try using $_POST, the response is array.
Can you please help me?
Here is my javascript code.
<html>
<head>
<script type="text/javascript">
//Create Http request depending on browser
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;}
}
// Function to create
var url = "control.php";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
var data=JSON.stringify({"name":"John", "time":"2pm"});
xmlhttp.send(data);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
This is my php code
<?php
include_once('JSON.php');
$json = new Services_JSON();
$value = $json->decode($_POST['name']);
echo $value;
?>
Have been working on this for days and I really appreciate any help that you can offer.
Thank you!
here it's:
print_r($GLOBALS['HTTP_RAW_POST_DATA']);
I think that it needs to parse the whole post first.
<?php
include_once('JSON.php');
$json = new Services_JSON();
$value = $json->decode($_POST);
echo $value;
?>
But also do you need these includes?
http://www.php.net/manual/en/function.json-decode.php
include_once('JSON.php');
$json = new Services_JSON();
can you not just do this?
echo json_decode($_POST)
An even better solution (see here) is use:
$json = json_decode(file_get_contents("php://input"), true) ?: [];
print_r($json);
Related
I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status== 200) {
document.getElementById("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?
Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>
I'm just starting out with AJAX. I'm trying to create a test where I enter some text into a text input box, click a submit button on a form, and have that text display on my page. The immediate error that I am getting is a 404 error ( www.mysite.com/ajaxFunction() ), but I'm sure that there are others yet to be discovered. Can anyone please help me correct this to get me started out with AJAX? I'm spinning my wheels trying to get started. Also, please realize that I am calling a php script since this is what my ultimate goal will require, which is why I'm not just using JavaScript itself. Thanks!
Here is the html:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.action = getFeedback();
}
function getFeedback() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("feedback").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","scripts/handle_feedback.php",true);
xmlhttp.send();
}
//-->
</script>
<div id="leftsidebox"></div>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
</body>
</html>
handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
return $mytext;
?>
EDIT: Here is my latest html code. I made the change to the php (switching 'return' to 'echo')
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.onsubmit = getFeedback;
}
function getFeedback() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("feedback").innerHTML=xmlhttp.responseText;
}
}
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textbox,true);
xmlhttp.send();
}
//-->
</script>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
scripts/handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
This won't do what you're expecting it to do:
document.myform.action = getFeedback();
You're probably expecting it to make it call getFeedback when the form is submitted. That's not actually what happens. When the browser tries to run that code, it will realize: “oh, hey, we're assigning action. But wait, on the right hand side, there's a function call! I've got to evaluate that function call in order to find the return value to set action to!” And so your browser dutifully calls getFeedback immediately. Since getFeedback doesn't return anything, it sets action to undefined. Boy, that was helpful.
If we want a JavaScript function to be called when the form is submitted, setting action is not the right way to do it. So what is the right way? An event listener. The most common way of attaching an event listener is using addEventListener, but since your use case is rather simple, we're going to use a simpler, often neglected way: setting onsubmit:
document.myform.onsubmit = getFeedback;
Note that we do not have parentheses after getFeedback. This is intentional. We want to set onsubmit to the getFeedback function itself, not its return value.
You're also using textbox without defining it. Sure, it exists in the document, but that doesn't mean it's a variable available in the script. To access it, you'll need to first get the element and then get that element's value:
document.getElementById('name').value
Another thing that might be getting you is the same origin policy. Rather than using a complete URL to open, just pass a relative URL:
xmlhttp.open("GET", "something.php" /* ... */, true);
It should be echo not return. return is used in function to return the data.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
Also you have to send the parameter to php file
xmlhttp.open("GET","scripts/handle_feedback.php?textbox=your_value",true);
First point : you missed request parameters from client end.
Send parameters in querystring for GET request.
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textvalue ,true);
for more reference read here.
And second point is :
'return' statement is used with functions/methods. Since you don't have any function here, so instead of that use 'echo' or 'print' statement.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
im quite new to php and javascript but still trying to get my webpage to work.
Im trying to add a 5-star-voting-system to the page which will contact my database and update accordingly.
As you might have noticed my code grammar isnt perfect either.
<div class="first" onmouseover="starmove('-32px')" onmouseout="starnormal()" onclick="rate('harrys','1')">
this is the div that "contacts" the javascript
function rate(id,ratings){
var i=id;
var r=ratings;
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
}
this is the javascript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Namnlös 1</title>
</head>
<body>
<?php
mysql_connect("host", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_set_charset('utf8');
$itemid = ($_GET["id"]);
$rating = ($_GET["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ('$itemid','$rating')";
mysql_query($query);
?>
</body>
</html>
this is my rating.php file (note: the values in mysql_connect is right on actual page, even if not defined here.)
if I just open my php file there will be a row added to mysql so i know its connected properly.
You are passing the values to rating.php as GET but you are fetching it as POST
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
Here, even if you give the method as POST, ?id="+i+"&rating="+r means that id and rating is being passed as GET.
So you cannot access them as
$itemid = ($_POST["id"]);
$rating = ($_POST["rating"]);
You will need to change that to:
$itemid = ($_GET["id"]);
$rating = ($_GET["rating"]);
Also change your query to:
$query = "INSERT INTO ratings(id,rating) VALUES ('".$itemid."','".$rating."')";
EDIT:
I have updated the Javascript code here. Try this:
<script>
function rate(id,ratings)
{
var i=id;
var r=ratings;
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
}
</script>
Changes:
1. There were two braces after:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
The second brace effectively closed the rate() function, so the code after that wasnt doing what it was expected to. So I moved that brace to the end of the code, to wrap the function.
The onreadystatechange function is called AFTER data has been sent to the server in order to track, what is going on with the request. In your code, you were sending the request INSIDE the onreadystatechange, which would never execute, since the request would never get sent..
I changed
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
}
into a simple POST call:
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
I hope this explains everything :)
You should try jQuery for XHTTP Calls. That way, you are sure that all browsers are supported with your code.
Add this to your head section:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Then use this code to make the call to the PHP page:
var i = id;
var r = ratings;
$.get("http://------/rating.php?id="+i+"&rating="+r);
I also noticed you did put "sds" in the "id" field in your query. The "id" field should be an integer. If it is an integer already, that's your problem. Also change $_POST to $_GET. Fixed version:
$itemid = ($_GET["id"]);
$rating = ($_GET["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ($itemid,'$rating')";
Please use jQuery to handle ajax requests. jQuery works cross browser and you can be sure it works.
Also:
$itemid = ($_POST["id"]);
$rating = ($_POST["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ('sds','$rating')";
Is insecure
$itemid = intval($_POST["id"]);
$rating = intval($_POST["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ('sds','$rating')";
is a lot better
First, use relative instead of absolute links if the php file you're trying to request is in the same site:
// Absolute link
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
// Relative link
xmlhttp.open("POST","rating.php?id="+i+"&rating="+r,true);
Then, you're trying to send and retrieve the info via POST, but you're sending the info in a query string (GET):
JS:
xmlhttp.open("GET","rating.php?id="+i+"&rating="+r,true);
PHP:
$itemid = $_GET["id"];
$rating = $_GET["rating"];
Finally, before you insert, use mysql_real_escape_string() or mysqli_real_escape_string(), depending on the MySQL library you're using, to prevent SQL injection in the database and compromise your site:
$itemid = mysql_real_escape_string($_GET["id"]);
$rating = mysql_real_escape_string($_GET["rating"]);
$query = 'INSERT INTO ratings(id,rating) VALUES ('.$itemid.','.$rating.')';
mysql_query($query);
I feel completely out of my depth but I feel so close..
I'm trying to Upload a file using AJAX. I found this tutorial http://blog.new-bamboo.co.uk/2010/7/30/html5-powered-ajax-file-uploads and it seemed to be going quite well until the end. I can't seem to access the file in PHP i.e. using $_FILES["foo"]["name"];
and I'm not sure how to upload using other techniques.
I'm not looking for the code to be perfect, just kept simple so I can understand what's going on. Thanks in advance :-)
Here is my server side code:
HTML:
page title
</head>
<body>
<form onsubmit='showUser(); return false;' enctype='multipart/form-data'>
<input id='the-file' name='file' type='file' />
<input type='submit'>
</form>
<br />
<div id='txtHint'><b></b></div>
</body>
Javascript:
function showUser(str)
{
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var foo = file.fileName;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","new_film_pro.php",true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.setRequestHeader("X-File-Type", file.type);
xmlhttp.setRequestHeader("X-File-Name", foo);
xmlhttp.send(file);
}
PHP:
<?php
$postdata = file_get_contents("php://input");
echo "Name: " . $_SERVER['HTTP_X_FILE_NAME'] . "<br />";
?>
Have a look at http://aquantum-demo.appspot.com/file-upload
Writing straight JavaScript is no longer such a great idea. Using libraries as demonstrated on that page, you can create a much more powerful file upload which supports multiple files, resumeable downloads, progress bar and many other features that you would really have to sweat to implement yourself but which give your user a better experience.
I am not sure.but on form tag you have not specified method
You may use file_get_contents('php://input') to get the file content.