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);
}
});
}
Related
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');
I have not touched PHP or AJAX that much in about 8 years, so my memory on this is pretty low at the moment.
What I'm doing is fetching data from my database that works great.
Then I want to use AJAX to get the data from the PHP file.
My PHP file on my server is connecting to the database and fetching the table "Form".
This data is then going to be retrieved by another app trough AJAX.
I have a working PHP file, but how I should order this for the AJAX to fetch it nicely is a big question for me.
The things I have at the moment is:
PHP FILE:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM form";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row['name'];
$country = $row['country'];
$email = $row['email'];
$need = $row['need'];
$available = $row['available'];
echo "name: " . $name . "<br> Country: " . $country . " <br> Email: " . $email . "<br> Need: " . $need . "<br> Available: " . $available;
$form_data = array();
array_push($form_data)
}
} else {
echo "Null results";
}
$conn->close();
?>
AJAX FILE:
$.ajax({
url: 'url',
data: "",
dataType: 'json',
success: function(data) {
}
});
The AJAX file is not complete since I'm still wondering about these PHP results.
Right now they are just stored in variables.
What is the best way to store these results to get an fetch for AJAX here?
Should I put the results in an array and then push that array into another array?
There can be many lines in forms, and I want 1 person with data: name, country etc to be in one array. Or is it stupid to have it in an array?
I hope someone can give a little clue and help me on my way here. Long time since I have been doing PHP and a little bit unclear about the best approach here.
Been searching for a while, but nothing made so much sense to me, so I'm coming here hoping someone can guide the way.
Happy Easter.
Create an array and save all your data, then json_encode to send the data to JavaScript.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_julekgwa";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM form";
$result = $conn->query($sql);
$rows = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row['name'];
$country = $row['country'];
$email = $row['email'];
$need = $row['need'];
$available = $row['available'];
$rows[] = "{ name: " . $name . ", Country: " . $country . ", Email: " . $email . ", Need: " . $need . ", Available: " . $available . "}";
}
echo json_encode($rows);
} else {
echo json_encode([ "error" => "Null results"]);
}
$conn->close();
?>
In your ajax do the following
$.ajax({
url: 'file.php',
type: "GET",
dataType: 'json',
success: function(data) {
data.forEach(item => {
console.log(item);
});
},
error: function(data) {
console.log(data);
}
});
I stuck in the following process:
Here is the well known "Facebook Login for the Web with the JavaScript SDK example":
https://developers.facebook.com/docs/facebook-login/web
I want to get the Facebook USERID as a simple string to pass it to a PHP variable. Altough the USERID is shown when I print the $fbID, but it's not a string.
How can I get the USERID as a simple string (or a number)...?
Here is my code:
<?php
$fbID = "<script>
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = response.id;
});
}
</script>";
?>
</script>
<div id="status">
</div>
<?php
echo $fbID;
$sql = "select id from customer where fbid = '$fbID' and status = '1'";
$table = mysqli_query($conn,$sql);
list($realid) = mysqli_fetch_array($table,MYSQLI_BOTH);
echo $realid;
?>
Thank you in advance for your answers!
Use ajax to persist the ID in your database. Add the following code to your FB.api('/me', function(response) { } function:
$.ajax({
url: 'persistID.php',
type: "POST",
dataType:'json',
data: ({id: response.id}),
success: function(data){
console.log(data);
}
});
And create a seperate persistID.php file where you persist the FacebookID:
<?php
$ID = $_POST['id'];
$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 customer (fbid) VALUES ($ID)";
// Persist userid
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
So I'm building a mobile (cordova) app using a mySQL server, PHP, javascript (jQuery) but I have encountered a rather annoying problem.
When sending a test string with AJAX the recieving end, a PHP script does not receive all the data:
function testJson() {
$.ajax({
type: 'POST',
data: {
text: "hello, this is a test to see if the string is send."
},
url: 'http://a.working.url/save.php',
success: function(data) {
alert('succes');
},
error: function(data) {
alert('There was an error adding your comment');
}
});
return false;
}
then at the serverside I have a small PHP script:
<?php
$server = "localhost:3307";
//changed port to 3307
$username = "user";
$password = "pass";
$database = "test";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$comment = $_POST['text'];
echo $comment;
$sql = "INSERT INTO data (comment) ";
$sql .= "VALUES ('$comment')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
but this PHP script did not recieve the full string, when I check using:
echo $_POST['text']
It only got: "hello, this is a test to see if the" (without quotes).
If anybody can help me it would be great cause I cannot continue working on the app unless the data transfer works.
Thanks in advance.
Below is my php file to apply query
$host = "localhost";
$user = "root";
$pass = "abc123";
$databaseName = "class";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT id, name FROM lecturer");
if (mysql_num_rows($result)) {
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
header('Content-type: application/json');
echo json_encode( $data );
}
And this is my other file where i am applying javascript. I have searched a lot of same queries but could not find solution. Please help me
<script type="text/javascript">
function lecturer(){
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type:'POST',
url : 'get-data.php',
contentType :"application/json; charset-utf8",
dataType:'json',
type:'POST',
success:function(data){
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function(i, data){
$('#a1_title').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
});
},
complete: function(){
}
)};
}
$(document).ready(function(){
lecturer();
});
</script>
Please help me I have tried to solve this problem buy i am not able to do it.
Your PHP code had bad syntax since you had your array() was surrounded with curly braces rather than parentheses. You also had some errors in your $.ajax, a misplaced parentheses. In addition, you do not need an iterator ([i]) in your $.each() function - you can just get each item's bit of information by associating this iteration's values. And as #Jay Blanchard said, mysqli would be used best here.
Try the following editions:
PHP:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "test";
$con = mysqli_connect($host, $user, $pass, $databaseName);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, name FROM lecturer");
if (mysqli_num_rows($result)) {
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
JS:
<script type="text/javascript">
function lecturer() {
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type: 'POST',
url: 'get-data.php',
contentType: "application/json; charset-utf8",
dataType: 'json',
type: 'POST',
success: function (data) {
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function (k, v) {
$('#a1_title').append('<option value="' + v.id + '">' + v.name + '</option>');
});
},
complete: function () {
}
});
}
$(document).ready(function () {
lecturer();
});
</script>