I saw a similar discussion here. But my returned data format is a bit different.
I have a Json string returned from server as shown below
<!DOCTYPE HTML>
<html>
<head>
<style>
</style>
</head>
<body>
{"error":false}</body>
</html>
I need to extract data "error":false from the Json string.
I tried as below
(1)Say the Json message is in result variable, then I checked as
if(result.error == false)
It doesn't work.
(2) I also used jQuery.parseJSON as discussed in this link.
It doesn't work also.
How can I parse Json data?
Json data is parsed in Jquery.ajax for the returned message as follow
jQuery.ajax({
url: "registrationdatavalidationatserver.php",
type: "POST",
data: $("form").serialize(), /*grab all elements in your form and serialize them */
success: function(result){
//To parse result
},
error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
(3) How to return message from server just Json data without
<html>, <head>, <style>, etc. tags?
I returned from server as echo json_encode($data);
I have a Json string returned from server as shown below.
No, you need to have only the following returned from the server:
{"error": false}
Say the Json message is in result variable, then I checked as if(result.error == false)
It will never work because it is a HTML. Not a JSON.
How to return message from server just Json data without <html>, <head>
Even before you send the output, please make sure you are not sending anything to browser. Have these defined in the PHP headers:
<?php
header("Content-type: application/json");
die(json_encode($arrayData));
?>
There must not be anything other than this. It is wise to have a dedicated file for JSON output too, if you are confused in making this kind of setup.
Related
I've got a strange problem where I'm trying to write a PHP page that returns some JSON to a Jquery AJAX call. Problems is that despite setting the content type to application/json, the response always seems to include the HTML header.
Here's the PHP code:
// some code that generates an array
header("Content-type: application/json");
echo json_encode($return);
Then in Javascript:
$.ajax({
url: '/VAPHP/services/datatable.php',
dataType: 'json',
data:
{
type: 'invoices'
},
success: function(data)
{
// show a message saying it's been sent!
alert('Success!');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error!');
}
});
The response always seems to be something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
{"aaData":[["2007-08-01","91109507","Invoice","10.000000","AUD"],["2007-08-02","91110103","Invoice","5.000000","AUD"],["2007-08-02","91110122","Invoice","305.000000","AUD"],["2007-08-02","91110129","Invoice","320.000000","AUD"],["2007-08-03","91111146","Credit
for Returns","10.000000","AUD"],["2007-08-06","91111895","Credit
for Returns","320.000000","AUD"],["2007-09-03","91128486","Credit
Memo","5.000000","AUD"],["2007-09-03","91128487","Credit
etc, etc
And according to the response header it certainly thinks it's JSON:
HTTP/1.1 200 OK
Content-Type: application/json
Server: Microsoft-IIS/7.5
X-Powered-By: PHP/5.3.3
Whenever I run the code and it alert "Error!" gets fired every time, which is understandable...
Anyone got any ideas why the HTML is being included in the response?
Calling header() actually has nothing to do with HTML-code being returned in the response.
header() is used to set HTTP-headers, while HTML-code (<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">) is sent in the body of HTTP response.
So the line of code
header("Content-type: application/json");
does his job correctly because response contains correct content type:
Content-Type: application/json
So what's wrong? Probably you have code that is executed before the code that deals with json. You should send only json encoded message in your response without any HTML tags and terminate the script using exit or die. Try to locate the code that sends HTML tags and put your code before it.
Ok, I found my own answer, looks like I had tidyhtml turned on inside my PHP.ini file, and had a
ob_start("ob_tidyhandler");
inside one of my global packages. Commented that out and it all works fine. Thanks for your time everyone!
Have you tried commenting the whole "header(...)"-part? It should work without it. The AJAX-call gets everything the PHP-program outputs, in this case including the header.
I feel somepart of your code is emitting the HTML DTD and the head part automatically for all responses from the php codebase. Are you using a framework ? If so which one ? The fact that the json.txt works is indicative that nothings wrong with js, browser or any proxies in between.
I suggest you debug the php code flow to see where this part is getting added to the html response.
There is probably something posting headers before you do. Can you provide more of the php code for this?Remember that a single white space outside of the php tags forces the output of headers ( http by default).
I don´t understand why my JSON doesn´t get parsed. I hope someone could explain this to me. I try to send a JSON from PHP to JavaScript.
This code works fine:
From PHP
echo json_encode(array($row['jobunique'], $row['jobtitle']));
to JavaScript
success: function(getjoblist) {
var getjobdetails = $.parseJSON(getjoblist);
}
But this code gives me an error back:
From PHP - data comes out of an array
echo json_encode(array($data[2], $data[3]));
I thought, maybe it's an object and I need to make a string out of the variables like this:
echo json_encode(array(strval($data[2]), strval($data[3])));
But it did not work either.
Here is the JavaScript code:
success: function(callback) {
var namearray = $.parseJSON(callback);
}
Here is the error from the console:
Uncaught SyntaxError: Unexpected token in JSON at position 0
Here is the network-tab:
The callback variable is already an array. JQuery's AJAX methods automatically parse responses, if there are JSON specific headers present (Content-type: application/json).
Try run JSON.parse(["Fabi","Squ"]) in the console, it will get you the same error message.
Read more about this at http://api.jquery.com/jquery.ajax/ :
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
I'm using the following code to send a form to a php processor:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
I presume that this sends the form to my php script with all the form values in json format but I then don't know how to then access this json and turn it back into the array i need to process in my PHP script.
Does anyone know how I access this variable in my processor script so I can process the data?
Also, what is the best way for me to view the data being posted so I can work out what to do with it, when I send the data the processor is obviously not displayed, is there a way to echo out/write the information received by the script to I can view it?
You can easily access to the json as an array called "$_POST" in your php.
for example, if you send the form as a json structured like this:
{
"name":"userID",
"psw":"password123"
}
in your php script there will be the variable $_POST with this structure:
$_POST = Array (
"name" => "userID",
"psw" => "password123"
)
EDIT
In a comment you asked me how to display the data received from the server,
that's quite simple,
in your php script just write this:
echo json_encode($_POST);
so that you output the $_POST array in the json format,
then in your script write this:
$.post($(this).attr('action'), $(this).serialize(),
function(data){ //"data" argument will contain the output from the server (that is the encoded $_POST array printed as json with the php code as showed above)
console.log(data); //log data
}
); //as you can see, I've deleted "json", becouse it's unuseful
I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});
I just want the easiest/most simple way to get my data from an AJAX form using 'POST' the data the user entered on my server.
So if the user leaves their name in the input form on the page, then AJAX POST's the data to a JSON file on my server.
Is this possible? Is this the quickest way to get the data that is entered?
Thanks in advance!
*can someone tell me why this got downvoted? Am I violating any terms? I would just like to know in the future. Thanks. :/
Ajax file directly can not write to a file in your server. But you can achieve this by creating simple php script say savejson.php on your server.
Your form:
<form>
<input type="text" id="name" name="name">
<button type="submit" id="submit-btn">
</form>
<script>
$('#submit-btn').on('click', function(e) {
e.preventDefault();
if( $('#name').val() ){
$.ajax({
url : 'savejson.php',
method : 'post',
data : { 'name': $('#name').val() },
success : function( response ) {
alert( response );
}
});
}
});
</script>
Your savejson.php:
<?php
$fp = fopen('names.json', 'w');
fwrite($fp, json_encode($_POST['name']));
fclose($fp);
?>
Ajax is a term that more-or-less just means "Make an HTTP request from JavaScript".
You can use it to make a POST request. You can use it to make the body of that request a JSON text.
You can't POST to a file, only to a URL. You would need server side code that would be responsible for taking the data in the request and writing it to a file.
Yes. This is a rather common question and you'd do good to take a look at the following questions as well:
How can I use JQuery to post JSON data?
Jquery Ajax Posting json to webservice
Essentially, you use a client-side language (Javascript) to send a POST request to your backend. Naturally, you will then require a backend language (such as PHP or node.js).
I'll provide an example:
JS (jQuery):
$.post("http://yourURL.com/backend.php",{
data: {
"name" :"John Smith",
"vehicle":"TARDIS"
}
}).success(function(response){
console.log(response)
//do something with the response
});
PHP
<?php
$data = json_decode($_POST['data'], true);
$name = $data['name'];
$vehicle = $data['vehicle'];
echo "Welcome {$vehicle}-driving $name!";
?>
Your PHP especially should include error checking among other things, but this will suffice for a simple example.
In your console, upon executing the AJAX request you will then see the following:
Welcome TARDIS-driving Doctor!
Which is the output from your PHP file
Sorry to jump in late here.
var name = $('#name').val();
$.ajax({
url : 'somefile.php',
method : 'post',
data : { 'name': name },
success : function( response ) {
console.log( response );
}
});
This will do the trick.
You cannot write to any file using JavaScript alone. Just cookies or local (or session) storage.
AJAX POST sends data to server. The data is in JSON format. You understand this part already.
On server, there needs to be a API to consume this JSON and write it to a file, or better store it in a database.
More questions:
Can it directly write to a file? No
Can API write to the file? Yes, its technically possible but not advisable
How do others do it? They take JSON response and write it to a database in server side code.