AJAX and JS, Cannot read JSON data? - javascript

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;

Related

Calling PHP JSON data results from JavaScript

I am attempting to obtain PHP data from my Javascript code. This is meant to be shown in the dayta div id. What I end up getting instead is undefined instead of the desired result (which in this instance is the firstname in my JSON file). I am not sure why this is happening.
My JavaScript code:
window.onload = function(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
var dayta = document.getElementById('datadisplay');
dayta.innerHTML = http.response.firstname;
}
}
http.open("GET", "myphpfile.php", true);
http.send();
}
My PHP code (myphpfile.php):
<?php
$content = file_get_contents('somejsonfile.json');
print_r($content);
$dbcon->close();
?>
The PHP code included is only a portion of my code, but it contains all the parts relevant to my problem.
$content outputs a JSON file, as that is what it is pointed to. If I echo $content I am able to verify that the content is streamed out as intended.
Thus, the problem is most likely with my JavaScript code. But I cannot identify specifically what is wrong.
My JSON file (somejsonfile.json):
{"firstname": "Ki ki ki ma ma ma"}
I understand that the most obvious way to approach this specific example is to simply have the JavaScript file reach the JSON file. However, since I'm trying to secure the path of my JSON file in my production code I am trying out this method.
Make sure you get a JSON response by using JSON.parse. Here's a quick solution. I have tried it and it works great!
window.onload = function(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
var dayta = document.getElementById('datadisplay');
var data = JSON.parse(http.responseText);
dayta.innerHTML = data.firstname;
}
}
http.open("GET", "myphpfile.php", true);
http.send();
}
pls check this code;
<?php
$content = file_get_contents('somejsonfile.json');
print_r(json_decode($content));
?>
if you see array truly then,
<?php
$content = file_get_contents('somejsonfile.json');
echo(json_encode($content));
?>
if you want to query in json file, you can use json_decode function to convert array and push or remove array item and then json_encode.

Javascript using PHP to return an array

Basically, what I'm trying to do is send a request to a separate .php file which queries my database. The problem occurs when trying to return an array as a variable type array. I need this, because I want to send it to another PHP when it is send to the HTML. In the second PHP file, I want to use a for-each-loop-statement in order to create some code, but this only takes arrays and not strings. I've tried a couple of things including the use of JSON in an attempt to fix this, but on return the array keeps turning into a string. Any help would be appreciated. Most relevant code is included below:
javascript:
function getEvents(){ //gets the events from the database
var req = new XMLHttpRequest();
var att = 1; //Just a filler because somehow this seems needed
var link = "IekjeConnector.php";
dataType:"json";
req.onreadystatechange = function() {
if(req.readyState === 4 && req.status === 200)
{
addEvents(JSON.parse(this.responseText)); //This should be a normal array
}
}
req.open("GET", link + "?att=" + att, true);
req.send();
}
function addEvents(events = ""){
var req = new XMLHttpRequest();
var link = "IekjeHome.php"; //sends to the next php
req.onreadystatechange = function() {
if(req.readyState === 4 && req.status === 200)
{ document.getElementById("event").innerHTML = this.responseText; }
}
req.open("GET", link + "?events=" + events, true); //events has the right value
req.send();
}
php:
if (filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING)) {
$events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
$length = count($events);
print_r(gettype($events));
foreach($events as $event)
{ echo $events[$count] . $events[$count+2]; }
}
The foreach returns an error that $events is a string as does the gettype().
I tried changing the way addEvents and the php-code receive the array, but i'm probably doing something wrong trying.
I think you need to change the string to array, for example using explode.
$events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
$events = explode(",",$events);
Instead of the ",", just put your event's separator.
I believe what you're looking for is JSON.parse(this.responseText).

Send javascript arrays via ajax without using jquery

i have a javascript array with values like "correct", "wrong".
I want to send this array to my php file using ajax. But im not familiar with how.
This is what i have tried so far..and i would like to do this without jquery.
var hold=[];
for(t = 0;t <= 10; t++){
answers_Arr = document.getElementsByName("question"+t);
for (k = 0; k < answers_Arr.length; k++){
if(answers_Arr[k].checked){
hold[t] = answers_Arr[k].value;
//document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
break;
}else{
hold[t] = "no";
continue;
}
}
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();
}
Here is an example of sending the json string with POST through AJAX:
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//
}
xmlhttp.open("POST","result.php",true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonString);
Avoid sending json strings with GET method because if the request string gets too long, the browser will throw you an error.
Now in your php script you will have all the data in $_POST
Edit: Looks like on some versions of php, the requests that have other Content-type, like application/json, the $_POST has an empty value. To fix this you can do:
$_POST = json_decode(file_get_contents('php://input'));
replace this line
xmlhttp.open("GET","result.php?res="+hold[],true);
with
xmlhttp.open("GET","result.php?res="+jsonString,true);

Passing value from JavaScript to PHP using AJAX

I'm trying to pass value to PHP code using AJAX.
Javascript
function countop() {
var href = window.location.href;
var href2 = href.split('/', 7);
xmlhttp.open('GET', '/count.php?val_for_count='+href2[6], true);
xmlhttp.send();
};
PHP
$x = $_GET['val_for_count'];
echo $x;
I don't get $x printed and I don't know why.
You have two problems.
First, xmlhttp is never declared, so your code throws a reference error.
var xmlhttp = new XMLHttpRequest();
Second, you never look at the HTTP response!
xmlhttp.addEventListener("load", function (event) {
document.body.appendChild(
document.createTextNode(
this.responseText
)
);
});
You have to create a new instance of XMLHttpRequest before using it:
var xmlhttp = new XMLHttpRequest();
And if you want to print the result of your request in your document, you can do it like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.body.innerHTML = xmlhttp.responseText;
}
};

xhr.responseText returned null with POST

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

Categories

Resources