PHP not receveing characters with accents from Ajax [duplicate] - php

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 5 years ago.
I made a script in Ajax that simply recovers data from MySQL and gives it back to PHP when a select option is changed:
$country = $_POST['country'];
$sql = "SELECT id,name FROM regions WHERE idcountry='$country' ORDER BY name ASC";
$result = mysqli_query($connexion->db, $sql);
$count_row = $result->num_rows;
$regions_arr = array();
while( $row = mysqli_fetch_array($result) ){
$idregion = $row['id'];
$nameregion = htmlentities($row['name']);
$regions_arr[] = array("id" => $idregion, "name" => $nameregion);
}
// encoding array to json format
echo json_encode($regions_arr);
And in my PHP page I have this script:
<script>
$(document).ready(function(){
$("#sel_country").change(function(){
var countryid = $(this).val();
$.ajax({
url: '/include/ajax/getRegions.php',
type: 'POST',
data: {country:countryid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#sel_region").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_region").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
</script>
Everything works at is has to, except for some of the names recovered that have special characters, for instance "Genève" or "Zürich". Those values are not showed at all, my option has the correct value for the id but it looks empty in the name.
I searched and I tried with uriencode but it doesn't seem to change, any idea how to fix this?
Thank you!
UPDATE AND SOLUTION
I solved this by changing my tables to utf8m64 in this way (for each table):
ALTER TABLE
`table_name`
CONVERT TO CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Then in my script Ajax I added this:
mysqli_set_charset($link, 'utf8mb4');
And then it finally works :)

Try like this
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "xml/html/script/json", // expected format for response
contentType: "application/json"
});

Related

Ajax request dataType json

I'm having troubles displaying a value in an input field. I did this in the past, and I haven't got a clue where my code goes wrong.
I have an input field with id="input" and a button with id="button". This is my jquery code:
$("#button").click(function() {
var uid = <?php echo $user['uid']; ?>;
$.ajax({
url: "php/fetchUserData.php",
method: "POST",
data: {
uid: uid
},
dataType: "json",
success: function(text) {
$("#input).val(text.bedrijfsnaam);
}
});
});
And here is the code on of the php/fetchUserData.php file:
<?php
include_once 'dbc.php';
if($_POST){
$uid = $_POST['uid'];
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$query = mysqli_query($dbc, $sql);
$result = mysqli_fetch_assoc($query);
echo json_encode($result);
}
?>
UPDATE:
var_dump($result) does displays the associative array.
console.log(text) gives no result.
if I change dataType to text and echo out $result['bedrijfsnaam'] instead of json_encode($result) all goed well. The problem is that I want to load more than just the bedrijfsnaam (= company name).
UPDATE 2:
If I use the very same code but with another table in the database it does works. I really don't have a clue what can be the problem here...
I've been searching what could be the matter with the users table, and I notice cardinality is 0, although there are 4 rows in the table. In the other tables of the database, the cardinality value represents the number of rows. Could that have anything to do with this problem?
UPDATE 3:
Instead of the query:
$sql = "SELECT * FROM users WHERE uid = '$uid'";
I tried:
$sql = "SELECT bedrijfsnaam FROM users WHERE uid = '$uid'";
And it worked! Then I started adding column names, and all went well until a certain column: land (meaning country) a varchar column just like many others in the table.
What could be the reason this particular column causes the error to happen?
I know this became a phpmyadmin question instead of a php or jquery question. Should the question be moved to the sql part of the forum?
Assuming this is your actual code, your issue is likely stemming from not actually referencing and updating a field.
Something like this should be what you need:
$("#input").val(text.bedrijfsnaam)
I don't know anything about PHP and I don't think it matters. I think you got most part right. In success of your ajax request, set the text value of the input field.
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$("id='button'").text(text.bedrijfsnaam);
}
});
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$('#input').val(text[0]);
}
});
hmtl maybe better works than .val
You're wrong with your jquery selection of your div: you're missing an " in your code.
hope it will work

jQuery display object value

I am trying to access some info in my database and displaying the result of my query in some textboxes.. my code works but it says object object..
here's my jQuery code:
jQuery('body').on('click', '.update_button', function() {
var manufacturer_part = jQuery(this).val();
jQuery.ajax({
url: '/codes/clearhouse_processor.php',
type: 'POST',
data: {update_key: manufacturer_part},
dataType: 'json',
success: function(result) {
jQuery('#update-manufacturer-part').val(result.part_number);
jQuery('#update-manufacturer').val(result.manufacturer);
jQuery('.update-form').stop();
jQuery('.update-form').slideToggle('slow');
jQuery('html,body').animate({
scrollTop: jQuery('.update-form').offset().top-60
}, 750);
}
});
});
and here's my php code...
if(isset($_POST['update_key'])){
$manufacturer_part = $_POST['update_key'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('part_number')));
$query->from($db->quoteName('clearing_house'));
$query->where($db->quoteName('part_number') . '='.preg_replace("/[^0-9,.]/", "", #$manufacturer_part) );
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
echo json_encode($results);
}
and btw, I am using joomla here...
thanks in advance,
jQuery('#update-manufacturer-part').val(result[0].part_number);
it is receiving an array from the server
by the result you gave
and if you want to see all the results that you receive
jQuery('#update-manufacturer-part').val(result[0].part_number);
_.map(result,function(){return part_number; }).join(",")
on the query itself update the fields that you need to get
$query->select($db->quoteName(array('part_number', 'manufacturer', 'field3', 'fieild4')));

Insert Data mysql using Ajax and PHP

I am want insert data to MySQL Database using Ajax and PHP
My Ajax Code
$(function(){
$('#submit').click(function(){
var Name = $('#InputName').val();
var Email = $('#InputEmail').val();
var Phone = $('#InputPhone').val();
var Username = $('#InputUser').val();
var Status = $('#selectStatus').val();
//Ajax for add Dealer
$.ajax({
url : "../page/addnewDealer.php",
type : "POST",
async : false,
data :{
Submit:'adduser',
Name : Name,
Email:Email,
Phone:Phone,
UserName:Username,
Status:Status
},
success :function(result){
alert(result);
}
});
});
});
and PHP code is
if(isset($_POST['Submit'])=='adduser')
{
$pass= get_rand_id();
$time= get_currunt_Time();
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
$result = mysql_query($insertData);
}
It is a registration page when i am add a user using this program . program replies success massage but in database nothing happen
change
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
to
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('".$_POST[Username]."','".$pass."','".$_POST[Status]."','".$_POST[Name]."','".$_POST[Phone]."','".$_POST[Email]."','".$time."','".$time."')";
Add braces { } around your $_POST variables in the query. Also, check your spelling of your field names - is "contEmaill" correct? (Two 'l's).
You can simply take post data to a variable and append it to the sql query.

Insert data into mysql using ajax

I'm trying to insert data to mysql, tried everything but nothing worked
here is my code :
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#rating-btn").click( function(){
var teaching=$("#teaching").val;
var marking=$("#marks").val;
var helpfulness=$("#helpfulness").val;
var difficulty=$("#difficulty").val;
var grade=$("#grade").val;
var com=$("#com").val;
$.ajax({
type: "POST",
url:"db/ajax.php",
data:"teaching=" + teaching +"&marking="+ marking +"&helpfulness="+ helpfulness
+"&difficulty="+difficulty+"&grade="+grade+"&com="+com,
dataType: "dataString",
cache: "true",
success: function(msg,string,jqXHR){
$("#results").html(msg+string+jqXHR);
}
});
});
});
ajax.php
<?php
error_reporting(0);
require 'db/connect.php';
$teaching = $_POST['teaching'];
$teaching = mysql_real_escape_string($teaching);
$marking = $_POST['marking'];
$marking = mysql_real_escape_string($marking);
$helpfulness = $_POST['helpfulness'];
$helpfulness = mysql_real_escape_string($helpfulness);
$difficulty = $_POST['difficulty'];
$difficulty = mysql_real_escape_string($difficulty);
$grade = $_POST['grade'];
$grade = mysql_real_escape_string($grade);
$com= $_POST['com'];
$sql = "INSERT INTO ratings VALUES ( '', '{$teaching}', '{$marking}' ,'{$helpfulness}', '{$difficulty}' ,'{$grade}' , '2' , '{$com}')";
mysqli_query($sql);
?>
connect.php
<?php
$db= new mysqli('localhost','root','','instructors');
if($db->connect_errno){
die("we are having some problems");
}
?>
I tried to the sql code and it worked in the phpmyadmin page.
So what is missing that is preventing the data from going into the database?
UPDATE:
when i try to echo all the variables and thier values apears normally
i also tried to do this :
$sql = "INSERT INTO `ratings` VALUES ( '', '3.5', '2.5' ,'4.5', '2.5' ,'1' , '2' , 'hello how are you')";
it does not insert this values to the database
but when i put the same sql code in the phpmyadmin its adds a row perfectly
It seems, your Js-code has some missing paranthesis. >ou should replace "val" with the function call "val()"
var teaching=$("#teaching").val();
var marking=$("#marks").val();
var helpfulness=$("#helpfulness").val();
var difficulty=$("#difficulty").val();
var grade=$("#grade").val();
var com=$("#com").val();
Afterwards, you should get some values in PHP-land, which can be inserted.
Additionally, you are mixing procedural and OOP-code.
mysqli_query($sql);
... is at least missing the connection as first parameter. But since you saved an instance of mysqli_connection already in $db try replacing it with:
$db->query($sql);
What everyone said about mysql and mysqli. Plus you have to add the & between the vars.
data:"teaching=" + teaching +"&marking="+ marking +"&helpfulness="+ helpfulness
+"&difficulty="+difficulty+"&grade="+grade+"&comment="+comment,
fixed my problem by just using the object $db that i already created in connect.php in the ajax.php
instead of writing
query(&sql)
the solution is :
$db->query($sql);
thanks for everyone for the help.

Ajax, PHP, MySQL returning sql table

I have the following Ajax code to send information from an HTML form to a PHP file.
$(document).ready(function(){
$('#txt').load( '../../do_comment.php' );
});
$(function(){
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#user_name").val();
var comment = $("#user_comment").val();
var ID = '2'; //must change for each post
$.ajax({
type: "POST",
url: "../../do_comment.php",
data: {user_name:name, user_comment:comment, ID:ID},
success: function(){
$('#txt').load( '../../do_comment.php' );
},
error:function(e){alert("it failed");}
});
});
});
In my PHP file I declare the variables like this:
$name = $_POST[user_name];
$comment = $_POST[user_comment];
$ID = $_POST[ID];
And correctly populate my database with this:
if($_POST[user_comment] != Null) {
$sql = "INSERT INTO $table_name (post_ID, user_name, comments)
VALUES ('$ID','$name', '$comment')";
$result = #mysql_query($sql,$connection) or die(mysql_error());
}
The problem is none of the variables will echo any sort of value, and when I try to query the database it only works if I hard code the ID value in instead of using the variable.
$data = mysql_query("SELECT * FROM $table_name WHERE post_ID =
'".mysql_real_escape_string($ID)."'") or
die(mysql_error());
Use the following when gathering from $_GET/$_POST/$_REQUEST:
$name = $_POST['user_name'];
$comment = $_POST['user_comment'];
$ID = $_POST['ID'];
Notice the tics. Proper syntax is $_POST[''].
Have you checked the database to make sure the proper values are being inserted?
Also, if the post_id is an integer, don't use tics
SELECT * FROM table WHERE post_ID = 1234
NOTICE: do not use MySQL_*, it has been deprecated in PHP 5.5. Use MySQLi or PDO. Watch out for SQL injections as well, especially when using MySQL_*.

Categories