- Home /
How to send data form to server using json in unity
I want to using json to send the form to my server here is my C# code
public string db_url="http://localhost/";
IEnumerator SaveAllPlayerPrefs(object[] parms)
{
string ourPostData = "{\"bone\":\"42\"}";
Hashtable headers = new Hashtable();
headers.Add("Content-Type", "application/json");
headers.Add("Cookie", "Our session cookie");
byte[] pData = System.Text.Encoding.UTF8.GetBytes(ourPostData);
WWW webRequest = new WWW(db_url + "SaveAllPlayerPref.php", pData, headers);
yield return webRequest;
}
and here is my php code:
<?php
$sql_connect = mysql_connect("localhost", "root", "") or die ("no DB Connection");
mysql_select_db("example") or die ("DB not found");
$bone = $_POST['bone'];
mysql_query("INSERT INTO save_game (bone) VALUES ('$bone');");
mysql_close($sql_connect);
?>
When i run it this code its running, but when i check the database, its not save the value of bone. It's save the empty string to bone, i want it to save 42.. in my database bone is varchar(100) and utf8_general_ci.
Can someone explain to me? thx before:)
$bone = $_POST['bone'];
After this line of code is run in the server, what is the content of the variable $bone? Have you checked? I suspect it's null. Don't you have to use json_decode or something in PHP?
If that is the case, this is definitely not a Unity question.
Answer by kmfjsc · Nov 30, 2016 at 08:10 AM
I've done for doing this below. Let's go : ==>
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class btnGetData : MonoBehaviour {
void Start()
{
gameObject.GetComponent<Button>().onClick.AddListener(TaskOnClick);
}
IEnumerator WaitForWWW(WWW www)
{
yield return www;
string txt = "";
if (string.IsNullOrEmpty(www.error))
txt = www.text; //text of success
else
txt = www.error; //error
GameObject.Find("Txtdemo").GetComponent<Text>().text = "++++++\n\n" + txt;
}
void TaskOnClick()
{
try
{
GameObject.Find("Txtdemo").GetComponent<Text>().text = "starting..";
string ourPostData = "{\"plan\":\"TESTA02\"";
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
//byte[] b = System.Text.Encoding.UTF8.GetBytes();
byte[] pData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
///POST by IIS hosting...
WWW api = new WWW("http://192.168.1.120/si_aoi/api/total", pData, headers);
///GET by IIS hosting...
///WWW api = new WWW("http://192.168.1.120/si_aoi/api/total?dynamix={\"plan\":\"TESTA02\"");
StartCoroutine(WaitForWWW(api));
}
catch (UnityException ex) { Debug.Log(ex.Message); }
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
JSON vs XML for Unity C# 1 Answer
jSON data error Unity3d 0 Answers
Error ambiguous reference with Json 1 Answer
A node in a childnode? 1 Answer