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.
Related
Hi I get This error in my console using sse
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
js code is :
if (typeof(EventSource) !== "undefined")
{
var source = new EventSource("../api/updateWellData.php?uid=<?php echo $node_id ?>");
source.onmessage = function(event) {
var response = JSON.parse(event.data);
document.getElementById("result").innerHTML = response.test;
// some code like the above line
};
}
else
{
// refresh the page every 30 secs
}
The PHP Code is :
header('Cache-Control: no-cache');
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/event-stream");
require_once("../resources/config.php");
if (isset($_GET['uid']))
{
$uid = $_GET['uid'];
while (1)
{
$query = Query("SELECT * FROM well_data_last WHERE well_detail_id = $uid");
$result = fetch_array($query);
echo json_encode($result);
ob_end_flush();
flush();
sleep(1);
}
}
This is my first time using sse I used the following documents : mozilla | w3schools
This error occurs when your PHP code outputs text in the wrong format.
This may be either a PHP error message (all of which are outputted as raw HTML), or some other text on the page which does not fit the text/event-stream format.
If the output of the PHP file does not match the format required by text/event-stream, it will fall back to using text/html. Javascript requires event streams use the text/event-stream content type so the JS console will show an error, but this is just a symptom of the actual problem - to fix the issue you need to fix your PHP.
In OP's case, the issue is with their echo statement. All data outputted to the stream must be proceeded by data:, and ended with a newline \n. The stream itself must end with another newline to indicate that no more data: messages follow.
To fix the error, OP should change
echo json_encode($result);
to
echo "data: " . json_encode($result) . "\n\n";
Another issue with OP's code is that there is no protection against SQL-injection in the database query. While this is irrelevant to the issue at hand, it is worth pointing out that prepared statements should be used instead.
I hade the same problem and the problem was a syntax error in the php file which showed an error message.
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
}
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...
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.
I am trying to retrieve a single row from a MySQL table using a mysqli statement. I've tried several different iterations of code, subtly changing the structure based on various previous questions from this forum, and others, but can't seem to get any result other than 'null'.
This is part of a larger script which is called via an Ajax request with jQuery. I've included both the PHP and the Javascript below, though I'm fairly confident in the JS being OK (preparing to be told otherwise now...).
Any suggestions as to where I'm going wrong would be very much appreciated as I can't see the wood from the trees anymore, and am just going around in circles.
PHP:
//initiate new mysqli object
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name); //custom subclass, this definitely works as is used in other scripts on the server
//prepares DB query. Query has been tested on phpmyadmin and returns the expected data set
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute(); //no params to bind, so execute straight away
$stmt->bind_result($item);
$stmt->fetch();
$dataset = $item->fetch_row();
$response[0] = $dataset; //returned data forms part of larger dataset
echo json_encode($response); //return the entire dataset to a jquery Ajax request
die;
JS:
//this definitely works as objects have been returned via the 'success' function as the code was being developed
$.ajax({
url : "items/populate-home-page-script.php",
type : "GET",
data : {data:toSend},
dataType : "json",
success : function(data){
alert(data[0]);
},
error : function(jqXHR, textStatus, errorThrown){
alert(textStatus+','+errorThrown);
}
});
return false;
I have also tried using fetch_assoc() and fetch_row() as part of the PHP query, taking direction from the PHP reference material here and here. I have also read through these questions from Stackoverflow this, this, and this, but I still seem to get a return of null for every different code combination I try.
As I've said in a code comment, I know that the link to the DB works as I've used it in other scripts, and in other areas in this script - so there's no reason why this object wouldn't work either. I also know that the query returns the expected data when inputted to phpmyadmin.
The returned data is just a number of strings, any all I would like to do is store around 16 returned datasets to an array, as part of a loop, and then return this array to the Ajax request.
You are using "AuctionMySQLi" which appears to extend the regular Mysqli driver. I'll assume it does this correctly.
You're using prepared statements which is probably an overkill in this case. You could accomplish the same thing with something like this (php 5.3, mysqli + mysqlnd):
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
echo json_encode($result->fetch_all());
} else {
echo json_encode(array());
}
$retrieve_link->close();
If you're using an older php version, or mysqlnd is not available, you can also do
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
} else {
echo json_encode(array());
}
$retrieve_link->close();
I also understand that you want to limit the number of results. In both cases, a good way of getting it done is to use a LIMIT statement in SQL. This is lower the overhead overall at source. Otherwise you can array_slice to slice the output of result->fetch_all() in solution 1, or $output in solution 2.
Finally, if you insist in using prepared statement read the note at
http://ca2.php.net/manual/en/mysqli-stmt.bind-result.php
and analyze provided example:
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute();
$stmt->bind_result($itemName, $itemCat, $endDate, $auctionType, $highBidder);
$output = array();
while($stmt->fetch()) {
$output[] = array($itemName, $itemCat, $endDate, $auctionType, $highBidder);
}
echo json_encode($output);
$retrieve_link->close()
It looks to me like you may have some confusion about ->fetch() and ->fetch_row(). You should use one or the other, but not both.
Try this to retrieve your result set:
$stmt->execute();
while ($dataset = $stmt->fetch_row()) {
$response[] = $dataset; //returned data forms part of larger dataset
}
This will append each row of your result set to your $response array.