This question already has answers here:
Reading JSON POST using PHP
(3 answers)
Closed 7 years ago.
I'm able to send JSON Data to server through Ajax as i can see it in params of My Browser Developer Tool => Network but i get No Response Even if try to Print $_REQUEST, $_POST I get just the Cookie Value but not data which I have send
I'm Following From MDN https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Here what I've tried, I'm trying to send data to server without jQuery Ajax method
After I do this on Server side
echo json_encode($_REQUEST['msgData']);
I get
Notice: Undefined index: msgData in
/path/to/url/ABC/controller/msgNotify.php
on line 24 null
jQuery(document).ready(function(){
jQuery('#msgNotify').on('click',function(){
alert("He");
var data={};
data['info']='msgNotify';
data['username']=username;
var msgData={'msgData':data};
makeRequest(msgData,'../controller/msgNotify.php');
});
});
function makeRequest(data,url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
httpRequest.onload = alertContents;
httpRequest.send(JSON.stringify(data));
}
function alertContents() {
try{
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}catch(e){
alert('Caught Exception: ' + e.description);
}
}
SERVER SIDE "../controller/msgNotify.php"
echo json_encode($_REQUEST['msgData']);
exit;
Without changing the way you are doing your POST (the JSON is in the body of the http request), you should read as follows
// extract from my Servlet class :
$content = file_get_contents('php://input');
$ary = json_decode($content , true); // prefer decoding to associative array
if ($content && !$ary) {
self::logResponseStatus('Received malformed JSON', api_request_status::MALFORMED_REQUEST);
return false;
}
$command = $ary['command'];
$apiKey = $ary['apiKey'];
// ... etc
You are sending your data as JSON string without key for getting this parametar in your request.
You could try with this:
httpRequest.send("msgData=" + JSON.stringify(data));
Your msgData will be key to getting your object {'msgData':data}. Since it's already a JSON string you don't need to use json_encode in php. If you want only to display "data" from received json you can use
$data = json_decode( $_REQUEST['msgData'] )
echo json_encode($data["msgData"]);
Related
I just started studying PHP and Ajax and I can't figure out how to bring a single variable from PHP file to my html file using Ajax. Can you please explain me how it works?
So far I understood that you create the request:
var xhttp = new XMLHttpRequest();
And that you send it to the server:
xhttp.open("GET", "demo_get.php", true);
xhttp.send();
Then you get the data from the PHP file using
xhttp.responseText
Now, I only want to send a variable from the server, for example
$name = "John"
How should my php code look like in order to send only that specific variable?
As a beginner, it would be a lot easier to use jQuery for your AJAX requests. I've been in this industry for over half my life and I still use it alot.
getstuff.php
header('Content-type: application/json');
echo json_encode(["FirstName" => "John"]);
exit;
jquery:
$.ajax({
url: '/getstuff.php',
success: function (response) {
console.log(response);
alert(response.FirstName);
}
});
I suggest using JSON as data interchange format, here is the javascript part:
let request = new XMLHttpRequest();
request.open('GET', 'demo_get.php', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success
let parsed_response = JSON.parse(this.response.trim());
console.log(parsed_response.my_var);
} else {
// Error
console.log(this.response);
}
};
request.onerror = function() {
console.log('Connection error!');
};
request.send();
The PHP part then would look like this:
<?php
header('Content-Type: application/json');
$my_response_data = ['my_var' => 'foo'];
echo json_encode($my_response_data);
exit;
... and some useful info about XMLHttpRequest.responseText vs XMLHttpRequest.response
I'm trying to parse a string from a noSQL database. With difficulty.
when you access the PHP file it gives a result like this:
[{"timestamp":"2016-11-07T09:48:30.335Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:29.015Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:27.688Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:27.085Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:26.577Z","Id":"d7ee735f16b5"}]
The same result is given in the network of the console.
When I then attempt to stringify the response it shows null.
Please can anyone help me access the timestamp values. Here is the current code:
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.responseType = 'json';
ajax.send();
var jsonResponse = JSON.stringify(ajax.response);
document.getElementById('demo').innerHTML = jsonResponse;
Most likely the response hasn't returned from the server yet in this example. Also verify that an element with an id of 'demo' does in fact exist in your html document.
Add event listeners to the ajax object:
ajax.onload = loadCompleted;
ajax.onerror = onLoadError;
then create a function to handle the result:
var jsonResponse = JSON.stringify(ajax.response);
document.getElementById('demo').innerHTML = jsonResponse;
Full example (updated per Bozidar's comments):
var url = 'https://jsonplaceholder.typicode.com/posts/1';
function loadCompleted() {
console.log(ajax.response)
var jsonResponse = JSON.stringify(ajax.response);
document.getElementById('demo').innerHTML = jsonResponse;
}
function onLoadError() {
//handle error logic
}
var ajax = new XMLHttpRequest();
ajax.onload = loadCompleted;
ajax.onerror = onLoadError;
ajax.open("GET", url, true);
ajax.responseType = 'json';
ajax.send();
See https://jsfiddle.net/px3mxa4n/ for a working example.
Shouldn't you wait for response before continuing with your code? Something like:
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
// do what you need like
var jsonResponse = JSON.stringify(ajax.response); // maybe JSON.parse and then iterate trough array of objects to create individual HTML elements?
// .......
}
}
I have two domains, leobee.com and txtease.com. I'd like to load a xml script from leobee.com into a php page on txtease.com. I was able to get the information to create the script below by researching stackoverflow site, However, I did not see how to fix this issue.
I've added php headers to the requesting script, and I'm getting "Origin is not allowed by Access-Control-Allow-Origin" error.
Can you look at my script and let me know where I went wrong? The test script is live at:
http://txtease.com/crossdomain/scripts/example.html
in the chrome/ or firebug console use this:
createCORSRequest('GET', 'http://www.leobee.com/crossdomain/data/data.xml');
PHP script:
<?php
echo "PHP Running";
header('Access-Control-Allow-Origin: http://www.leobee.com');
?>
<script>
var xhr = new window.XMLHttpRequest();
var string;
function createCORSRequest(method, url) {
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
xhr.send(null);
string ="with Credentials";
xhr.onerror = function() {console.log('There was an error!')};
xhr.onreadystatechange = callbackFunction(string);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
xhr.send(null);
string ="x domain request";
xhr.onreadystatechange = callbackFunction(string);
} else if(!"withCredentials" in xhr){
xhr.open(method, url, true);
xhr.send(null);
string ="with no Credentials";
xhr.onreadystatechange = callbackFunction(string);
}else {
// Otherwise, CORS is not supported by the browser.
alert("cross domain not supported");
xhr = null;
}
return xhr;
}
function callbackFunction(string){
console.log("Responding function: "+string);
if (xhr.readyState == 4){
var responseText = xhr.responseXML;
console.log("xml string is: "+responseText);
if (xhr.responseXML ===null){
responseText=xhr.responseText;
console.log("html string is: "+responseText);
}
}
}
</script>
You are giving pages with the origin http://www.leobee.com permission to read data from http://txtease.com/scriptExample.php, but you need it to be the other way around.
The permission to read data has to come from the site that the data is coming from. A site can't grant itself permission to read data from arbitrary sites.
Also echo "PHP Running"; will output content. You can't call header after you have output content.
I'm working on a project at school for my data mining class and I want to use the stackoverflow API to obtain the raw data. I was looking at a little introduction tutorial about using PHP to access it and the first code example wasn't working at all. The culprit was the json_decode function. The version of PHP installed on the school server is 5.1.6 and the function only exists >= 5.2. Searching here I found about using pear but the school's PHP is configured with '--without-pear'
What are my best options for getting around these limitations. I'd rather not have to switch entirely to a separate language. Is it possible to make a call to an external function in another language?
The offending line was
$response = json_decode(http_inflate(file_get_contents($url)));
You can install PEAR libraries without using the PEAR installation process. Just download the file from the PEAR website (Services_JSON) and include it manually.
You could simply use the JSON support directly from PEAR, it has no dependancies on other PEAR libraries. I believe all you would need is JSON.php
I too was in situation when I wanted to code using JSON but on the server was only PHP v 5.1.6. After couple of hours trying, I found that all I had to do was to simply include JSON.php from my PHP script and slightly alter my AJAX function (originally got it somewhere from the web - not my work).
Here are both files, hope it saves somebody some nerves.
java.js
var request;
function runAjax (JSONString, phpScript, cfunc) {
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
request = false;
}
}
}
request.onreadystatechange = cfunc;
request.open("POST", phpScript);
request.setRequestHeader("Content-type", "application/json", true);
request.send(JSONString);
}
function smazVzor (id) {
var JSONObject = new Object;
JSONObject.id = id;
JSONString = JSON.stringify(JSONObject);
runAjax(JSONString, "./ajax/smaz_vzor.php", function () {
if (request.readyState == 4) {
var JSONObject = JSON.parse(request.responseText);
alert(JSONObject.zprava);
if (JSONObject.kod == 1) document.location.href = "./index.php";
}
});
}
smaz_vzor.php
<?php
require("../../include/dbconnect.php"); // just some commands for MySQL
require('../../include/JSON/JSON.php'); // <-- THIS IS IMPORTANT
$json = new Services_JSON(); // create a new instance of Services_JSON class
$str_json = file_get_contents('php://input'); // read fiel send by POST method as text
$decoded = $json->decode($str_json); // decode JSON string to PHP object
$sql = "DELETE FROM Obory_vzory WHERE id = '$decoded->id'";
$response = array(); // create response array
if (!mysql_query($sql, $pripojeni)) {
$response['kod'] = 0;
$response['zprava'] = "Something got wrong.\nError: ".mysql_error();
} else {
$response['kod'] = 1;
$response['zprava'] = "Operation successful.";
}
$encoded = $json->encode($response); // encode array $json to JSON string
die($encoded); // send response back to java and end script execution
?>
HI,
I am using the following code
request.js
var request;
function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = new XMLHttpRequest();
request.open("GET", "request.php?json="+JSONstring, true);
request.onreadystatechange = sendData;
alert('called');
request.send(null);
}
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
try
{
//var JSONobject = eval('(' + JSONtext + ')');
var JSONobject = JSON.parse(JSONtext);
}
catch(e)
{
var err="Error: "+e.description;
alert(err);
}
alert('1');
// notice how variables are used
try {
var msg = "Number of errors: "+JSONobject.errorsNum+ "\n- "+JSONobject.error[0]+ "\n- "+JSONobject.error[1];
alert(msg);
}
catch(ee)
{
var errr="Error: "+ee.description;
alert(errr);
}
}
}
The php function I have used here is request.php
<?php
// decode JSON string to PHP object
$decoded = json_decode($_GET['json']);
// do something with data here
echo "Decoded string - ". $decoded;
// create response object
$json = array();
$json['errorsNum'] = 2;
$json['error'] = array();
$json['error'][] = 'Wrong email!';
$json['error'][] = 'Wrong hobby!';
// encode array $json to JSON string
$encoded = json_encode($json);
// send response back to index.html
// and end script execution
die($encoded);
?>
I'm calling this JavaScript function from a HTML page request.html
<html>
<head>
<script src="request.js">
</script>
</head>
<body>
call<br>
</body>
</html>
The problem here is I was getting Syntax Error at the line:24
var JSONobject = JSON.parse(JSONtext);
if I was using
var JSONobject = eval('(' + JSONtext + ')');
I was getting " ) Expected Error "
After that I deleted browser cache. Restarted the browser, now the code seems working very fine.
You should verify JSON format, then look up there - http://ru.wikipedia.org/wiki/JSON. You can get an idea.