I would like to pass a string that has been serialized by JSON using $.ajax to an external php file to be assigned to a regular array.
Here is what I got so far which isn't showing 0th index of taskContent array.
JQuery code:
$(".json").click(function() {
var allTaskArr = [];
$('#appendTask .taskbox').each(function(index,domEle){
//domEle == this
allTaskArr[index] = $(domEle).val();
});
var allTaskStr = '{"taskContent":'+JSON.stringify(allTaskArr)+'}';
$.ajax({
url:'testjson.php',
type:"POST",
datatype:'json',
data:allTaskStr
});
});
PHP file:
$jsonContent = $_POST['taskContent'];
$taskContent = json_decode($jsonContent,true);
echo $taskContent[0];
You said:
#Spudley I'm getting 'Undefined Index: taskContent' message.
The reason for this that PHP is not receiving a post variable named tastContent.
And the reason for this is that you are not sending the JSON correctly.
In the jQuery code, you are producing a JSON string, and then putting this in the data element of the ajax call. In fact, the data element is supposed to be given an object, not a json string; it encodes it to json itself, so if you give it json in the first place, the PHP program will receive a double-encoded string -- ie a json string which decodes to another json string.
So instead of this:
var allTaskStr = '{"taskContent":'+JSON.stringify(allTaskArr)+'}';
... you need to send the data as an object, like this:
var allTask = {taskContent:allTaskArr};
or just put it straight into the ajax call:
data : {taskContent:allTaskArr}
Hope that helps get you on the right track and explains what the problem is.
Disregard this post before this edit.
This is your issue:
var allTaskStr = '{"taskContent":'+JSON.stringify(allTaskArr)+'}';
Should be:
var allTaskStr = {"taskContent":JSON.stringify(allTaskArr)};
data:, expects an object and you are sending it a string.
Related
I'm passing an object through ajax to a PHP file for processing like this:
var Obj = {id:1, name:"John", value:12.1};
$.ajax({
url : "myfile.php",
type : 'POST',
data : Obj,
success : function(data) {
console.log(data);
});
My issue is when I receive the parameters on my $_POST variable everything is a string like id => "1" or value => "12.1". I would like these to be kept like an Int and a Float for example without additional conversions on the PHP side.
Is there an easy way to maintain the variable types?
You need to convert the values on PHP because PHP receives values as a string :
$data = $_POST['data'] ;
$int = (int)$data['id']; // or intval($data['id'])
$float = (float)$data['value']; // or floatval($data['value'])
Is there an easy way to maintain the variable types?
Not really. The data format used to send the data doesn't carry any kind of type hinting.
You could use JSON instead.
You'd have to encode the data as JSON when you send it, and then explicitly decode it in PHP.
I know ajax calls and $_POST have been around a lot lately, nevertheless i could not find an answer to my current problem.
In my Javascript, I have a two-dimensional data array:
var postData = new Array(new Array());
postData[0]['type'] = 'grid';
postData[0]['data'] = gridData;
I then try to send this array to a PHP script:
function export_report_pdf(postData){
console.log(postData);
$.post('/ajax/ExportReportPDF.ajax.php',{data: JSON.stringify(postData)},
function(postData){
console.log("Successfully requested report export.");
});
}
I have tried to receive the array in my PHP script:
print_r($_POST);
var_dump(json_decode(file_get_contents("php://input")));
but all I get in my $_POST is an empty two-dimensional array. When I do the console.log(postData) in the beginning of my function, the data is there.
I have also checked $_REQUEST and tried removing the JSON.stringify.
Your inner variable type should be an object instead of an array, otherwise it won't get serialized properly:
var postData = [];
postData.push({
type: 'grid',
data: gridData
});
have you tried using get instead of post.
try that that would atleast ensure that data is getting passed from client to server and problem is with POST request only.
Also when u try GET than check in console if u are getting any error.
Don't JSON.stringify your post data. jQuery will do that for you, regardless of whether you've done it yourself, so it's winding up double-encoded. If you check your logs, you'll see that, after unencoding the data, PHP has a single POST parameter that is all of your data, JSON encoded.
Your could should look like this:
$.post('/ajax/ExportReportPDF.ajax.php', {data: postData}, ...
function export_report_pdf(postData){
console.log(postData);
$.ajax(url:'/ajax/ExportReportPDF.ajax.php',type:'POST',{data: JSON.stringify(postData)},
success:function(postData){
console.log("Successfully requested report export.");
});
}
try this.
and make sure you have latest jquery included.
So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}
As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.
You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);
You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.
Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)
This is how I got my php array to javascript
echo 'var daysofweek = '.json_encode($daysofweek).';';
Now I am aware that json_decode can do the opposite, however the problem is I don't know the syntax to do so.
I tried:
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
yes im clueless.
I forgot to mention that I want to send an array through post, having all my information regarding all the form values dynamically created by javascript. Otherwise, I wouldn't know which name="" to look for as it will be decided by the user. Unless someone else has an alternative solution...
PHP is a pre-processor and can't do what you're asking. You would need the PHP engine to be able to process the javascript on the page. json_decode is for decoding a json string in PHP.
To do that you would have to pass the javascript array to a PHP script using something like Ajax so your PHP script can process it anyway you would need, then pass back the result to your Javascript code.
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
I'm clueless in this part... is this javascript? if so, you need to use a JSON Parser like the JSON2.js https://github.com/douglascrockford/JSON-js
this file creates a Javascript JSON Object which allows you to parse a JSON string to a Javascript object. (you can always use eval() but it won't prevent against possible malicious code...) or the other way around... from a Javascript Object transform into a JSON string.
After converting to a JSON string you just need to send the data through AJAX to a PHP file, like:
var data = {
key: value,
key2: value2
},
JSON = JSON.stringify(data);
$.ajax({
url: 'php_file.php',
type: 'POST',
data: JSON,
success: function(data){
alert(data)
}
});
(I'm using jQuery to save some lines...)
Then on the php_file.php you would have something like this:
<?php
$json = json_decode($_POST['data']);
foreach($json as $value){
//Do something with it!
}
?>
Yes as the Wajiw said, PHP is pre-processor. But I think it might be possible with the ajaxed request.
Send the Javascript array as an argument request to the other page and process it with the php, and again display back the results.
Note: Never tried this :)
Thanks
First of all:
array_days[] = "psdfo";
array_days[] = "bsdf";
These lines are valid PHP but not valid JavaScript. The correct equivalent would be:
array_days.push("psdfo");
array_days.push("bsdf");
On to passing the resulting array of strings (that's what I am assuming) to PHP. To send it as form data in pure JS, we can create hidden input elements when the form is submitted (try it):
<form id="myform" method="POST" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('myform').onsubmit = function() {
for(var i = 0; i < array_days.length; ++i) {
var inputElement = document.createElement('input');
inputElement.type = 'hidden';
inputElement.name = 'array_days[]';
inputElement.value = array_days[i];
this.appendChild(inputElement);
}
};
</script>
PHP will interpret each input having the name of array_days[] as an array element of $_POST['array_days']. For example, you can access $_POST['array_days'][0] in PHP.
For AJAX, jQuery 1.4 and above will automatically achieve this effect when you pass an array as a data parameter to $.ajax.
Why not json_decode()? The answer is that older versions of web browsers do not support the JavaScript function JSON.stringify() that is equivalent to PHP's json_encode(), although there is a library to add support. One might consider it for a more complex case, but for such a simple case, it should not be necessary.
I have been misinterpreted. I have created a JSON Object in PHP. I just need access to that object in Javascript. That is all.
I just learned that many of my problems can be solved by using JSON. Now learning how to use JSON is another problem, though. ;-)
Suppose this is the code in PHP:
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Now how do I access the $javascriptFriendlyData in javascript.
I tried using JQuery but I can't really figure out much...
If it helps, the JSON Data structure is somewhat like this:
[{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}...
]
Try this:
<script>
<?php
echo 'var data = '.$javascriptFriendlyData;
?>
// now the JSON data is stored in the data variable
console.log(data);
</script>
I'm assuming you are running PHP in the HTML template here:
<html>
<head>
<script><?php echo 'var data = '.$javascriptFriendlyData; ?></script>
<script src="some_js_file.js"></script>
</head>
<body>
etc...
In the some_js_file.js, you can now access the data variable.
If it's an array of simple data as you describe, there is little reason to eval() it, but you might consider it anyway.
From the official JSON documentation:
var myObject = eval('(' + myJSONtext + ')');
Now you can use it like any other Javascript object.
If you are creating the JSON encoded data in your PHP script and echoing in your JavaScript, you don't even have to call eval because it is already in a native JavaScript format.
So taking your code...
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Then, in your Javascript code you can do something like...
<script type="text/javascript">
var data = <?php echo $javascriptFriendlyData; ?>;
</script>
Then when the page is rendered, the data is already parsed and ready to use. It is when you are handling AJAX requests that return data that it needs to be evaluated. Otherwise, it is no different then using JavaScript notation inline.
eg:
<script type="text/javascript">
var somevar = [{objVar1:"SomeVal"},{objVal2:"SomeVal2"}];
</script>
If you are trying to have your JavaScript in a separate file, then you will need to set this variable in your JavaScript before you load your JavaScript file or run the JavaScript file through the PHP interpreter.
JSON is just a notation for Javascript data. Which means you can have this kind of JS code :
var data = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
Which will just put your data in the data Javascript variable.
Considering that [] symbolize an array, and {} symbolize an object, you can use this to access the title property of the first element of the data array :
alert(data[0].atitle);
And you'll get
Ameya R. Kadam
And, to loop over each elements of the data array, you can use something like this :
var i;
for (i=0 ; i<data.length ; i++) {
alert(data[i].aid + ' : ' + data[i].atitle);
}
(Absolutly no need for jQuery for such a task, btw)
If your array is in a variable called data:
$.each(data, function(){
alert(this.aid);
alert(this.atitle);
});
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function() {
alert(this.aid)
alert(this.atitle)
})
Or
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function(i,o) {
alert(o.aid)
alert(o.atitle)
})
I have found that the JSON.org Json2.js library to come in handy for going from JSON to JS and back from JS object to JSON. For example, instead of:
var obj = eval('(' + jsonString + ')');
with the JSON.org library you use:
var obj = JSON.parse(jsonString);
You can also specify a second parameter that allows you to work with the results of the JSON being revived as an object.
To go back to a JSON string just call:
var jsonString = JSON.stringify(obj);
This also takes optional arguments to help control JSON string creation.
JSON basicalle represents a Data Structure right, so essentially it's an Object, or instance of a Class, so to use it you do this:
var MyJSonObject = eval("(" + jSonString + ")");
UPDATE
hey Amit, you can't access PHP objects from javascript. What you have to do is somehow construct the JSON string in PHP, but then write it out to the client. I'm not sure how you'd do it in PHP, but this how you'd do it in ASP. The idea is the same, the syntax will be different in PHP.
<html>
<head>
<script type="text/javascript">
var MyObject = eval("(" + <%= Response.Write(strServerSideVariable) %> + ")");
</script>
</head>
<body>
</body>
</html>
Note that in ASP/.NET the tags "<% %>" denote server side, not client side, code. This is what you have to do with PHP amit
It's worth noting that some browsers now provide a set of native functions for JSON decoding and encoding: JSON.parse() and JSON.stringify(). They are safer than using the eval() function and only works if the JSON data is well-formed, whereas eval() would evaluate things like the following:
{
'hello': (undefined
? 'world'
: ('number ' + Math.floor (40.235)))
}
What's wrong with that? The JavaScript value `undefined' is not available in JSON (only true, false, null, strings and numbers are allowed); single quotes are used everywhere when only double quotes are valid in JSON; you can't call JavaScript functions or perform string concatenation in JSON.
Obviously the last one is a big problem because you could receive some malicious JSON, possibly a value from a form input, that attempts to tamper with things. So when possible, use JSON.parse() and JSON.stringify()...because eval() is dangerous.
Edit:
I misread the original post. If you have a JSON object in PHP and you want to use it in JavaScript, you would need to convert the JSON object to a string and pass it on to JavaScript. The only way to do that would be to make your JavaScript code actually ask for the newly created JSON string in the first place. PHP would return a string, JavaScript would use eval() or JSON.parse() on the string, and you'd have your object in JavaScript. I'm not sure if there is a non-AJAX way to do this without making your JavaScript files into PHP files, setting the Content-Type header, etc., but I know that AJAX would work in this situation.