I am creating simple request for GET a "message" with title etc from MySQL server.
So, I've got something like this in my AngularJS:
$http({
url: 'http://localhost/webpack/downloadMessage.php',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response){
console.log("CHECKED");
console.log(response.data);
}, function(response) {
alert('something wrong');
})
})
}
Just a request for data. But I'm confused with my php code, because I'm a beginner, can you help me what's wrong? I want just whole table where section = 3.
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
if(!isset($_POST)) die();
session_start();
$response = [];
$con = mysqli_connect('localhost', 'root', '', 'projekt');
$query = "SELECT * FROM messages WHERE section='3'";
$result = mysqli_query($con, $query);
echo json_encode($result);
It's without errors, but in my console i've got this:
CHECKED {current_field: null, field_count: null, lengths: null,
num_rows: null, type: null}
According to a manual result of mysqli_query is either a mysql_result or false if query fails.
To get data from mysqli_result you need to fetch it, for example with fetch_assoc:
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
echo json_encode($row);
Also, there can be cases when you have no results ($row will be empty) or your query fails ($result will be false). These cases should be checked in your script and appropriate response should be returned.
Related
I have a PHP file in which I'm getting data from a geoJSON file, I'm going through the data and storing what I need in a new associative array, then sorting it. I need to make an AJAX call to this PHP file to get the sorted data through, but it's throwing "SyntaxError: Unexpected token a in JSON at position 0", the "a" being "a"rray... from the response, so I believe it's going through as a string.
My PHP file:
<?php
$countryBordersJson = file_get_contents("../js/countryBorders.geojson");
$countryBordersJsonData = json_decode($countryBordersJson, true);
$dataLength = count($countryBordersJsonData['features']);
$countryNames = array();
for($i = 0; $i < $dataLength; $i++) {
$countryName = $countryBordersJsonData['features'][$i]['properties']['name'];
$countryIsoa2 = $countryBordersJsonData['features'][$i]['properties']['iso_a2'];
$country[$i]['countryName'] = $countryName;
$country[$i]['iso_a2'] = $countryIsoa2;
array_push($countryNames, $country[$i]);
}
sort($countryNames);
$data = json_encode($countryNames);
$decode = json_decode($data, true);
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['data'] = $decode;
header('Content-Type: application/json');
var_dump($output);
?>
My AJAX request:
$.ajax({
url: "libs/php/countryBorders.php",
dataType: "json",
type: "GET",
success: function(result) {
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.warn(jqXHR.responseText, textStatus, errorThrown);
}
})
I'm still getting to grips with JSON, PHP etc. so would appreciate any help.
Are you sending the data with var_dump ? It cannot work like that. You need to send a string :
echo json_encode($output);
I am currently in the process of learning how to retrieve encoded JSON data from a mySQL database on an apache server and decode the JSON into an instance of my own custom struct;
struct Person: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64
var firstName: String
var lastName: String
}
here is my method for the network request on xcode
func dataRequestDownload() {
let baseURL = URL(string: "http://example.com/db_request.php?action=request")
DispatchQueue.main.async {
if let url = baseURL {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
let decoder = JSONDecoder()
let person = try? decoder.decode(Person.self, from: data)
print(person)
}
}
task.resume()
}
}
}
}
My issue is that person prints as nil which makes me think the data isnt being decoded properly.
This is my PHP script for the GET request.
<?php
$con=mysqli_connect("127.0.0.1","root","example_password","example_database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM person";
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con)
?>
Finally I am not sure this info matters, but in the mySQL database the table is set up just like my struct where id is the PRIMARY key. If more information is needed let me know in the comments, but as far as I know this is all that seems connected to my issue.
Edit: Some other possibly important information is when calling print(data) and print(response) I get
48 bytes
{ Status Code: 200, Headers {
Connection = (
"Keep-Alive"
);
"Content-Length" = (
48
);
"Content-Type" = (
"text/html; charset=UTF-8"
);
Date = (
"Thu, 17 Jun 2021 18:43:02 GMT"
);
"Keep-Alive" = (
"timeout=5, max=100"
);
Server = (
"Apache/2.4.46 (Win64) PHP/7.3.21"
);
"X-Powered-By" = (
"PHP/7.3.21"
);
} })
the URL is exempt from this of course.
Per the request in the comments; having done this
let object = try? JSONSerialization.jsonObject(with: data)
print(object)
I get
Optional(<__NSSingleObjectArrayI 0x281510080>(
{
firstName = John;
id = 0;
lastName = Doe;
}
)
)
Edit2: Upon running
do {
let person = try decoder.decode([Person].self, from: data)
print(person)
} catch {
print(error)
}
the following error appears
typeMismatch(Swift.Int64, Swift.DecodingError.Context(codingPath [_JSONKey(stringValue: "Index 0", intValue: 0),
CodingKeys(stringValue: "id", intValue: nil)], debugDescription:
"Expected to decode Int64 but found a string/data instead.", underlyingError: nil))
Here is the actual JSON upon visiting the URL
[{"id":"0","firstName":"John","lastName":"Doe"}]
When decoding JSON, it's helpful to use do/try/catch so that you can actually see what the error is.
It looks like, in this case, you have an array (which is clear from your PHP code), but you're trying to decode a single object. Try this:
do {
let person = try decoder.decode([Person].self, from: data)
print(person)
} catch {
print(error)
}
Then, since you'll have an array in person (which might be more accurately named people at this point), you'll want to access it with something like person.first
Update, based on added code in your edits:
That error is telling you that id is a String in the JSON. Either adjust your Person model to use String for the type of id instead of Int64, or adjust your database and or PHP code to use a number instead of a String for the id.
i want to post a json object to php.
var user = {username:"test", password:"test", name:"test",
email:"test#hotmail.com"};
var str_json = JSON.stringify(user);
$.ajax({
url: '/register_API.php',
type: 'post',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log('success');
},
data: user
});
}
In php i want to insert it into mysql:
$data = file_get_contents('php://input');
$json = json_decode($data,true);
$username = $json['username'];
$password = $json["password"];
$email = $json['email'];
$insertSql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$password', '$email');";
The $data string contains: username=test&password=test&name=test&email=test%40hotmail.com, but i can't get the variable by decoding...
Thanks in advance!
Change data: user to data: str_json and then
change $data = file_get_contents('php://input');
to $data = $_POST['data']
You're not sending a JSON string, you're sending a Javascript object which jQuery is translating to a set of parameters in the outgoing POST request. Your data will be available to PHP in $_POST - no need to decode it first.
Look for it like this:
$username = $_POST['username'];
$password = $_POST["password"];
$email = $_POST['email'];
I think you want to send raw JSON as text and have that be in the post body and not treated as an encoded form.
In this case I think your PHP code is right. Send the stringified JSON as you are, but set the data type to dataType: "text".
I think you will be able to read it with
$data = file_get_contents('php://input');
I think you can use
//works like explode, but splits your data where finds "=" and "&" too.
$output = preg_split( "/ (=|&) /", $data);
This will return an array of your data. where:
$output[0]="Username";
$output[1]="test";
This can be useful if you have fixed data.
JQuery
function save() {
imageData = $(".sigPad").signaturePad().getSignatureImage();
consumeData = $('#consume').val();
$.ajax({
type: "POST",
url: "",
data: {'signatureasimage' : imageData, 'consume' : consumeData },
dataType: 'json',
cache: false,
success: function(response){
alert(response.msg);
/*var imageUrl = response['signature_image'];
d = new Date();
$(".signatureImage").attr("src",imageUrl);
if (response.status == true) {
window.location.href = "<?php echo ROOT_URL.'esignup/attendees_list.php?icode='.$icode;?>";
}*/
},
error: function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
};
PHP
$data = array();
$confirmationData = array();
$data['attendee_id'] = $attendeeId;
$data['is_consume_the_provided_meal'] = $_POST['consume'];
$data['signature_image'] = $destination;
$data['confirmed'] = 1;
if($confirmedAttendee){
$sql = "SELECT * FROM `".TBL_ATTENDEE_CONFIRMATION."` WHERE `attendee_id` = '.$attendeeId.'";
$confirmationData = selectFrom($sql);
update_array('tbl_attendee_confirmation', $data, array('attendee_id' => $attendeeId));
$confirmationData = selectFrom($sql);
}else{
var_dump("it went through insert array");
insert_array('tbl_attendee_confirmation', $data);
}
$data = array();
$data['msg']="Testing, testing.";
echo json_encode($data);
Jquery ajax does post request with data imageData and consumeData. imageData and consumeData are strings. Copying to file works and the data updates the table. The problem is I get parsererror when I want to get imageUrl so I can update the sigImage with the new image source. I commented the part where I replace the image src with new imageURL. Does anyone know the issue?
Error shows up as "alert('Error.\nParsing JSON Request failed.');" from code. Error still shows up with test code.
Try doing this in your PHP:
echo json_encode($data, JSON_FORCE_OBJECT);
I don't completely understand it, but in my experience if you are returning an array you've built in PHP to be parsed using the ECMAScript JSON object, you need to use the JSON_FORCE_OBJECT constant to ensure that it returns a JSON object instead of a JSON array.
json_encode constants
You also could try outputting the header for JSON before echoing your JSON encoded array, gimme a sec.
header('Content-Type: application/json');
Also here
I'm tapping into the Twitter firehose to store some tweets based on some set filters for analytic purposes.
I have written a PHP script that opens a connection to the Twitter stream, and keeps it open while(!eof)...so this basically stays open indefinitely.
However, I have it set so that it stops after 5 seconds. I want to use AJAX to call this script ever 5.5 seconds (offset to make sure they don't collide), and then re-loop on success etc...
The problem is that my function doesn't seem to be receiving a "success" signal. What's going on here?
Here are the relevant portions of my code:
$(function() {
makeRequest();
});
function makeRequest(){
console.log("Getting tweets...");
$.ajax({
url: "./php/store_tweets.php",
success: function(){
console.log("Success!");
makeRequest();
}
});
}
The Script:
<?php
$start = time();
$expAddress = "HOSTNAME";
$expUser = "USERNAME";
$expPwd = "PASSWORD";
$database = "DBNAME";
$opts = array(
'http' => array(
'method' => "POST",
'content' => 'keywords,go,here'
)
);
// Open connection to stream
$db = mysql_connect($expAddress, $expUser, $expPwd);
mysql_select_db($database, $db);
$context = stream_context_create($opts);
$instream = fopen('https://USERNAME:PASSWORD#stream.twitter.com/1/statuses/filter.json', 'r', false, $context);
while (!feof($instream)) {
if (time() - $start > 5) { // break after 5 seconds
break;
}
if (!($line = stream_get_line($instream, 100000, "\n"))) {
continue;
} else {
$tweet = json_decode($line);
// Clean before storing
// LOTS OF VARIABLES FOR BELOW...REMOVED FOR READABILITY
// Send to database
$ok = mysql_query("INSERT INTO tweets
(created_at, from_user, from_user_id, latitude, longitude, tweet_id, language_code,
place_name, profile_img_url, source, text, retweet_count, followers_count,
friends_count, listed_count, favorites_count)
VALUES
(NOW(), '$from_user', '$from_user_id', '$latitude', '$longitude', '$tweet_id', '$language_code',
'$place_name', '$profile_img_url', '$source', '$text', '$retweet_count', '$followers_count',
'$friends_count', '$listed_count', '$favorites_count')");
if (!$ok) {
echo "Mysql Error: " . mysql_error();
}
flush();
}
}
?>
You should try javascript function setInterval.
<script type="text/javascript">
var myVar=setInterval(function(){makeRequest()},5000);
function myStopFunction()
{
clearInterval(myVar);
}
</script>