Hi I am trying to create AJAX call via POST method with JSON. I do not want to use jQuery. Here's my javascript code:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "index.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
console.log(xhttp.responseText);
}
}
var data = "POSTdata=" + JSON.stringify({ data1 : 9, data2 : 4, data3 : 87});
xhttp.send(data);
And here's my PHP code:
if(isset($_POST['POSTdata']))
{
$version = json_decode($_POST['POSTdata']);
print_r($version);
}
else
{
echo "failure";
}
The print_r output is something like that:
stdClass Object
(
[data1] => 9
[data2] => 4
[data3] => 87
)
So simply i just don't know how to "reach" that data to use it. Could anyone help me?
Related
I have this in PHP
$invalid_code_msg = ['error' => 'Invalid purchase code. Please double check your purchase code and try again!'];
throw new Exception(json_encode($invalid_code_msg));
In js:
var xhr = new XMLHttpRequest;
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.onreadystatechange = function () {
if (this.readyState === 4){
if (this.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data, data.error)
//here data is still a string unless I parse it twice?
}
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("pc=" + purchase_code.value);
I am trying to figure out why data is still a string unless I parse it twice?
data is still a string after first JSON.parse
{"error":"Invalid purchase code. Please double check your purchase code and try again!"}
I'm trying to write a chrome extension, that closes a tab when it's loaded and contains specific keywords, which I'm storing in banned.json. But following code gives me an error:
//background.js:
var obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
obj = JSON.parse(xhttp.response);
console.log(obj.banned);
}};
xhttp.open('GET', "banned.json", true);
xhttp.send();
chrome.webNavigation.onCompleted.addListener(closeTab, obj.banned); // error is here
function closeTab(e) {
if (!e.frameId) {
console.log("Hallo2");
chrome.tabs.remove(e.tabId);
}
}
It says that it cannot read property banned of undefined. How can that be? obj is defined in the first line and I can reference it in the if-block. Can anyone help me?
EDIT:
banned.json:
{
"banned": [
"https://www.google.de/",
"youtube.com"
]
}
You need put "chrome.webNavigation.onCompleted.addListener" sentence in "xhttp.onreadystatechange" function.
var obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
obj = JSON.parse(xhttp.response);
console.log(obj.banned);
chrome.webNavigation.onCompleted.addListener(closeTab, obj.banned);
}};
xhttp.open('GET', "banned.json", true);
xhttp.send();
function closeTab(e) {
if (!e.frameId) {
console.log("Hallo2");
chrome.tabs.remove(e.tabId);
}
}
EDIT
You can try changing banned.json as follows.
{
"banned":
"url" : [
{"hostContains":"https://www.google.de/"},
{"hostContains":"youtube.com"}
]
}
Solution:
change banned.json to:
[
"www.google.de",
"www.youtube.com/?gl=DE"
]
"chrome.webNavigation.onCompleted.addListener" sentence mustn't be in "xhttp.onreadystatechange" function else you're gonna get an error.
I would like my program to import an JSON file, using the data to create an array-list then access the array-list so that I can display it on the web page.
I've tried using JSON.parse() but it only works when I do something like JSON.parse('[{"shape":"polygon"},{"shape":"square"}]); It doesn't work for parsing a JSON file that is not declared inside. My JSON file is saved to my desktop. I'm new to JavaScript and importing files so anything would be helpful!
I've tried using:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObject = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
I keep getting errors with: JSON.parse(this.responseText);
JSON.parse Error: Invalid character at position:5 problemlist1.html(3,5)
You can just have the log in xmlhttp scope and it'll work.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.responseText))
}
};
xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
EDIT: seen your edit, in addition, make sure that your JSON has the right format:
{
"key1" : 1,
"key2" : 2,
"key3" : 3
}
I have the following AJAX code:
var ajax = new XMLHttpRequest();
axaj.open("POST", "index.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200){
var returnVal = ajax.responseText;
}
}
ajax.send("nextMax=-1");
And pairs with some PHP that ends with:
echo json_encode(array(
'next_id' => $nextID
));
exit();
This all works, as it is. If I print out returnVal inside the AJAX call, it prints out the correct array, with the correct value:
{"next_id":"935210077606657948"}
But I cannot access the id directly. I've tried
var nextID = returnVal.next_id;
and
var nextID = returnVal['next_id'];
and other variations, but all return undefined.
How do I get the array elements from within returnVal?
Thanks in advance.
Found a solution not 30 seconds after posting the question. But for those who are in the same place:
Switch
var returnVal = ajax.responseText;
to
var returnVal = JSON.parse(ajax.responseText);
and then the call works:
returnVal.next_id;
Here is how my js look like
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myajaxurl.com/lyric", true);
var data = "lyric";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.send(data);
and my simple php
<?php
if( isset($_POST['lyric']) )
{ ?>
<?php echo "test"; ?>
//it take sometime for my php to work and return the result, i do data scraping here
<?php } ?>
I expect to see 'test' in console.log but I didn't, the ajax need send. why??
PHP doesn't seem to be able to decode a single parameter with no value when doing a post request. A simple solution would be to explicitly add = after the parameter name:
var data = "lyric=";
Example:
// index.php
print_r($_POST);
// command line
// parameter name, not value
$ curl --data "lyric" http://localhost:8888/index.php
Array
(
)
// parameter name with empty value
$ curl --data "lyric=" http://localhost:8888/index.php
Array
(
[lyric] =>
)
Compare to GET instead (with print_r($_GET)):
$ curl http://localhost:8888/index.php?foo
Array
(
[foo] =>
)
You were trying to access the data incorrectly. You need to pass the parameters just like you would do if you were making a GET request. So in the below code, the data variable can be accessed through the $_POST array, which stores the data you want.
JAVASCRIPT
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myajaxurl.com/lyric", true);
var data1 = "data=lyric";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.send(data1);
PHP
<?php
if( isset($_POST['data']) )
{
echo "test";
}
?>
EDIT
The header issue can be solved like this
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myajaxurl.com/lyric", true);
var data1 = "data=lyric";
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", data1.length);
http.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.send(data1);
source:http://www.openjs.com/articles/ajax_xmlhttp_using_post.php