skip to Main Content

I insert some data from a php form to the database. When I enter greek characters the database shows strange characters.

I have in my HTML charset="utf-8"
I tried decoding the post values and then from strange characters it gives me ????

$.ajax({
   url:postURL,
   method:"POST",             
   data:$('#add_name').serialize(),
   type: 'json',
   success:function(data)
   {
     i=1;
     var spot = document.getElementById('spot_name').value;
     window.location.href = "<?php echo base_url("index.php/Spot_preview/spot_preview/");?>"+spot;

   }
  });

php

foreach ($_POST["date"] as $key => $date) {
    $dur =$_POST['spot_duration'];
    $cat = $_POST['category'][$key];
    $price = $dur * $cat;
    $spot_name = ($_POST['spot_name']);
    $sql = "INSERT INTO spot(spot_duration,spot_type,spot_name,spot_link,customer_name,spot_date,spot_show,spot_time,spot_price,spot_category) VALUES ('".$_POST['spot_duration']."','".$_POST['spot_type']."','".$spot_name."','".$_POST['file_name_helper']."','".$_POST['customer_name']."','".$date."','".$_POST['show'][$key]."','".$_POST['time'][$key]."',$price,'".$_POST['category'][$key]."')";
    $mysqli->query($sql);
}

2

Answers


  1. Change your contentType to support different charset:

    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    

    EDIT: .. I’ve tried and tested it myself and found that there is no issues with ajax request at all and it sends the data perfectly fine but the issue is on the server side upon receiving.

    You have to set the php header like this in your method:

    header('Content-Type: application/json; charset=utf-8');
    

    I’ve sent this text ΑαΒβΓγΔδΕεΖζΗηΘθΙιΚκΛλΜμΝν and received and echoed it correctly after setting the header with charset utf-8.

    Login or Signup to reply.
  2. Try using the serializeArray() to create a JSON from post data. added a console.log for debugging.

     $('.submitBtn').click(function(e) {
         e.preventDefault();
         var sdata = $('#add_name').serializeArray();
         console.log(fdata);
       $.ajax({
           url:'',
           method:"POST",             
           data:fdata,
           type: 'json',
           success:function(data)
           {
             i=1;
             var spot = document.getElementById('spot_name').value;
             window.location.href = "<?php echo base_url("index.php/Spot_preview/spot_preview/");?>"+spot;
           }
          });
     })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search