PHP does not receive complete data when send it by AJAX - javascript

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.

Related

How to fetch data from database and display it using AJAX in an app

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);
}
});

How to get response.id as string from Facebook Login Java SDK

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();
?>

Call PHP Script from JavaScript with parameters

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);
}
});
}

Using JS to run PHP script on server

I've been at this for quite a while now, and I have pretty much no experience with PHP and I've only begun with JavaScript.
I'm attempting to run a PHP script that I have on my server from the JavaScript on the webpage using AJAX. To be honest, I don't really have much of an idea of what I'm doing.
My current code:
JS:
function Write() {
$.ajax({
type: "POST",
url: "Write.php",
data: {
'GUID': "12345678987654321",
'IP': "127.0.0.2",
'USERNAME': "George",
'BAN_REASON': "Broke my pencil."
},
success: function(data) {
console.log(data);
}
});
}
PHP:
<?php
exec("java -jar Database.jar '.$_POST['GUID']' '.$_POST['IP']' '.$_POST['USERNAME']' '.$_POST['BAN_REASON']'");
?>
(I'm also not too entirely sure that I did that String correctly, so help on that would be appreciated)
Basically, that PHP code is using a Java program I made to write to a MySQL database using the arguments that are being sent by the PHP "exec()." It's not writing to the database at all, so I'm assuming it's something with the AJAX going to the PHP function.
When "Write()" is ran, all it does is print out the PHP code to the console...
NEW CODE
<?php
//Server
$servername = "localhost";
$dbusername = $_POST['DB_USERNAME'];
$password = $_POST['DB_PASSWORD'];
$dbname = "bansdb";
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP'];
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES ('$guid', '$ip', '$username', '$ban_reason')";
if (mysqli_query($connection, $sql)) {
echo "Ban successfully added.";
} else {
echo "Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
I would not pass your DB user/password over the network. Just make a simple application password and store the password statically in the PHP with the db user/password (in HTML modify form to have APP_PASSWORD input). With parameterized queries aside from closing SQL injection you also can have single quotes in your value and don't have to worry about the query breaking (the driver handles the quoting).
<?php
//Server
$servername = "localhost";
$dbusername = 'static_db_user';//$_POST['DB_USERNAME'];
$password = 'staticpassword';//$_POST['DB_PASSWORD'];
$dbname = "bansdb";
if($_POST['APP_PASSWORD'] != 'Some generic password') {
die('Invalid Credentials');
}
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP']; // I would store IP as an unsigned int, ip2long
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES (?,?,?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, , 'ssss', $guid, $ip, $username, $ban_reason;
if(mysqli_stmt_execute($stmt)) {
echo "Ban successfully added.";
} else {
echo "Execute Error: " . $sql . mysqli_error($connection);
}
} else {
echo "Prepare Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
all it does is print out the PHP code to the console...
Do you have a web server that's configured to execute PHP code? You must realize that you cannot just run a plain php file in your browser opened from the filesystem on your "server".
Make a new file called info.php and save it to your web server. Inside it should only be this:
<?php
phpinfo();
If you see that code when you browse to it, then you do not have PHP enabled. Otherwise, you will see a lot of information about your configuration.
not too entirely sure that I did that String correctly
pretty close, but you should read up about some quotes
this might work for you:
<?php
exec("java -jar Database.jar $_POST[GUID] $_POST[IP] $_POST[USERNAME] $_POST[BAN_REASON]");

Return echo from php-function to ajax

I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.

Categories

Resources