This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 4 years ago.
I'm trying to send data through AJAX to a PHP file to then upload to my database using SQL. I've already altered my table to allow UTF-8 to be inserted. When I insert using a form it works fine but when using AJAX to send data it won't send it.
For example, I'm trying to send some text and an emoji to a PHP file which then uploads to my database.
I've already got <meta charset="utf-8"> at the top of my page and even added header("Content-Type: text/html; charset=utf-8"); to the page and PHP file as I've seen some other posts mention that but it hasn't worked.
Here is the AJAX function:
$detail = $('#post').text(); //Gets text from div
$.ajax({
url: 'edit.php',
type: 'post',
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
data: {detail: $detail},
datatype: 'html',
success: function() {
console.log($detail);
}});
The $detail is simply the value from a div and all the edit file simply does is UPDATE the table.
When I console.log the data it comes back with text and an emoji but it doesn't insert into my database.
While writing this, I noticed that adding 'application/x-www-form-urlencoded;charset=utf-8' stops the whole process from working but I'm not sure why.
Backend Code for those that asked:
<?php
$host = "hostname";
$user = "user";
$password = "pass";
$db_name = "database";
$tbl_name = "table";
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$detail = $_POST['detail'];
// Add your validation and save data to database
if(strlen($detail) <= 5000) {
$stmt = mysqli_stmt_init($conn);
$sql = "UPDATE $tbl_name SET detail = ?";
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $detail);
mysqli_stmt_execute($stmt);
}
mysqli_stmt_close($stmt);
}
}
?>
NOTE: This works when I pass it through a form but via AJAX when adding an emoji such as 😂 it doesn't work.
Add mysqli_set_charset($conn, 'utf8mb4'); to all php files after connecting to database.
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 months ago.
So basically I have a working HTML Form that when filled out and submitted goes tomy SQL database, I have check multiple times and it works as should unless there is a ' character in the data being submitted. If there is a ' it simply won't submit the form. I don't know why this is and was hoping someone would know and potentionally help my resolve the problem so that that character can be used. I am using PHP to connect my HTMLform to my SQL server.
All the columns in my SQL Table are VARCHAR(no.)
EDIT:
This is the code on my php file.
<?php
// database connection code
// $con = mysqli_connect('localhost', 'database_user', 'database_password','database');
$con = mysqli_connect('localhost', 'root', '7520NHOj','db_connect');
// get the post records
$txtName = $_POST['txtName'];
$txtEmail = $_POST['txtEmail'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];
// database insert SQL code
$sql = "INSERT INTO `tbl_contact` (`fldName`, `fldEmail`, `fldPhone`, `fldMessage`) VALUES ('$txtName', '$txtEmail', '$txtPhone', '$txtMessage')";
// insert in database
$rs = mysqli_query($con, $sql);
if($rs)
{
echo "Your Contact form has been submitted, we will get back to you as soon as possible!";
}
?>
Use mysqli_real_escape_string function for solving problem.
Use the following code.
<?php
// database connection code
// $con = mysqli_connect('localhost', 'database_user', 'database_password','database');
$con = mysqli_connect('localhost', 'root', '7520NHOj','db_connect');
// get the post records
$txtName = mysqli_real_escape_string($con,$_POST['txtName']);
$txtEmail = mysqli_real_escape_string($con,$_POST['txtEmail']);
$txtPhone = mysqli_real_escape_string($con,$_POST['txtPhone']);
$txtMessage = mysqli_real_escape_string($con,$_POST['txtMessage']);
// database insert SQL code
$sql = "INSERT INTO `tbl_contact` (`fldName`, `fldEmail`, `fldPhone`, `fldMessage`) VALUES ('$txtName', '$txtEmail', '$txtPhone', '$txtMessage')";
// insert in database
$rs = mysqli_query($con, $sql);
if($rs)
{
echo "Your Contact form has been submitted, we will get back to you as soon as possible!";
}
?>
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have a failing PDO Prepared DELETE statement inside a PHP file called with AJAX.
My AJAX call looks like this:
var data = {action: "deleteTask", value: "1"};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: data,
success: function(data) {
alert(data);
},
error: function() {
alert("Something's wrong!");
}
});
My ajax.php looks like this:
<?php
...
function delete(){
$return = "something must be right...";
require('connect.php');
$sql = "DELETE FROM 'tasks' WHERE 'task_id' = ?";
$stmt = $dbcon->prepare($sql);
$stmt->execute(array($_POST["value"]));
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
Here is a sample of connect.php:
<?php
// Configuration
$username = 'me';
$password = '1234';
$server = 'localhost';
$database = 'mydb';
try {
$dbcon = new PDO("mysql:host=$server;dbname=$database",$username,$password);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $er) {
echo 'ERROR: ' . $er->getMessage();
}
?>
A few things that I have already established:
1) My ajax call works fine if I comment out everything related to the PDO statement;
2) My connect.php file works, because I have tested it with standard HTML forms (as opposed to calling it from ajax);
3) there are no typos in the names of the table and the field of the DB;
4) The $_POST["value"] gives the the right value corresponding to the record I am trying to delete.
5) When I set brakepoints on each line related to the PDO, when I am at the line: $stmt->execute(array($_POST["value"])); and I click "Step Into", it jumps straight to the alert("Something's wrong!"); in the Ajax (nothing gets executed in the ajax.php after that line)
I have spent many hours trying to figure out what is wrong with this and read all the posts that exist on the subject, but my problem seems particular, so any help would be much appreciated! Thanks.
You should look into the browser's the Net responce. It should show a SQL error. If you use MySQL your query should look:
DELETE FROM `tasks` WHERE `task_id` = ?
And if it is PostgreSQL:
DELETE FROM "tasks" WHERE "task_id" = ?
Seems like you forgot to add the code:
delete();
Once you will add it, you will actually call the function and not only declare it.
Another option, try and set PDO to print error. http://php.net/manual/en/pdo.errorinfo.php Then you will the error printed back in the console.
I'm pulling data from a database using JSON and MySQL in my android app. It successfully pulls the "Title" and "Image_URL" fields from my database. But my "Content" field, which contains large paragraphs of text, returns null. When I type in some short text, it shows up. But when copy/pasting my long paragraphs it returns null.
the "Content" field I'm using in my database is set to "text". I also tried "longtext", and "varchar (2000)". I tried deleting all inverted commas from my paragraphs too, as I read they can cause issues.
Below is my php code. I don't know anything about php as I'm a beginner to all this but use this simple code and it usually works.
Thank you
<?php
$host = "************";
$db = "***********";
$user = "**********";
$pass = "*********";
$con = mysql_connect($host, $user, $pass);
mysql_select_db($db) or die(mysql_error());
$Title=$_REQUEST['Title'];
$result = mysql_query("SELECT * FROM Reviews WHERE Title= '$Title'");
while($row = mysql_fetch_assoc($result) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
I'm using Alban Xhaferllari AJAX multiple uploader and I have an issue with inserting data to my database. Here is the link to the upload.php. here is my code that it doesn't work.
function success($file_path)
{
$conn = new mysqli("localhost", "xxxxx", "xxxxxxxx");
$conn->set_charset("utf8");
$conn->select_db("xxxxxxx");
$id = $conn->query("INSERT INTO Galerie (Poza) VALUES($file_path) ");
}
This is the code from their website dunno what's wrong cause I dont get any error but still it doesn't insert.
Please correct following it works for me
$id = $conn->query("INSERT INTO Galerie (Poza) VALUES('$file_path') ");
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Update database info with onclick button
I have a onclick button which calls a function with php inside of it to query a database. The code works fine separately, but together, it does nothing. After looking through some answers it says I have to place the query database code into a separate PHP file, and somehow call that file on the users onclick ? Is that the best option, and if so, can anyone provide an example of how I would call the PHP database lookup file from an onclick button ? Thanks in advance.
<div onClick="newUser();"
style="position:absolute;display: block; cursor:pointer; top: 100px; left: 600px;">
<img src="assets/invite.png">
</div>
<head>
<script type="text/javascript">
<?php
function newUser(){
// Make a MySQL Connection
$me = json_decode(#file_get_contents('https://graph.facebook.com/me?access_token=' . $cookie['access_token']));
$uid = $me->id;
echo "$uid";
$hostname="";
$username="";
$password="";
$dbname="mpsuserdata";
$usertable="userdata";
$connection = mysql_connect($hostname, $username, $password);
mysql_select_db($dbname, $connection) or die ("Could not connect");
mysql_query("INSERT INTO userdata
(id, name, startdate, enddate, shop) VALUES('11111111' , 'UK', '$startdate' , '$enddate' , 'test' ) ")
or die(mysql_error());
echo "Data Inserted!";
}
?>
</script>
Use AJAX..
AJAX is the very much easy solution for you. you can put JavaScript function on your button on-click event.
and call jquery.ajax function for that. you can now use your php page for execute query for your database.
function ajaxfunc()
{
jQuery.ajax({
type: "GET",
url: "query_page.php",
data: "queryfields",
success: function(html){
// data you want to return on.
}
});
}
i think this makes you happy and satisfied.
this can be done through ajax post/get method for more please go through the link