I'm new to AJAX. I've looked at previous postings and see this is a common question. The usual answer is that the data isn't actually in JSON format. This is certainly true in my case - the correct response is preceded by other data from earlier echo output, like this:
<button type="button" id="dotest" name="dotest" >SAVE</button>{"foo":"bar"}
This is the test code that creates this output:
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php include "../php/bin/test-bin.php"; ?>
<script src="../js/test.js"></script>
</body>
</html>
JS
$('#dotest').click(function(){testCode()});
function testCode()
{
$.ajax({
type: 'POST',
dataType: 'json',
data: {testvar:true},
url:'../php/bin/test-bin.php',
success: function(formdata) {
alert(formdata['foo']);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
},
});
}
PHP
<?php
echo '<button type="button" id="dotest" name="dotest" >SAVE</button>';
if(filter_has_var(INPUT_POST, 'testvar'))
{
$myArr = array("foo" => "bar");
$json = json_encode($myArr);
return;
}
If I move the echo button statement to the end of the PHP code, the unwanted text doesn't appear in the response.
Have I some error in my code? Or is there some way to flush the PHP output after echo calls? I've tried flush() but it doesn't work.
Any help you can give would be good for my blood pressure!
EDIT
I've done what's suggested and put the Ajax call in a separate file. I get the same problem. In testing I've removed almost all the code, leaving this (the requires and defines do nothing at this point):
<?php
// include global constants etc
require_once(__DIR__.'/../inc/config.php');
require_once(__DIR__.'/../inc/errorhandler.php');
require_once(__DIR__.'/../inc/common.php');
// fl_data
#define('FL_PREVVAL', 0);
#define('FL_CURRVAL', 1);
$data = array('animal' => 'horse', 'vehicle' => 'cart');
$json = json_encode($data);
echo $json;
The Ajax response is an error, but xhr.responseText contains correctly formatted JSON.
If I remove the two define statements, the response is success with the same data. Putting back any code preceding the echo produces the same error situation.
What am I doing wrong!
Related
I have a html page with jQuery and I used ajax to send data to the a php file to save the data.
I have seen other questions like this but none of them seemed to match my purpose.
The data is an iframe's srcdoc.
My html looks like this:
<iframe srcdoc="<h1>hello</h1>" id="iframe"></iframe>
<br />
<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">
My jQuery and JS looks like this:
function saveDoc(e) {
let iframe = document.querySelector("#iframe");
let data = {"srcdoc": iframe.srcdoc, "lnk": e};
$.ajax({
type: "POST",
url: "saver.php",
dataType : "text",
contentType: "application/json",
data: data,
cache: false,
timeout: 3000,
success: function (data) {
alert("SUCCESS");
console.log(data);
},
error: function (e) {
alert(e);
}
});
}
And my php code looks like this:
<!doctype html>
<html>
<body>
<?php
if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
$myfile = fopen($_POST["link"], "w");
fwrite($myfile, $_POST["srcdoc"]);
fclose($myfile);
echo $_POST["lnk"];
echo "\n <br/>";
echo $_POST["srcdoc"];
} else {
echo "Error";
}
?>
</body>
</html>
When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:
<!doctype html>
<html>
<body>
Error</body>
</html>
What is happening here, and what am I doing wrong?
contentType: "application/json"
You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)
Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)
I'm receiving data from an API (asana) when an event was made in my workspace via a POST method in a file called asanatarget.php
The data is correct and i can store it in file when received.
Looks like that:
{"events":"resource":xxx,"user":xxx,"type":"story","action":"added","created_at":"2019-02-20T14:48:09.142Z","parent":xxx}]}
In the same file I send the data to a new file with AJAX with GET method:
asanatarget.php
<?php
if(isset($_SERVER['HTTP_X_HOOK_SECRET'])) {
$h = $_SERVER['HTTP_X_HOOK_SECRET'];
header('X-Hook-Secret:' . $h);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$input = file_get_contents('php://input');
if ($input) {
$entries = json_decode(file_get_contents('php://input'), true);
file_put_contents('targetasanaDATA' . time() . '.txt', json_encode($entries));
?>
<script>
$( document ).ready(function() {
$.ajax({
type: "GET",
url: "/asanawebhook", // Working with laravel, the route is well defined
data: <?php echo json_encode($entries); ?>,
dataType: "json",
success: function(response){
console.log("success " + response);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
}
});
});
</script>
<?php
}
?>
</body>
</html>
When i'm directly loading asanatarget.php with test data, it's working fine and the data is passed to /asanawebhook but when the data is passed directly from the api, it's not working.
I checked and the data is always correct
Your PHP script generates only a HTML page (basically, a text).
The javascript can be interpreted and executed by a browser. But if no browser reads this page and execute it, nothing happens. PHP generates a webpage, nobody reads it, and things ends here.
You can use PHP too to send data via POST. You can build your query with http_build_query() and use file_get_contents().
I'm using dataTable and I'm having the Json parse error. Here is my code:
jQuery(function($){
$('#allusers').dataTable({
"sAjaxSource": document.URL+"/allusers.php"
});
$.ajax({
url: document.URL+"/allusers.php",
success: function(data){
alert (data);
}
});
});
So inserted the $.ajax part so that I could see the data being returned. (Well I could also see it using firebug, just wanna make sure) and the response that I am getting is the HTML code instead of the JSON object.
here is the snippet of allusers.php:
$dataArr['aaData'] = Array();
$res = $mysqli->query($query);
$numrows = $res->num_rows;
$output = array('iTotalRecords' => $numrows, "iTotalDisplayRecords" => 10, "aaData" => array() );
if ($res = $mysqli->query($query)){
while($row = $res->fetch_array(MYSQLI_ASSOC)){
$r = Array();
foreach($row as $key=>$value){
$r[] = $value;
}
$output['aaData'][] = $r;
}
} else
die(mysql_errno());
$output['err'] = 'hello';
header('Content-Type: application/json');
echo json_encode($output);
exit();
I already tried var_dump($r) to check the contents of $output and I don't see a problem with it.
So the result that I'm getting is:
<!DOCTYPE html>
<html class="home">
<head>
<title>User List</title>
...
it basically returns the html content of the whole page.
Is the problem within the javascript or php?
Thanks in advance for the help!
Not sure if your PHP framework respects requested datatypes, but you could start by requesting JSON specifically. Either specify:
$.ajax({
url: document.URL+"/allusers.php",
dataType: "application/json",
success: function(data){
alert (data);
}
});
or use the jquery json shortcut:
$.getJSON("url", data, callbackFuntion);
The default for the $.ajax() method is to intelligently guess the output, so it seems weird it doesn't pick up on your content-type.
My last idea would be that you specified php headers and footers globally somehow, so they are added to your output?
I've already fixed this problem. Since I'm using a MVC, I put the function in the controller then just added a code like this:
if (isset($_GET["var"]))
function();
also I removed the
header('Content-Type: application/json');
I don't know why, but when I removed that it worked. Thanks all for pitching in your ideas. :)
I'm just learning how to use jQuery and PHP together. This is my first attempt, and I feel like I'm almost getting the concept. However, there's an issue I failed to address. When I post a JSON object to PHP script and try to return one of the parameters, I get the following error : "Trying to get property of non-object in ..."
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css"></style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
var myData = {
'firstName' : 'John',
'lastName' : 'Doe'
};
$.ajax( {
type: "POST",
url: "postData.php",
contentType: "application/json",
data: myData,
success: function(msg){
alert(msg);
},
error: function(err) {
alert('error!' + err);
}
});
}
</script>
</body>
</html>
postData.php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>
With a bit more work, you can achieve this using a REST client that will automatically handle data-type conversion and URL parsing among other things.
To name some of the advantages of using a REST architecture:
Simple.
You can easily scale your solution using caching, loading-balancing etc.
Allows you to logically separate your URL-endpoints.
It gives you the flexibility to change implementation easily without changing clients.
Try reading, A Brief Introduction to REST to get a better idea about the design pattern and it's uses. Of course you won't need to write a framework from scratch if you don't want to, since there are already several open-source PHP based implementations out there such as Recess PHP Rest Framework.
Hope this helps!
json_decode (depending on PHP version) defaults to returning an array, not an object. The proper way to access it would be:
$output = $jsonData['firstname'];
You'll also want it to return an associative array, so pass true as the second argument of json_decode.
$jsonData = json_decode($input, true);
What could alternately be happening is that the JSON is invalid, in which case PHP returns null. You can check for that:
if ($jsonData = json_decode($input, true) === null) {
// Do stuff!
} else {
// Invalid JSON :(
}
I put it a little bit more simple with the function post of jquery.
I hope you found it useful:
first your html and js:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css">
</style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
$.post(
"postData.php",
{
firstName : 'John',
lastName : 'Doe'
},
function(msg)
{
alert(msg);
}
);
}
</script>
</body>
</html>
then your php:
<?php
echo $_REQUEST['firstName']." - ".$_REQUEST['lastName'];
?>
I finally figured it out:
js:
function postData() {
var myData = {
firstName: 'John',
lastName: 'Doe'
};
$.ajax({
type: "POST",
url: "postData.php",
data: JSON.stringify(myData),
success: function(msg){
alert(msg);
},
error: function(err){
alert('error!' + JSON.stringify(err));
}
});
}
php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>
When decoding you DON'T want to put "true" as the second argument, because then, it's not JSON but an associative array (or so I've read). If I put json_decode($input, true), then it won't work.
I want to fetch data from mysql, and echo it by a json_encode. then my JQUERY will catch JSON via $.getJSON and append the result into my <ul>.
im trying to figure out why the data being captured by JQUERY is not printing on my index.php
this is my index.php
<html>
<?php
include_once('connect.php');
$sql = "SELECT * FROM data";
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($query))
array_push($result,
array(
'name' => $row[1],
'msg' => $row[2]));
echo json_encode(array("key" => $result));
?>
<body>
<ul>
//insert fetch data here
</ul>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/custom.js"></script>
</body>
</html>
and here is my JQUERY
function my_function() {
$.getJSON("index.php", function(data) {
$.each(data.key, function(){
$("ul").append("<li>Name: "+this['name']+"</li>"
"<li>message: "+this['msg']+ "</li>");
});
});
}
You don't need to fetch your data via JSON as you're echo-ing the JSON on the same page.
you could do something like this:
<ul id="jsonData" data-json-data="<?php echo json_encode($result;)?>"
And in your js file:
var myData = $('#jsonData').data('json-data');
first: check your index.php output by itself to see if it's displaying valid json. ¿Are there invalid UTF8 characters? In that case json_encode's output is null.
second: I'd use plain ajax method hinting json as dataType:
jQuery.ajax({
url: 'index.php',
dataType: 'json'
}).done(function(data) {
for (i=1;i<data.length;i++) {
datarow=data[i];
$("ul").append("<li>Name: "+datarow.name+"</li>");
$("ul").append("<li>message: "+datarow.msg+ "</li>");
}
});
third: don't use the same script to generate the json and to display it, it makes no sense to decouple view from app if you do it all in the front. In that case you might as well use plain php to generate it all, as the previous answer told. (#Abdoul Sy)