How can I send HTML data to PHP using JSON? - javascript

I can't seem to understand how to send data from my Client-side HTML to my Server-side PHP (Which already means their not in the same folder and are not running in the server) and only get a Notice of an unidentified variable and a Fatal error: Cannot access empty property.
I tried the methods in W3Schools and still no luck. And just to be sure I tried to copy paste it. Still the same.
So my question is: How can I send this simple Client-side HTML/JavaScript data:-
<script>
function sender(){
obj = "tblname";
// how to send that data to the php server-side.
}
</script>
To this PHP:-
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "mydb");
$result = $conn->query("SELECT * FROM ".$objData);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
Using JSON?
If anyone could elaborate and show me a sample it would be great.
Again, I am a noob/newb in using JSON and have no long term background (I just started like a week ago and that had a lot of problems already) and am completely clueless when it comes to this type of client-to-server communication.
I Just need the simple sender code (from the JavaScript) and the receiving code (from the Php) one or two lines will do; with a short description on how they work.
I'm using Windows 7, Wamp3.0.6 and Chrome.
PS: I got that from W3Schools. Yes it didn't work. And please don't be Vague. Thank you!

You can make ajax call form client side to server file and can send data with get method
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "path of your php file",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
})

-_-
Everyone seems to try and over complicate and over think this when the simple answer would have been this code.
function caller(){
myData = "myTbl";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "bring.php?q="+myData,true); //sends myData to the php. You can change the GET to POST if ya want to be extra safe but either way, the php won't care anyways.
xmlhttp.send();
}
The above code is from the client server and sends the data of myData to this Server-side php.
<?php
$q = $_REQUEST['q']; //the receiver of the data. You can use explode() to separate them into pieces and turn it into a jigsaw puzzle if ya want.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} // how to connect is not important in my question but it is important for you to be able to connect to the database.
// now for the important stuff
$sql = "SELECT * FROM ".$q." "; // I had to extend it with a space because sometimes it's misunderstood.
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
$outp = array();
while($row=mysqli_fetch_assoc($result))
{
$outp[] = $row;
}
echo json_encode($outp); //sends the data gathered from the database table back to the client as a JSON file, and you are done.
?>
It took me 6 hours worth of studying with a lot of internet surfing and trials and errors.
And like I said; I am a newb at JSON so it's pretty much understood that I don't understand AJAX. Like, AT ALL.
I'm sorry if ya think I sound like an idiot but let's face it, almost all of us were idiots at one point while trying to learn programming. So, I'm surprised why some people are just plain rude here. Thanks. Somehow I'm not really surprised that their also like this here. Makes my internet social life a bit more boring.
So next time, do me a favor and instead of being totally rude, just answer the question if you have one.

You cannot transfer an object via HTTP as it is. You need to transform it into a string you can put into the body of your HTTP-POST Request:
try {
var jsonString = JSON.stringify(anyJsonObject);
//send it to the server
} catch(ex) {
//handle error if anyJsonObject wasn't a valid JSON object. Remember: Not every JS object is a JSON object too.
}
The opposite way is:
try {
var jsonObject = JSON.parse(anyJsonString);
} catch(ex) {
//handle error if anyJsonString was malformed
}

Related

AngularJS JSON not arriving php

i am having the following problem, i have a service that makes a http request, and when i try to get the response throws a parser error, and that is because the response is not ready when it tries to parse the response.
here is the code
simpafAPIservice.getSimulacao($stateParams.id).success(function(response){
console.log(JSON.stringify(response[0].info));
$scope.simuladorInfo.cliente = response[0].cliente;
$scope.simuladorInfo.info = JSON.parse(response[0].info);
console.log(JSON.stringify(response[0].info));
setTimeout(function(){
for(var i=0;i<$scope.simuladorInfo.info.simuladores.length;i++){
$scope.addDataGraphic(i);
}
},100);
});
}
When i console.log the response it prints an empty string, which is odd, that's why it throws this parser error.
My question is how can i do .success function only when the response is ready?
Edit:
in the end the problem is other, i am storing a JSON in a database, but when the JSON has very information it doesn't arrive at php.
here's my php code:
<?php
$id = $_POST["id"];
$id_col = $_POST["id_col"];
$tipo = $_POST["tipo"];
$cliente = $_POST["cliente"];
$info = $_POST["info"];
date_default_timezone_set("Europe/Lisbon");
$data = date("Y-m-d H:i:s");
require 'connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($id!=""){
$sql = "UPDATE `Simulacoes` SET `info`='".$info."' WHERE `id`='".$id."'";
}else{
$sql = "INSERT INTO `Simulacoes`(`id_col`, `tipo`, `data`, `cliente`, `info`) VALUES ('".$id_col."','".$tipo."','".$data."', '".$cliente."', '".$info."')";
}
if ($conn->query($sql) === TRUE) {
echo $info;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
here's the response i get:
{"data":"","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"params":{"id_col":"1","tipo":"Património Reforma","info":{"simuladores":[{"nome":"ii","info":{"prazoReforma":20,"empreendimentos":{"empreendimentos":[{"id":"1","nome":"Oporto Place","localizacao":"Porto","$$hashKey":"object:50"}],"tipologias":{"0":"Loft","19":"T2","37":"T3"},"plantas":{"0":"3.1","1":"6","2":"8","5":"3.2","12":"2.1","13":"7","14":"2.2","15":"5"},"pisos":[{"id":"2","piso":"1","$$hashKey":"object:69"}]},"entrada":"20000","duracao":"35","taxa":"5","montante":82000,"prestacao":"414","prestacao_seguros":"440","renda_liquida":"320","resultado":-120,"patrimonio":134367},"$$hashKey":"object:38","imovel":{"empreendimento":{"id":"1"},"tipologia":"Loft","planta":"3.1","piso":"2","info":{"condominio":"50","renda":"400 ","preco":"102000 ","id":"1"}},"hide":1}],"montanteTotal":134367,"pensao":"569","idadeActual":"45","idadeReforma":"65","pmII":120,"pmTotal":120}},"url":"php/guarda-simulacoes.php","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
As you can see, when i echo $info it returns nothing, an empty string, but in data.config.params i get all params. Anyone knows why is this happening?
Your codes looks ok, which is taking promise from And executing code in its success. I think instead of setTimeout you should use $timeout which will run $digest cycle when timeout complete
Code
simpafAPIservice.getSimulacao($stateParams.id).success(function(response){
console.log(JSON.stringify(response[0].info));
$scope.simuladorInfo.cliente = response[0].cliente;
$scope.simuladorInfo.info = JSON.parse(response[0].info);
console.log(JSON.stringify(response[0].info));
$timeout(function(){
for(var i=0;i<$scope.simuladorInfo.info.simuladores.length;i++){
$scope.addDataGraphic(i);
}
},100);
});
}
According to the docs, $http.success returns data in the first argument, which is converted to JSON only if the active transformResponse can detect is is the appropriate format:
Angular provides the following default transformations:
...
Response transformations
($httpProvider.defaults.transformResponse and
$http.defaults.transformResponse):
If XSRF prefix is detected, strip it (see Security Considerations
section below). If JSON response is detected, deserialize it using a
JSON parser.
If your server is responding with an empty string (which seems the case here)
then it will not be detected as a JSON object and will remain an empty string.
Check your server response, it may be responding with no body and an error status. One thing to watch for if you are requesting data from a different domain (even if it's ultimately the same server) is same-origin policy.

PHP and JQuery weird behaviour

I have a 3-tier architecture. The db is oracle, the business/logic layer is php, while the front end is html/JavaScript. My business/logic layer have a bunch of unit tests that only pass if the requirements are met. The problem occurs when I wire the business layer and front end via javascript. After a lot debugging, I found the sources of the problem:
JavaScript code causing error.
function getAllUsers() {
var allUsers = [];
$.ajax ({
url: '../php/get-all-users.php',
success:function(data){
allUsersJSON = JSON.parse(data);
console.log(allUsersJSON);
for (var i = 0; i < allUsersJSON.length; i++){
allUsers[i] = allUsersJSON[i].USER_NAME;
}
console.log(allUsers);
}
});
return allUsers;
}
../php/get-all-users.php
<?php
include_once 'Database.php'
$db = Database::instance(); // Singleton to initialize db.
echo json_encode($db->getAllUsers());
?>
Database.php fragment.
public function createConnection($username, $password, $connectionString){
$this->_connection = oci_connect($username, $password, $connectionString);
if (!$this->_connection) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
throw new Exception("Database connection failed. Please check constructor arguments.");
}else{
//print "Database connection established.\n";
}
}
In one of my tests, I tried echo json_encode($db->getAllUsers()); and get a result, "[\"USER_NAME\":\"userName\"]". In get-all-users.php, if I comment out everything, and echo the string I get from the tests, the web page now loads fine, but of course this is not what I desired. Furthermore, if I uncomment include_once 'Database.php' in get-all-users.php and comment out oci_connect in my Database.php, the web page loads fine. This made me conclude that the root of the problem is oci_connect.
Did anyone else have a similar experience? I tried googling but found no result. If you need more information to make light of this problem, I'd gladly spew them out.
Edit:
I'm working in linux. My team mate is working with Windows and he have no problems like this.

jquery ajax to php script not saving data

I have the following jQuery ajax call to a php script:
actualHtml = $('div').html(); // could this line be causing an issue?
$.ajax({
type: 'POST',
url: 'save-html-css-action.php',
data: {
'htmlTextToSave': htmlTextToSave,
'actualHtml': actualHtml,
'userId':userId
},
success: function(msg){
alert(msg);
}
});
php:
$htmlCssToSave = $_POST['htmlTextToSave'];
$userId = $_POST['userId'];
$actualHtml = $_POST['actualHtml'];
$mysqli = new mysqli($servername, $sqlusername, $sqlpassword, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
//printf("Connect failed: %s\n", mysqli_connect_error());
echo "Connection failed: ".mysqli_connect_error();
exit();
}
$mysqli->query("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values ('".$htmlCssToSave."',".$userId.",'".$actualHtml."')");
echo "success";
/* close connection */
$mysqli->close();
but when I check the database, the data isn't there. Am I doing something wrong in the jquery/php combo (meaning the ajax call)? I'm getting a javascript "success" alert, so it's hitting the script, but I'm not sure why the info isn't being inserted.
The table datatypes are medium text for both the htmlcsstosave and the actualhtml columns, and int for userid (not the primary key, this is a foreign key to another table)
so I added a an error alert and this is the output
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'margin-0'>
<head>
</head>
<body cl' at line 1
As we discussed, the issue is with escaping and sanitizing data. If you used prepared statements, it will handle it for you. let's have a look at how that would work:
Prepare the statement:
$stmt = $mysqli->prepare("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values (?,?,?)");
Bind your parameters:
$stmt->bind_param('sis', $htmlCssToSave, $userId, $actualHtml);
Then execute your statement:
$stmt->execute();
Then you should be good to go. The prepared statement should handle the data sanitization for you now.
Resouces:
mysqli prepare
mysqli bind_param
mysqli execute
Can you post the CREATE TABLE statement for the user_saved_data table?
In general, I'd recommend just tracing it through and see where the data gets lost.
For example, can you echo the query you are generating and run in manually in MySQL? You may have a syntax error in the SQL being generated...

PHP json_encode then getJSON issue in javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

How do I auto-refresh my php chat-script?

I am having trouble getting my php chat script to auto refresh when mysql data is changed. I have done a good bit of research and it seems a lot of other people's solutions are more complicated then what I need (I'm going for something very basic).
I do not know any javascript so detailed comments would be appreciated if js is involved.
Here is the php script that I have created. It is functioning (at least for me).
include 'connect2.php';
echo "
Enter a Message:
<form method=post action='' name=chat>
<input type=text name=message>
<input type=submit name=chat value=Submit>
</form>
";
if (isset($_POST['chat'])) {
$message = $_POST['message'];
mysql_query("INSERT INTO chat set message='$message',user='$_SESSION[username]'");
}
$sql = "select * from chat order by id desc limit 15";
$result = mysql_query($sql) or die ("An error has occured with in the database.");
while ($data = mysql_fetch_assoc($result)) {
$db_message = $data['message'];
$db_user = $data['user'];
echo "$db_user : $db_message <br>";
}
?>
Any help would be appreciated, thanks! :)
You can use setInterval and jQuery library ajax functions to check for it.
For example, it's very simple to do with jQuery:
$(document).ready(function() {
// check once in five seconds
setInterval(function() {
$.get('/script.php', {do: 'new_messages'}, function(response) {
if(response == 1) {
window.location.reload();
}
});
}, 5000);
});
And somewhere on server:
if(isset($_GET['do']) && $_GET['do'] == 'new_messages') {
// some your code that detects if there's any new messages, and sets
// $there_are_new_messages to true, if there's any
...
if($there_are_new_messages) {
echo 1;
exit; // avoid further output
}
}
Please remember, that for this to work you need to ensure that there's no output before ajax block, as you can get into unexpected results.
Also consider that using output is not a good practice at all to show your script everything is ok. Better way is to set HTTP header with corresponding response code.
The best way to do this in your case would probably be using Ajax (and jQuery) and refreshing every X seconds.
Ready Handler- http://api.jquery.com/ready/
Javascript Timer- http://www.w3schools.com/js/js_timing.asp
Ajax Request- http://api.jquery.com/jQuery.post/
PHP json_encode- http://php.net/manual/en/function.json-encode.php
$( document ).ready(function() { //set up refresh timer on page load
var refreshTimer = setInterval(function(){refreshMessages()},5000); //creates timer to request every 5 seconds
});
function refreshMessages(){
$.post( "getMessages.php", function( data ) { //fire ajax post request
alert("Got messages: " + data); // this just alerts the data when the request is done, you'll probably want to format/print
});
}
On the getMessages.php side of things, you'll want to pull your messages from the database how you normally would. In this case, json encoding your php messages array would be an easy way for you to iterate the returned object.
<?php
$messages = // get messages array from database
echo json_encode($messages);
?>

Categories