how to send json to php file to save on server - php

Im developing a javascript/php/ajax application and have stumbled across some problems.
Im confident at javascript and ajax but my php is a little rusty.
My aim is to get a json file from the server, modify it using javascript, and then save this modified json back to the server.
After some research it was obvious that the modified json file must be sent to a php file, this php file will then do the saving.
HOW do i send a json string from javascript to php? OR how do I get the php file to pick up the json variable from the javascript?
im assuming the php will be something like:
<?php
$json = $_POST["something"];
?>
but how do i send or "post" the javascript variable to the php file?
I was thinking about creating a hidden html form, setting a hidden textbox to the json string, then posting the html form
But surely there must be a way without including the html middle man?
Im looking for answer WITHOUT jQuery. Seeing as this is an application i would like a relieve the dependancy of jQuery.

The only, as far as I know, proper way to do this is sending data to a file through Ajax, then attaching some POST or GET data.
Example:
You could send the data in the url as GET:
http://example.com/foo.php?myvalue=cake
And then in the php you'd say:
<?php
$yourvalue = $_GET['myvalue'];
// Some code to save it to the database/server
?>

You would need to create a XMLHttp-Request like this:
xmlhttp.open( "POST", url, false );
xmlhttp.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);
xmlhttp.send("data=yaystuff!")
So you can send it. In PHP just get the $_POST['data'] variable and do some json_decode() on it, if you send JSON :)

Related

server not parsing php file called from jquery ajax

Im using a basic jquery ajax call.
I make a call to a php file without input parameters with option datatype set to json.
I want the server to parse the php which queries a table in a mysql db, convert it to array and finally encode it to json and return.
I tried a test call from the browser by copying the php file url in the address field, and it shows that it works, since I can see a blank page with all the rows of the table in json formatting.
Instead, when calling from my javascript code the $.ajax call fails with error
Requested JSON parse failed
which means ajax call was expecting json (since I set option datatype to that) but received another format.
So I tried removing the datatype option from the call, and lo and behold I got a response success, but what did I received from my php file?
Well, it was the whole code in the file, like the server doesn't parse it cause it thinks it's plain text.
Is there a way out of this problem? Thanks.
Send also content header with json data
<?php
header('Content-Type: application/json');
echo json_encode($data);
The ajax function is expecting a JSON encoded document so you have to send a header with the response saying that the response contains JSON. Something like this:
<?php
header('Content-Type: application/json');
// All your code here
echo json_encode($someArray);
?>
I'm an idiot, I may answer my own question, I was debugging jquery from visual studio, which automatically instatiates an iis web server, and it explains why it was treating php files like text files. Obviously under apache everything works fine.
Sorry for taking your time....

add this php code inside this javascript

can someone tell me how to add this php code:
<?php include('shopping_cart_temp.php'); ?>
Into this javascript line:
$('.cart_status').append('<p class="json-productname">' + retObj.product_name );
More specifically,
$.get('shopping_car_temp.php', function(result){
$('.cart_status').append('<p class="json-productname">' + result );
});
In your shopping_car_temp.php file, echo only retObj.product_name. If you need to echo multiple things, you may want to format them as JSON objects. You can read about those at: http://api.jquery.com/jQuery.get/
Use an AJAX call:
$.get('shopping_car_temp.php', function(result){
// display the data returned, value store in 'result'
});
PHP is a server side language, while Javascript is a client side language.
When you request a php page in your browser the request is processed by the server, PHP code is interpreted and an HTML page is sent to you. Then, only when HTML page is in your browser, javascript is interpreted, so from here you can't add PHP code because it couldn't be interpreted.
As #TurdPile said, you can make an ajax request to get the code from shopping_cart_temp.php and then manipulate it, but you should read some ajax tutorial to understand exactly how it works because it could be quite hard to understand

xmlhttprequest and php

Here's a stupid question, don't laugh, I've been trying to figure this out but no luck, I guess I'm too tired. So there's an application sending data (image file as string) to a php script, sending it with XMLHttpRequest.send(data). My question is how do I access this string in PHP to save it to a file?
EDIT $_POST, $_GET and $_FILES are all empty
First: Make sure you are sending a POST request (when you call the open method)
Second: Since it looks like you are sending raw data, set an appropriate content type (with setRequestHeader)
Third: You should be able to retrieve the data with $HTTP_RAW_POST_DATA or file_get_contents("php://input");.

JSON response from PHP script being enclosed in <head></head><body> ... <body>

I am trying to debug a simple PHP/JSON/jQuery problem.
The following PHP script:
header('Content-type: text/javascript');
echo json_encode(array('type'=>'error','message'=>'arg'));
is being consumed by jQuery but when the line:
var results = jQuery.parseJSON(responseText);
is executed, the jQuery JSON parser gives the following:
uncaught exception: Invalid JSON: <head></head><body><pre>{"type":"error","message":"oops!"}</pre></body>
Obviously the head/body/pre are not supposed to be returned.
I cannot see any hidden characters nor anything out of order in my PHP code..
Any ideas?
This one has had me stumped for the last two days. I'm using the jQuery Form plugin's ajaxSubmit function to submit a form via AJAX without reloading the page. I finally stumbled across the answer after this question showed me a parameter I hadn't noticed previously: dataType.
Behind the scenes, an iframe is being created and is actually making the call back to the server. The response from the server is being pulled from the iframe, which is bringing along with it the tags.
The jQuery Form plugin handles the situation by allowing you to specify the type of response to expect from the server. If I specify 'json' as the response type, the following few lines of code are executed to get the JSON from within the tags:
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
}
(doc is a reference to the iframe's document and xhr is the XmlHttpResponse object that ultimately gets returned from the plugin's function.)
I don't know exactly how you're making your AJAX call, but I'm guessing a similar construct (perhaps using a document fragment) will allow you to extract the necessary JSON from the response.
Try not to send header('Content-type: text/javascript');
json for php find "function send_as_json($obj)"
headers types
Set the header to application/json.

What's the best way to send JavaScript array to PHP script using GET?

I have an interactive web application powered by jQuery where users can manipulate visual objects on the screen. When done, the "state" of JavaScript objects should be sent to PHP to store into database. I'd prefer to use GET for this, but solution that uses POST to submit the data is also viable.
I'm currently thinking to serialize all JS objects using something like base64 encoding and just use something like:
var str = encode_objects();
document.location = 'result.php?result='+str;
However, something tells me there has to be some, more elegant, way than writing my own base64 encoding function in JavaScript. Isn't there something already built into JavaScript that can do the job?
Update: decoding in PHP is not the problem. I know how to decode base64, JSON, whatever in PHP. The problem is how to encode data on JavaScript side.
AJAX is out of the question. It has to be a clean GET or POST with page reload.
json_decode() should serve you well here.
If you simply append a string containing the JSON representation of your javascript object to your HTTP request, you can json_decode() it in PHP and have a PHP object ready to go.
Edit: I should mention that this page has a link to a Javascript JSON stringifier, which will convert your JS objects into the necessary JSON.
first of all, if you're updating the objects state, it should be a POST. try to keep all your GET idempotent.
second, even if you don't want to do any AJAX, JSON is still your friend. the easiest way would be to serialize your objects into JSON and send the resulting string in the POST dataload. there are many ways to decode JSON in PHP, and you're all set.
You can use this serialize function, and then unserialize it on the PHP end.
GET or POST will probably depend on the size of your data : there is a limit on the amout of data you can pass through GET (something like 2000 bytes ; more, depending on the browser).
There is also an other thing to take into account : if you are modifying data, you should use POST ; not GET, which is used to... get... data.
About the format, I would really not go for anything like a custom function doing any kind of stuff like base64 : I would definitly go for JSON, which is a native Javascript notation.
You can for instance have a look at :
wikipedia
http://www.json.org/
There are many JS libraries that can generate JSON (probably every JS Framework can ; and there are standlone libraries like this one) ; and since PHP 5.2 there are functions in PHP to encode/decode it (see json_encode and json_decode)
If it's just a simple flat array you don't need to do anything fancy, as PHP has a built in feature to parse array syntax from GET/POST variable names. Rough example below.
Javascript side:
// Do the parameter-building however you want, I picked the short/messy way
var arrayvalues = [1, 2, 'a'];
var querystring = "var[]=" + arrayvalues.join("&var[]=");
querystring += "&var[something]=abcdef";
// querystring is now "var[]=1&var[]=2&var[]=a&var[something]=abcdef"
PHP side:
var_dump($_POST);
// Remember to validate the data properly!
if ( is_array($_POST['var']) ) {
count($_POST['var']);
echo $_POST['var']['something'];
array_map('do_something_interesting', $_POST['var']);
}
I've used Jquery/JSON.
var jsonArray = $.toJSON(jsArray);
Then sent it via JQuery/Ajax

Categories