Sending json using native javascript - php

I want to use native javascript to send a json to php file. Why my $_POST from get-translation.php is empty?
var xmlhttp;
json_data = JSON.stringify(a_data);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","get-translation.php",true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(json_data); // json_data is simple json

$_POST only works for the default content type application/x-www-form-urlencoded.
For any other type of data - including JSON - you need to parse the raw input stream.
file_get_contents('php://input') will return the raw request body. Since this is JSON, you need to use json_decode to parse the json data into an associative array.
$jsonData = json_decode(file_get_contents('php://input'));

You need to make the JSON data a string:
json_data = JSON.stringify(json_data);

Related

Data from javascript code insert to mysql database

Here I have a script which help me to get places from google places API. So now I want to store all this into mysql but how? I'm new to mysql and php, and how to store data that I get from google places to database?
What I need to do here? Can someone show me on my example...
How to combine php and javascript;
CODE: http://jsbin.com/AlEVaCa/1
So I need to store data which I got from google:
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
I want to store all place.name,website ... etc. data to mydatabase. How to do that?
Is there any way to store this data?
Use AJAX to send data to PHP file.
Use jQuery $.post()-AJAX method to send data to php file
data = "name="+name+"&place="+website;
$.post('file_to_store.php', data, function(data) {
//Here you can get the output from PHP file which is (data) here
});
Pure javascript way
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
data = "name="+name+"&place="+website;
xmlhttp.open("POST","file_to_store.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
In file_to_store.php receive all data from $_POST[] global array
if(isset($_POST)){
$name = $_POST['name'];
$website = $_POST['website'];
//Do same for all other variables
//Steps to insert Data into Database
//1. Connect to database
//2. Select Database
//3. Generate Database Insert Query
//4. Run mysql Query to insert
// Return appropriate return back to Javascript code - Success or Failure
}
Use serialize($data) then put it into database, use unserialize() after getting data from db.
Addition: this will store raw data, you'll probably need a parser also.
Addition 2: sorry I assumed that you got an array.
Alternative solution if you got non-array data:
you can use base64_encode($raw_data) to store and base64_decode($encoded_data) to use the encoded data coming from SQL.
Fundamentally, your JavaScript program, executing on the client side, does not have direct access to the SQL database on the host. You must use AJAX to issue requests to the host, and the host-side software must be programmed to handle them. Lots(!) of existing tutorials on this subject are already out there ... everywhere.

Passing javascript object to php file using ajax post method

Iam desperately trying to pass a json object using ajax post method to a php file, decode it and pass something back.
Php's json_last_error displays 4, which means Syntax error.
this.send = function()
{
var json = {"name" : "Darth Vader"};
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","php/config.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+json);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
};
};
};
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data["name"];
}
?>
You have to encode it to json if you want to send it as json.
xmlhttp.send("data="+encodeURIComponent(JSON.stringify(json)));
currently what you have will send something like data=[Object object].
The variable json is a JavaScript object which is not json. JSON is a data-interchange format which is basicly a subset of javascript. see http://json.org
var object = {"name" : "Darth Vader"};// a JavaScript object
var json = '{"name" : "Darth Vader"}';// json holds a json string

How to pass JSON via ajax to PHP?

I'm trying to pass a json string to php via ajax and php is not decoding it properly. a vardump in php after the decode always returns null. Can anyone tell me what I'm doing wrong. Big thanks!!!
var addObj= {"facility":"Baptist Medical Center",
"osb":"Jacksonville",
"office":"North Branch"};
var JSONstr = JSON.stringify(addObj);
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var rt = xmlhttp.responseText;
alert(rt);
}
}
xmlhttp.open("GET","jsontest.php?addObj="+JSONstr,true);
xmlhttp.send();
//php code in jsontest.php
<?php
var_dump(json_decode($_GET['addObj'], true));
?>
//php returns null
Try urldecodeing the parameter first:
var_dump(json_decode(urldecode($_GET['addObj']), true));

Passing Json using Ajax Post via javascript to php not working

Hi i am trying to send Json via Ajax to PHP using Javascript. The data is sent correctly by index.html when I view it on firebug. It shows Json type with the correct data.
However, it seems that I am unable to read the JSON on php. I am unable to access it using $_POST.
I tried using $_POST['name'] and there is not response.
When i try using $_POST, the response is array.
Can you please help me?
Here is my javascript code.
<html>
<head>
<script type="text/javascript">
//Create Http request depending on browser
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;}
}
// Function to create
var url = "control.php";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
var data=JSON.stringify({"name":"John", "time":"2pm"});
xmlhttp.send(data);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
This is my php code
<?php
include_once('JSON.php');
$json = new Services_JSON();
$value = $json->decode($_POST['name']);
echo $value;
?>
Have been working on this for days and I really appreciate any help that you can offer.
Thank you!
here it's:
print_r($GLOBALS['HTTP_RAW_POST_DATA']);
I think that it needs to parse the whole post first.
<?php
include_once('JSON.php');
$json = new Services_JSON();
$value = $json->decode($_POST);
echo $value;
?>
But also do you need these includes?
http://www.php.net/manual/en/function.json-decode.php
include_once('JSON.php');
$json = new Services_JSON();
can you not just do this?
echo json_decode($_POST)
An even better solution (see here) is use:
$json = json_decode(file_get_contents("php://input"), true) ?: [];
print_r($json);

Sending Javascript Object to PHP via Ajax

I'm learning Ajax by failure and have hit a wall:
I have an array (if it matters, the array is storing number id's based on what checkboxes the user checks) that is written in Javascript.
I have a function that is called when the user clicks the 'save' button. The function is as follows:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var url = "create_amenities.php";
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
My question is:
What can I put in this function to pull the array into the php script I'm trying to call ('create_amenities.php')?
furthermore, should I try using JSON? And if so, how could I send a JSON object via ajax?
Thanks in advance.
If your array has more then 1 dimension or is an associative array you should use JSON.
Json turns a complete array structure into a string.
This string can easily send to your php application and turned back into a php array.
More information on json: http://www.json.org/js.html
var my_array = { ... };
var json = JSON.stringify( my_array );
In php you can decode the string with json_decode:
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json));
Loop over the array and append encodeURIComponent('keyname[]') + '=' + encodeURIComponent(theArray[i]) + '&' to the query string each time.
furthermore, should I try using JSON?
You could, but it would mean decoding JSON at the other end instead of letting normal form handling take care of it.
And if so, how could I send a JSON object via ajax?
There is no such thing as a JSON object. JSON takes the form of a string, and you can include strings in query strings (just remember to encodeURIComponent).
I found this question useful for Javascript enthusiasts.
Sending a javascript Object, be it js array or js object, you must stringify the setup before putting it to the server for decode & processing.
Stringifying a js object:
Based on your function:
case of Javascript Array object
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
case of Javascript Object object
let my_obj = {
name: "Daniel",
age: 23,
location: "Nigeria"
}
my_obj = JSON.stringify(my_obj);
Ones on point you can push this to the server, as per use case, u're working with AJAX GET method in sending your stringified object to the server.
Here is the full code:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
document.getElementById('message').innerHTML = this.responseText;
// if your returned response is in json, please, do ensure to parse the response before displaying
// like this JSON.parse(this.responseText)
}
}
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
var url = "create_amenities.php?my_json=" + my_array;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here are what i noticed out of your codes:
You don't need to call xmlhttp inside of xmlhttp object again, all you need is the this
I included the my_json parameter that holds the array object you are sending to the server.
Now, here in the server, you will need to catch the object and convert it to php readable object.
$my_json = $_GET['my_json'];
$my_json = json_decode($my_json);
Now, you can do whatever you wish it, because it has now become a full php array.
Example to pick the first array option:
$first = $my_json[0];
echo json_encode($first) // hahaha, you echoed it for AJAX to display
// i used to json_encode() to convert from php object to a js readable object
First off, yes, do not write ajax by hand. You are unlikely to produce something that truly works on all browsers.
The best approach to your actual problem would be to submit your array as cgi parameters.
If the checkboxes are in a form, you need to do very little - simply submit the form,
<form><input type=checkbox ...><input type=checkbox ...>
$.post("test.php", $("#testform").serialize());
See http://api.jquery.com/jQuery.post/ for more details on how to do that.
Your list will turn up as an array in PHP.
Or to augment your own example with something very simple, do this:
url = url + '?checkboxes=' + checkboxes.join(',');
Now just split it inside PHP and you've got it back!

Categories