JSON.parse(xmlhttp.responseText) returns empty - javascript

I am using Ajax. My search.php contains the javascript code. It requests for content.php which echoes an array $res that contains values in the form of "key" : value.
content.php :
echo json_encode($res);
search.php:
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"> </script>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText); //this alerts the correct content of $res but along with all the HTML page codes
var array = JSON.parse(xmlhttp.responseText); //also tried json_decode(xmlhttp.responseText, true); and jQuery.parseJSON( xmlhttp.responseText );
alert(array); // this doesn't alert at all
}
}
xmlhttp.open("GET", "<?php echo #$this->config->base_url(); ?>index.php/content.php", true);
xmlhttp.send();
</script>
However, when I print $res alone in a separate page, it shows the correct output which is:
{"1894":1,"1905":0,"1916":0,"1927":0,"1938":0,"1949":0,"1960":0,"1971":0,"1982":0,"1993":0,"2004":1,"2015":2}
I tried to loop through the array:
var array = JSON.parse(xmlhttp.responseText);
for(var index in array) {
alert(index+ " is: "+ array[index]);
}
But this also doesn't alert anything.
I've been trying and searching on this for days but couldn't find a working solution.
Edit:
here is the output of alert(xmlhttp.responseText) :
part 1 of the alert window
part 2 of the alert window
couldn't post more than two links (because I don't have enough reputation), anyway you had a glimpse of it, I believe.

According to what I can see in both images, your PHP is giving you HTML code after the JSON object, that could be the problem that stops you from parsing it. Make sure you end PHP execution after echoing $res. In other words, try with this line:
echo json_encode($res);exit;
Also, in case that doesn't work, please change alert(xmlhttp.responseText) to console.log(xmlhttp.responseText), check the browser console and copy here all the text you get back from the server

<script type="text/javascript">
var url=<?php echo "'" . $this->config->base_url() . 'index.php/content.php';?>;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {/* this was unclosed */
if( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
var r=xmlhttp.responseText;
console.info('ajax response: %s ',r);
var array = JSON.parse(r);
}
}
xmlhttp.open( "GET", url, true );
xmlhttp.send();
</script>

Related

AJAX request returning response text of 'false' instead of desired response text

I have a browserside javascript file that's supposed to be asking the serverside php file for a string with an ajax request. The php file seems to have the correct string, but for some reason the ajax request is returning the string 'false'.
This is the php file, named test.php:
<?php
$dir = "site/uploads";
$a = scandir($dir);
$b = json_encode($a);
echo $b;
?>
This is the js file:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.responseType = "text";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('test' + xmlhttp.responseText);
console.log('test' + JSON.parse(xmlhttp.responseText));
}
};
xmlhttp.open("GET", "test.php", 'false');
xmlhttp.send();
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.responseType = "text";
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
console.log('test2' + xmlhttp2.responseText);
console.log('test2' + JSON.parse(xmlhttp2.responseText));
}
};
xmlhttp2.open("GET", "test2.php", 'false');
xmlhttp2.send();
}
when i open the website in my browser and run load(), the console reads:
testfalse
testfalse
test2false
test2false
and has no errors. What am I doing wrong here? Thanks!
scandir() in the php-file is probably returning false, because of an error.
https://www.php.net/manual/de/function.scandir.php (Check the return values)
There are multiple possiblities for this to happen:
The folder doesn't exist
The path is incorrect (Try using absolute paths)
The folder isn't accessible, because of missing permissions

AJAX and PHP sending "HTTP get request" to the same page

My application gathers some client related information via JavaScript and submits it via AJAX to a php page.
See the code below:
index.php
<html>
<head>
<script>
function postClientData(){
var client_data = new Array(screen.availHeight, screen.availWidth);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == client_data[0]){
document.getElementById("message").innerHTML = "Client data successfully submitted!";
}
}
};
var parameters = "ajax.php?screen_height=" + client_data[0] + "&screen_width=" + client_data[1];
xmlhttp.open("GET", parameters, true);
xmlhttp.send();
}
</script>
</head>
<body onload="postClientData()">
<span id="message"></span></p>
</body>
</html>
ajax.php
<?php
echo $_REQUEST["screen_height"];
//Does something else...
?>
I was wondering if I could merge the ajax.php content to my index.php and eliminate ajax.php. When I try adding the code, I probably get into a endless loop since I don't get my "success" message.
How can I solve this issue?
Correct, IMO I would definitely keep this specific logic separated in the ajax.php file.
If you do really want to merge, add it to the top of index.php (before printing data):
if (isset($_GET['screen_height'])) && isset($_GET['screen_width']) {
// Execute specific logic and exit to prevent sending the HTML.
exit;
}

Update a php variable with AJAX Javascript

I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";

javascript in php and using ajax

I'm getting really confused with php,ajax and javascript.
I'm using some ajax code I got from w3 schools to handle a form and display it below the form input. However, I can't seem to get my php and Javascript right. I'm using JavaScript in php tags where I then Get my variable in the same php tags and echo it. I then try to get that variable in ajax. I don't think I'm correctly getting the variable with ajax and inside my php. Does anyone have some advice.
Thanks
Heres my javascript in my html doc
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "hackacronymphp.php?phpAnswer=" + str, true);
xmlhttp.send();
}
}
</script>
Here's the last part of my script with my php afterward all inside one php tag
var stringe = vari.join("");
console.log(stringe);
var answer = dataarray[stringe];
console.log(answer);
</script>
$phpanswer = $_GET['answer']
echo $phpanswer ;
?>

Getting variable from php file called by ajax request

I have main file index.php. Where user perform login I load url.php in <div> inside index.php through ajax request.
Now on url.php, on button click event I submit the form and post data to data.php file. As url.php is loaded into index.php, button click event on url.php will call function in section of index.php.
I am getting two variable $x and $y as a result on data.php.
On index.php I have JS function where I want to use $x and $y. How can I retrieve?
index.php
<script type="text/javascript">
//------------------script 2 starts ---------
function showUser(form, e) {
//alert(myid);
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var sent = form.elements['sent'].value;
//var sent2 = form.elements['sent2'].value;
//alert(sent2);
//var divElements = document.getElementById('d1').innerHTML;
var text1 = document.getElementById('previewUrl').innerText || document.getElementById('previewUrl').textContent;
var text2 = document.getElementById('previewTitle').innerText || document.getElementById('previewTitle').textContent;
var text3 = document.getElementById('previewDescription').innerText || document.getElementById('previewDescription').textContent;
//alert(text3);
console.log(sent);
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
sent = encodeURIComponent(sent);
text1 = encodeURIComponent(text1);
text2 = encodeURIComponent(text2);
text3 = encodeURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
}
</script>
+
$.ajax({
url:'url.php'
,async: true
,type : 'POST'
,cache: false
,data : 'myid=' + myid
,dataType: 'html'
,success: function(data){
$('body').html(data);
FB.XFBML.parse();
}
}
);
url.php
<form action="data.php" method="POST" onsubmit="showUser(this, event)">
data.php
if (preg_match_all('/[^=]*=([^;#]*)/', shell_exec("/home/technoworld/Desktop/test/b '$test'"), $matches)){ //Values stored in ma.
echo "hi";
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
this x and y I want to fetch in index.php.
I know this is not impossible. But complex to thing for me!
My preferred method of sending data back from the server side is responding with JSON response..
$data['x'] = $x;
$data['y'] = $y;
header('Content-Type: application/json');
echo json_encode($data);
That should give a response to your ajax callback, so you could use it like this:
$.post('data.php', { "myid": id }, function(data) {
console.log(data.x); //data.x = $x
console.log(data.y); //data.y = $y
});
I didn't test the code to see if it actually works, but it should give an idea of what to do. Let me know if it makes sense :)
If you want to retrieve only two value.
Simplest solution just like boiling a egg is:
just print both value in with separating value like ':'
echo $x.':'.$y;
and when you getting response. separate value with ':' and then you can use them..
or JSON response is also good practice for this.

Categories

Resources