I am stuck in a part where i am trying to fetch the data from php file to the script in json format . I am new to php just trying to learn from w3schools and i got stuck in HTTP method POST to send data to the PHP file and display in html but i am getting an error as
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at XMLHttpRequest.xmlhttp.onreadystatechange
And here is my code which i had done till now in front part i used html and javascript as :
<script>
function change_myselect(sel) {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":sel, "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "get_email.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
</script>
<select id="get_email" name="get_email" onchange="change_myselect(this.value)">
<option value="">Choose an option:</option>
<option value="3">Customers</option>
<option value="4">Products</option>
<option value="5">Suppliers</option>
</select>
<p id="demo"></p>
And here is my php file :
<?php
include("admin/include/config.php");
$id=$_POST['get_email']
if(isset($_POST['$id'])){
$sql=mysql_query("select * from subscription where id=".$id);
$returnArray = array();
while ($row=mysql_fetch_array($sql)){
$returnArray =
array("email"=>$row['email'],"creationDate"=>$row['creationDate']);
}
// return JSON response.
header('Content-Type: application/json');
echo json_encode($returnArray);
}
Can you suggest me what i am doing wrong in the above script . Thanks in Advance
You've some error in PHP code, you're just printing the email. That's not a JSON string.
Read this to know more about JSON: https://www.w3schools.com/js/js_json_intro.asp
By reading your JS code you're accessing name from the object, so may need to change the PHP script as follow,
<?php
include("admin/include/config.php");
$id=$_POST['get_email']
if(isset($_POST['$id'])){
$sql=mysql_query("select * from subscription where id=".$id); // You missed semi colon here.
$returnArray = array();
while ($row=mysql_fetch_array($sql)){
$returnArray = array("email"=>$row['email'],"name"=>$row['name']); // assuming column name exists.
}
// return JSON response.
header('Content-Type: application/json');
echo json_encode($returnArray);
}
Related
I am working on a code that will fetch the data from textarea and submit it through ajax on button click.
In next step, PHP will create a file on server and store the ajax data into file.
I have already tried addslashes function of PHP, but that is not working.
I have tried to do it via the above method and its submitting the text data successfully. But the issue is with HTML data. I think it must be a parsing problem.
The HTML code
<textarea id="textareaCode"></textarea>
The Javascript code with Ajax
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = comment;
xmlhttp.open("GET","makePage.php?content=" + content,true);
xmlhttp.send();
}
</script>
And Finally the PHP code
<?php
$content = $_GET["content"];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>
I am not getting any error message
You should do it with POST instead of GET, like Teemu said:
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
This row set the right header.
<textarea id="textareaCode"></textarea>
test
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = JSON.stringify({ comment: comment });
xmlhttp.open("POST","makePage.php",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(content);
}
</script>
PHP:
<?php
$data = json_decode(file_get_contents('php://input'), true);
$content = $data['comment'];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>
Post will work this way
function makePage(){
var data = document.getElementById('textareaCode').value;
$.post("makePage.php", {content: data}, function(result){
//Do something with the result
});
};
Then the php
$content = $_POST['content'] or $_REQUEST['content']
What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];
I looked a lot on the internet and wasn't able to find the answer i need, so here i come to you.
What i have : A database which look like this :
name latitude longitude
---- --------- ----------
foo 13.323 -51.356
foo 54.698 2.487
What i want to do : I need to retrieve the latitude and longitude from a mysqli request done with php and use it in a function that i defined.
My problem : I'm trying to use xmlrequest but it apparently doesn't work.
The code : JS :
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(str){
var xhr;
if(str==""){
return;
}
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var object = JSON.parse(xhr.responseText);
for(var a in object){
newMark(v['lat'], v['lng']);
document.getElementById("pi").innerHTML=JSON.parse(xrh.responseText); // This is a test to display any kind of result.
}
}
}
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
PHP :
<?php
$nom = $_GET['q'];
include("connexion.php");
$con = connect_LIF4();
$req1= "SELECT Latitude, Longitude FROM etape LEFT JOIN itineraires ON NomLieu=nomEtape WHERE nomIti LIKE '%$nom%'";
$result1 = mysqli_query($con, $req1);
$data = array();
while($row = mysqli_fetch_array($result1){
$data['lat'] = $row['Latitude'];
$data['lng'] = $row['Longitude'];
$resp[] = $data;
}
echo json_encode($resp);
mysqli_close($con);
?>
I tried to use newMark(lat, lng)(Which i coded and works fine) with random values, in showMark outside the onreadystatechange and it works, but i need to use it with the values retrieved from the php.
One problem with your PHP is that
while($row = mysqli_fetch_array($result1){
is missing the second brace. It should be:
while($row = mysqli_fetch_array($result1)){
Also the URL in the ajax request should be the full URL, not just getpos.php
Thirdly you have written xrh.responseText (should be xhr).
Basically there's loads of syntax errors in your code - you should use the javascript console to debug the front end ones, and PHP logging or error display for the back end ones. You should only need help here once you've debugged all obvious syntax errors.
EDIT - below is a working example (although I haven't done the MySQL part)
JS + HTML:
<span id='pi'></span>
<select id='nameIti'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
</select>
<script>
function newMark(lat,lng) {
console.log(lat);
console.log(lng);
}
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(val){
var str=val;
var xhr;
// if(str==""){
// return;
// }
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var result = JSON.parse(xhr.responseText);
console.log(result);
for(var a in result){
newMark(result[a]['lat'], result[a]['lng']);
document.getElementById("pi").innerHTML = result[a]['lat'] + ', ' + result[a]['lng'];
}
}
}
// xhr.open("GET", "getpos.php?q="+str, true);
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
</script>
PHP:
<?php
$nom = $_GET['q'];
$data = array();
if($nom == 'foo') {
$data['lat'] = '5.12';
$data['lng'] = '0.34';
$resp[] = $data;
}
else if($nom == 'bar') {
$data['lat'] = '2.34';
$data['lng'] = '1.34';
$resp[] = $data;
}
echo json_encode($resp);
?>
<?php
header("Content-Type: application/json");
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
require_once("connect_db.php");
$i = 0;
$jsonData = '{';
$sqlString = "SELECT * FROM tablename ORDER BY RAND() LIMIT $limit";
$query = mysqli_query($con, $sqlString) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$i++;
$id = $row["id"];
$title = $row["title"];
$cd = $row["creationdate"];
$cd = strftime("%B %d, %Y", strtotime($cd));
$jsonData .= '"article'.$i.'":{ "id":"'.$id.'","title":"'.$title.'", "cd":"'.$cd.'" },';
}
$now = getdate();
$timestamp = $now[0];
$jsonData .= '"arbitrary":{"itemcount":'.$i.', "returntime":"'.$timestamp.'"}';
$jsonData .= '}';
echo $jsonData;
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var myTimer;
function ajax_json_data(){
var databox = document.getElementById("databox");
var arbitrarybox = document.getElementById("arbitrarybox");
var hr = new XMLHttpRequest();
hr.open("POST", "json_mysql_data.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
arbitrarybox.innerHTML = d.arbitrary.returntime;
databox.innerHTML = "";
for(var o in d){
if(d[o].title){
databox.innerHTML += '<p>'+d[o].title+'<br>';
databox.innerHTML += ''+d[o].cd+'</p>';
}
}
}
}
hr.send("limit=4");
databox.innerHTML = "requesting...";
myTimer = setTimeout('ajax_json_data()',6000);
}
</script>
</head>
<body>
<h2>Timed JSON Data Request Random Items Script</h2>
<div id="databox"></div>
<div id="arbitrarybox"></div>
<script type="text/javascript">ajax_json_data();</script>
</body>
</html>
PHP code goes on a separate file called "json_mysql_data.php". I'm just following this tutorial from https://www.youtube.com/watch?v=-Bv8P5oQnFw and it runs fine for him but not for me. I tested "connect_db.php" with mysql alone and it works fine. It seems to me like php doesn't go pass if (isset ($_POST['limit'])) but why...On the html file I get the "requesting..." message from the javascript code which means is waiting for PHP. Thanks for your help guys.
You check for the ready state and change the content of databox with the response JSON inside the onreadystatechange function:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
databox.innerHTML = "requesting...";
…
}
But you change the HTML of the databox:
databox.innerHTML = "requesting...";
Still inside the block of the onreadystatechange function and after you receive the response, so the databox will always say "requesting..." no matter what you receive. You have to move the part that prints "requesting..." outside of it:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
}
…
databox.innerHTML = "requesting...";
…
Update:
Also, it seems that your function ins't defined correctly, as you can see, the one on the MDN reference pages example receives a parameter:
req.onreadystatechange = function(aEvt) {
…
}
But yours doesn't have such parameter:
hr.onreadystatechange = function() {
…
}
Ans that's it.
Thank you for your help #arielnmz. I found the problem. PHP was having issues with the getDate() function because the date.timezone field was not configured in the PHP.ini file. Adding the following line to the file fixed the problem:
date.timezone = "UTC"
I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery.
One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).
The problem occurs when I'm trying to put the PHP variable through JQuery.
What I have to do this for me is:
var _leafs = <?php echo json_encode($leafs); ?>;
When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.
When I use the above code and alert() the result it's missing the brackets and quotes.
Even weirder is when I pass it through like so:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
The result is this:
" string(4) "
"
Which shows up to be a <br> in my html reader.
Am I missing something when I'm converting it to json?
Additional code:
<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
// The XML file could not be reached
echo 'Error loading XML. Please check the URL.';
} else {
// Get the XML file
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$paths = [];
$leafs = [];
foreach ($xpath->evaluate('//*|//#*') as $node) {
$isLeaf = !($xpath->evaluate('count(#*|*) > 0', $node));
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path .= '/'.$parent->nodeName;
}
$path .= '/'.($node instanceOf DOMAttr ? '#' : '').$node->nodeName;
if ($isLeaf) {
$leafs[$path] = TRUE;
} else {
$paths[$path] = TRUE;
}
}
$paths = array_keys($paths);
$leafs = array_keys($leafs);
echo "Choose a path<br><br>
<form>
<select id='field_dropdown'>";
foreach($paths as $value) {
echo "<option value='".$value."'>".$value."</option>";
}
echo " </select>
<button id='send_path'>Send path</button>
</form>
";
}
?>
<script>
$(document).ready(function() {
$('#send_path').click(function() {
var _path = $("#field_dropdown").val();
// Get the leafs array and send it as a json string to set_fields.php
var _leafs = <?php echo json_encode($leafs); ?>;
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
$('#fields').append(data);
}).error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
return false;
});
});
</script>
And here the code where I want the json array to end up (and then get turned back into a PHP array).
<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }
var_dump($path."<br>");
var_dump($leafs."<br>");
?>
What if you get the array through jquery instead of echoing it?
<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />
and then
var _leafs = $('#hidden-value').val();
What about adding an = after the lf query parameter when you build the get URI?
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...
Just write 'json' in the last parameter of get method:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
$('#fields').append(data);
},'json')//<-- this
.error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
Did you try this?
var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]