I need help, sending data from the server.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, voltage/*, current_out, power ,temperature, reading_time*/ FROM SensorData GROUP BY id;";
$result = mysqli_query($conn,$sql);
$data1= array();
foreach ($result as $row) {
$data1[] = $row;
}
$result->close();
shaped
[{"id":"36","voltage":"16"},{"id":"37","voltage":"18"},{"id":"38","voltage":"20"},{"id":"39","voltage":"22"},{"id":"40","voltage":"26"},{"id":"41","voltage":"30"},{"id":"42","voltage":"32"},{"id":"43","voltage":"34"},{"id":"44","voltage":"36"},{"id":"45","voltage":"36"}]
and I process but I don't know exactly how to approach individual parameters. you don't know where the problem is.
<script >
$(document).ready(function(){
$.ajax({
url: "http://192.168.1.16/webput_to_mysql.php",
method: "GET",
success: function(data1) {
console.log(data1);
var voltage1 = [];
var id1 = [];
voltage1.push(data1[1].voltage);
document.getElementById("demo").innerHTML = voltage1;
}
});
});
</script>
enter image description here
The problem is that the data is coming back as a string, and you're trying to read it as JSON. You can just add the dataType option to ajax, to tell jQuery how to handle things.
$.ajax({
url: "http://192.168.1.16/webput_to_mysql.php",
method: "GET",
dataType: "json",
...
});
See the docs for more info.
Another option is to send the json header in PHP (before your echo json_encode...), which should help jQuery detect the type automatically:
header('Content-Type: application/json');
Related
I have done a lot of research on Google and StackOverflow but I can't solve this problem (that's why this question is no duplicate):
I have a js function, which is called on click (working). With this function I'm trying to call a PHP script to execute... But it doesn't react... Please tell me what's wrong (complete solution would be appreciated...)
PHP code:
<?php
$servername = "bot-sam.lima-db.de:3306";
$username = "USER379138";
$password = "pwd";
$dbname = "db_379138_1";
$q = $_POST['q'];
$a = $_POST['a'];
function alert($msg) {
echo "<script type='text/javascript'>alert('$msg');</script>";
}
echo $q . $a;
// echo and alert are not opening so i think the php script isn't executing
alert("question is " . $q);
alert("answer is " . $a);
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO knowledge_base ('question', 'answer')
VALUES ($q, $a)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
JavaScript function (which gets called properly; jQuery working):
function myfunc() {
var question = "test1";
var answer = "test2";
$.ajax({
url: 'phpscript.php',
type: 'POST',
data: {q: question, a: answer},
dataType: 'json',
sucess: console.log("SQL entry made")
});
}
I'm sorry to ask such a simple question but I just can't solve the problem...
Try to use the below code
function myfunc() {
var question = "test1";
var answer = "test2";
$.ajax({
url: 'phpscript.php',
type: 'POST',
data: {q: question, a: answer},
dataType: 'json',
success: function(result) {
console.log(result);
}
});
}
I'm running a script which is supposed to send a user ID number to a database. The database grabs a bunch of image IDs from whichever row has the matching user ID, then goes to a different table and grabs the image URLs which match the image IDs. Then it returns the URLs.
The PHP script runs fine on its own, it returns the correct URL in either straight text or JSON, as requested.
As for the jQuery, the AJAX call does indeed get to the success function, because I can ask it to document.write something there and it will do it. When I ask it to print out the data, however, the AJAX call runs forever (I think it is repeatedly calling the success function? Based on the browser telling me that it is either waiting or transferring data repeatedly). Regardless, nothing is printed to the screen despite the repeating script.
Oh, also, no errors are returned to the console.
I am not sure why it is doing this and so here I am. I've browsed through the other posts here and randomly on the internet, with no luck. Any help is appreciated!
Here is the PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
// define variables and set to empty values
$servername = "localhost";
$username = "root";
$password = "Wolf*6262";
$dbname = "Game";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET["id"];
}
$query1 = mysqli_query($conn, "SELECT imageids FROM users WHERE id = $id");
// Start user session
if ($imageIds = mysqli_fetch_array($query1)) {
fetchUrls($imageIds, $conn);
} else {
echo "Fail";
}
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = '1'");
$array = mysqli_fetch_assoc($query2);
$url = $array["url"];
exit($url);
}
$conn->close();
The jQuery:
function getUrls (userId) {
$.ajax({
type: 'GET',
data: {id:userId},
URL: 'fetchChar.php',
async: false,
dataType: 'text',
success: function (data) {
document.write(data);
document.write(userId);
}
});
}
Aaand here's where I define userId and call getUrls, it's in a separate HTML file:
var userId = <?php echo $_SESSION["id"]; ?>;
$(document).ready(getUrls(userId));
Can you please modify your script: as standard way what prefer from jQuery:
1. Change URL to url
2. Please avoid async defining
Like this
$.ajax({
type: 'GET',
data:{ id: userId },
url: 'fetchChar.php',
// async: false,
dataType: 'text',
success: function (data) {
console.log(data);
//document.write(data);
//document.write(userId);
}
});
I added console log to show the return data, so that you can make sure that your data is returning correctly from fetchChar.php file using console log.
Ended up doing the following, question solved:
Javascript file:
$.ajax({
type: "POST",
dataType: "json",
url: "fetchChar.php",
data: {id:userId},
success: function(data) {
document.write(JSON.stringify(data));
}
});
PHP file, near the end:
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = 1");
$array = mysqli_fetch_assoc($query2);
$url = $array['url'];
$url = json_encode($url);
echo $url;
exit();
}
When I tried to used ajax to post data from javascript file to php file, there was nothing displayed on php file after using
$_POST['userinput']
Here is the javascript file:
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
userinput = places[0].name.toString(); // Get user input from search box
// Pass data to userinput.php via ajax
$.ajax({
url: 'userinput.php',
data: {userinput : userinput},
type: "POST",
success: function (result) {
alert(JSON.stringify(result));
}
});
});
php file:
if (isset($_POST)) {
$servername = "localhost";
$username = "XXXXXXX";
$password = "XXXXXXXXX";
$dbname = "CALIFORNIA";
$city = $_POST['userinput']; // Nothing is posted here
// Create connection
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);
$sql = $conn->prepare("SELECT State FROM CITY as C WHERE C.City_name=$city");
$sql->execute();
$result = $sql->fetchAll();
$json = json_encode($result);
echo $json;
}
I was able to connect to the mysql database. However, there was no data posted from javascript file to php. I'm not sure what to do from this point. the value $city print out nothing. On the client side it printed out an empty object.
in your ajax function try setting dataType property
$.ajax({
url: 'userinput.php',
data: {'userinput' : 'userinput'},
type: "POST",
dataType: "text", // add this property
success: function (result) {
alert(JSON.stringify(result));
}
});
I'm trying to insert a JSON array of objects passed via a jquery $.ajax POST into a MySQL database via PHP. I've seemingly tried everything but for some reason I can't get it to work. Any suggestions would be much appreciated.
PHP
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = json_decode($_POST, true);
foreach ($data as $item) {
$worker_id = $item['worker_id'];
$response_time = $item['time'];
$video_id = $item['video_id'];
$submission = $item['response'];
$test_answer = $item['test_answer'];
$sql = "INSERT INTO nristudy (worker_id, response_time, video_id, submission, test_answer)
VALUES ('$worker_id', '$response_time', '$video_id', '$submission', '$test_answer')";
if (!($conn->query($sql))) {
die($conn->error);
}
}
if (!$conn->commit()) {
echo "Transaction commit failed";
exit();
}
$conn->close();
?>
Javascript
var json = JSON.stringify(submissions);
$.ajax({
type: "POST",
url: "http://hci.cs.wisc.edu/nri/store_data.php",
data: json,
success: function(data){
console.log("Success: " + data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... look at the console for more information!');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
The solution to your problem depends heavily on what the error is. However, one thing that is pretty clear is that you should be escaping the strings you are trying to put into the query.
I recommend that you switch to using PDO and prepared statements as you will not have to worry about escaping anything and can rely on PDO to take care of it when you prepare the statement.
You might also want to try serialize instead of json_encode but if it works there is a chance that SQL injection is still a real big possibility for you.
how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.
$('#bot_guar').click( function () {
//var rows = $("#tabla1").dataTable().fnGetNodes();
var oTable = $('#tabla1').DataTable();
var data1 = oTable.rows().data();
//alert(data1.length);
$.ajax({
type:"POST",
dataType:'json',
url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
data:data1,
success: function(data){
alert(data);
}//success
});
});
this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.
You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:
$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];
Now, Connect to your database and insert this data through your php script:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Its good practice to send a response to your call back functions so you can do this:
echo json_encode(array('status'=>"Success", message=""));
Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:
var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}
I hope that helped!