My UTF-8 characters become unrecognised after passing with AJAX - encoding

I query names out of my UTF-8 database, if I echo them with php, they print just fine in a browser.
When I send them back however with Ajax, they become unrecognisable. After hours of debugging, I can't find my mistake.
This is the ajax code:
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'getnames.php',
type: 'GET',
dataType: 'json',
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
data: {
name: selected_race.concat("__".concat(query)),
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
}
And this is the get names.php
<?php
// parameters from URL
$type_entry = $_GET['name'];
$split = explode("__",$type_entry);
$race = "Race_".$split[0];
$name = "%".$split[1]."%";
// connect to the database and get the names
require 'connect_sql.php';
//$names_query = "Select Name FROM " .$race ." WHERE Name Like " .$name;
$names_query = "Select Name FROM ".$race." WHERE Name LIKE '".$name."'";
$query_result = mysqli_query($db, $names_query) or die("Zit hier de fout".mysql_error());;
$names = array();
while($row = mysqli_fetch_array($query_result)){
$names[] = "{ \"Name\": \"$row[0]\" }";
}
//output to browers
header('Content-Type: text/javascript; charset=UTF-8');
echo "[\n" .join(",\n", $names) ."\n]";?>
Do you see what I am doing wrong?

Related

What i did wrong specifying bootbox message, i'm getting an error?

I'm using this function to send in other page where I'm updating user permission level.
var setPermLevel = function(userId, value)
{
$.ajax({
type: "POST",
url: "/user/setPermLevel",
data: {id: userId, value: value},
success: function(data)
{
if(data[0]['error']) bootbox.alert(data[0]['error']);
else bootbox.alert(data[0]['message'], function() { location.reload(); });
}
});
};
I'm trying with that code to send back a message to bootbox to show up to user, but I'm getting anyway an error from bootbox "Please specify a message".
if(isset($_POST['id']))
{
$userId = $_POST['id'];
$value = $_POST['value'];
$rslt = "[";
if(User::isAdmin($_SESSION['user']) < 6 && $value > 4) {
$rslt .= '{"error":" You can\'t acces that."}';
}
else {
$q = DB::prepare('UPDATE `users` SET `Admin` = ? WHERE `ID` = ?');
$q->execute(array($value, $userId));
$data .= '{"message":" Succesfully"}';
}
$rslt .= "]";
echo $rslt;
}
This is the error:
Uncaught Error: Please specify a message
at sanitize (bootbox.js:109)
at Object.window.bootbox.window.bootbox.exports.dialog (bootbox.js:450)
at Object.window.bootbox.window.bootbox.exports.alert (bootbox.js:246)
at Object.success (toolBox.js:3470)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
What I did wrong, can anyone help me?

How to save multiple image path to database while image is saved to server

I have this code on how to save multiple images to server using codeigniter and ajax
I have gone through this code, though i'm still learning Ajax, Json and Javascript. But i want to be able to save the image paths (for all images uploaded to the database so i can be able to retrieve them for each user. Just the was facebook image upload is). The code below is in my view file.
$(document).ready(function(){
$('#profiles').change(function(){
var files = $('#profiles')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++){
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1){
error += " " + count + "Invalid Image File(s)"
}
else {
form_data.append("profiles[]", files[count]);
}
}
if(error == ''){
$.ajax({
url:"<?php echo base_url(); ?>pastors/upload_image",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function() {
$('#upl_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data){
$('#upl_images').html(data);
$('#profiles').val('');
document.getElementById("success_msg").style.transition="all 0.9s ease";
document.getElementById("success_msg").style.opacity=0.5;
document.getElementById("success_msg").innerHTML="Images Successfully Uploaded";
//alert(pastor +" "+ "You saved a new report");
setTimeout(remove_prodiv, 1500);
}
})
}
else{
alert(error);
}
});
});
And this is my controller
public function upload_image(){
if($_FILES["profiles"]["name"] != ''){
$output = '';
$config["upload_path"] = './programphoto/';
$config["allowed_types"] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["profiles"]["name"]); $count++){
$_FILES["file"]["name"] = $_FILES["profiles"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["profiles"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["profiles"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["profiles"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["profiles"]["size"][$count];
if($this->upload->do_upload('file')){
$data = $this->upload->data();
//$image=$data["file_name"];
//$this->pastors_model->SaveReport($image);
$output .= '
<div class="col-md-2">
<img src="'.base_url().'programphoto/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
}
}
echo $output;
}
}
This code uploads images perfectly to the server. but i just want a way out to saving the paths to database
I got this working.
All I did was to send the file names to the model each time it uploads,
like this:
if($this->upload->do_upload('file')){
$data = $this->upload->data();
$output .= '
<div class="col-md-2">
<img src="'.base_url().'folder/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$filename = $data['file_name'];
$this->Model->save_file($filename);
}

Joomla website is getting 303 redirect loop

My website is sometimes getting a 303 redirect loop on the main page. This gives me an error when trying to view the site "the webpage has a redirect loop", but most of the time is loads fine. But, the 303 redirect doesn't look good for SEO. I'm running the Joomla 3.2.3 with the Zo2 framework. I used the firefox live http headers tool and this is what it shows:
HTTP/1.1 303 See other
Date: Sat, 19 Apr 2014 06:42:44 GMT
Server: Apache mod_fcgid/2.3.10-dev
X-Powered-By: PHP/5.4.26
Set-Cookie: 81f5073a1f9d10dc244e07c98216335e=hb7mb5k3v0vftstcgtdbonikq6; path=/; HttpOnly
Location: /
Cache-Control: max-age=600
Expires: Sat, 19 Apr 2014 06:52:44 GMT
Content-Length: 0
Keep-Alive: timeout=5
Connection: Keep-Alive
I went through and disable every plugin in Joomla one at a time and when I disable the Zo2 framework plugin the 303 redirect went away. I've asked on their forums and they haven't been able to help me. So, I searched through all of the files in the zo2 plugin directory for the word redirect and this is what I found.
These two are in the site.megamenu.js
!function ($) {
$(document).ready(function ($) {
// when clicking on menu
redirect();
var duration = 0;
var $parent = $('.zo2-megamenu');
var hover_type = $parent.data('hover');
if ($parent.data('duration')) {
duration = $parent.data('duration');
}
function redirect() {
$('.dropdown-toggle').on('click',function(e){
if($(this).parent().hasClass('open') && this.href && this.href != '#'){
window.location.href = this.href;
e.preventDefault();
}
});
}
I have other website running on this server using the same .htaccess and php.ini files so I don't think that could be the problem, because they are not getting a redirect. I would appreciate some help with this. The website is http://www.betterfreestuff.com
/**
* Zo2 Framework (http://zo2framework.org)
*
* #link http://github.com/aploss/zo2
* #package Zo2
* #author Hiepvu
* #copyright Copyright ( c ) 2008 - 2013 APL Solutions
* #license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later
*/
!function ($) {
$(document).ready(function ($) {
// when clicking on menu
redirect();
var duration = 0;
var $parent = $('.zo2-megamenu');
var hover_type = $parent.data('hover');
if ($parent.data('duration')) {
duration = $parent.data('duration');
}
if (duration && (hover_type == 'hover')) {
var timeout = duration ? duration + 50 : 500;
$('.nav > li, li.mega').hover(
function(e) {
onMouseIn(this, timeout);
}
,
function (e) {
onMouseOut(this);
}
);
} else if (hover_type == 'click') {
$('.mega-nav').find('.dropdown-submenu').hover(
function(e) {
onMouseIn(this, 100);
}
,
function (e) {
onMouseOut(this);
}
);
}
// for first li tag
function redirect() {
$('.dropdown-toggle').on('click',function(e){
if($(this).parent().hasClass('open') && this.href && this.href != '#'){
window.location.href = this.href;
e.preventDefault();
}
});
}
function onMouseIn (e, timeout) {
var $this = $(e);
if ($this.hasClass('mega')) {
$this.addClass ('hovering');
clearTimeout ($this.data('hoverTime'));
$this.data('hoverTime',
setTimeout(function(){$this.removeClass ('hovering')}, timeout));
clearTimeout ($this.data('hoverTime'));
$this.data('hoverTime',
setTimeout(function(){$this.addClass ('open')}, 100));
} else {
clearTimeout($this.data('hoverTime'));
$this.data('hoverTime',
setTimeout(function () {
$this.addClass('open')
}, 100));
}
}
function onMouseOut (e) {
var $this = $(e);
clearTimeout($this.data('hoverTime'));
$this.data('hoverTime',
setTimeout(function () {
$this.removeClass('open')
}, 100));
}
/** BEGIN: off canvas menu **/
var showOffCanvasMenu = function () {
var $offcanvas = $('.offcanvas');
var $body = $('body');
var $wrapper = $('.wrapper');
$body.addClass('overflow-hidden');
$wrapper.addClass('offcanvas-push');
var $overlay = $('<div />').addClass('offcanvas-overlay').appendTo('body');
$overlay.css({
top:0,
right:0,
bottom:0
}).fadeIn();
$overlay.click(function() {
$body.removeClass('overflow-hidden');
$wrapper.removeClass('offcanvas-push');
$offcanvas.removeClass('active');
$('.offcanvas-overlay').remove();
});
};
var hideOffCanvasMenu = function () {
var $body = $('body');
var $wrapper = $('.wrapper');
var $offcanvas = $('.offcanvas');
$body.removeClass('overflow-hidden');
$wrapper.removeClass('offcanvas-push');
$offcanvas.removeClass('active');
$('.offcanvas-overlay').remove();
};
$('[data-toggle=offcanvas]').click(function() {
var $offcanvas = $('.offcanvas');
$offcanvas.toggleClass('active');
if ($offcanvas.hasClass('active')) {
showOffCanvasMenu();
}
else {
hideOffCanvasMenu();
}
});
$('body').on('click', '.sidebar-nav a', function() {
if (!$(this).hasClass('nav-oc-toggle')) hideOffCanvasMenu();
});
$('body').on('click', '.sidebar-close', function() {
hideOffCanvasMenu();
});
// new off canvas submenu
$('body').on('click', '.nav-oc-toggle', function() {
var $this = $(this);
var $parent = $this.closest('.nav-parent');
if ($parent.find('> .submenu').hasClass('in')) $this.removeClass('icon-caret-up').addClass('icon-caret-down');
else $this.removeClass('icon-caret-down').addClass('icon-caret-up');
});
/** END: off canvas menu **/
});
}(jQuery);
I searched for 303 in all of the files on my server and these files came back with redirect statements.
cms.php
public function redirect($url, $moved = false)
{
// Handle B/C by checking if a message was passed to the method, will be removed at 4.0
if (func_num_args() > 1)
{
$args = func_get_args();
/*
* Do some checks on the $args array, values below correspond to legacy redirect() method
*
* $args[0] = $url
* $args[1] = Message to enqueue
* $args[2] = Message type
* $args[3] = $moved
*/
if (isset($args[1]) && !empty($args[1]) && !is_bool($args[1]))
{
// Log that passing the message to the function is deprecated
JLog::add(
'Passing a message and message type to JFactory::getApplication()->redirect() is deprecated. '
. 'Please set your message via JFactory::getApplication()->enqueueMessage() prior to calling redirect().',
JLog::WARNING,
'deprecated'
);
$message = $args[1];
// Set the message type if present
if (isset($args[2]) && !empty($args[2]))
{
$type = $args[2];
}
else
{
$type = null;
}
// Enqueue the message
$this->enqueueMessage($message, $type);
// Reset the $moved variable
$moved = isset($args[3]) ? (boolean) $args[3] : false;
}
}
application.php
public function redirect($url, $msg = '', $msgType = 'message', $moved = false)
{
// Check for relative internal links.
if (preg_match('#^index2?\.php#', $url))
{
$url = JUri::base() . $url;
}
// Strip out any line breaks.
$url = preg_split("/[\r\n]/", $url);
$url = $url[0];
/*
* If we don't start with a http we need to fix this before we proceed.
* We could validly start with something else (e.g. ftp), though this would
* be unlikely and isn't supported by this API.
*/
if (!preg_match('#^http#i', $url))
{
$uri = JUri::getInstance();
$prefix = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
if ($url[0] == '/')
{
// We just need the prefix since we have a path relative to the root.
$url = $prefix . $url;
}
else
{
// It's relative to where we are now, so lets add that.
$parts = explode('/', $uri->toString(array('path')));
array_pop($parts);
$path = implode('/', $parts) . '/';
$url = $prefix . $path . $url;
}
}
// If the message exists, enqueue it.
if (trim($msg))
{
$this->enqueueMessage($msg, $msgType);
}
// Persist messages if they exist.
if (count($this->_messageQueue))
{
$session = JFactory::getSession();
$session->set('application.queue', $this->_messageQueue);
}
// If the headers have been sent, then we cannot send an additional location header
// so we will output a javascript redirect statement.
if (headers_sent())
{
echo "<script>document.location.href='" . str_replace("'", "&apos;", $url) . "';</script>\n";
}
else
{
$document = JFactory::getDocument();
jimport('phputf8.utils.ascii');
if (($this->client->engine == JApplicationWebClient::TRIDENT) && !utf8_is_ascii($url))
{
// MSIE type browser and/or server cause issues when url contains utf8 character,so use a javascript redirect method
echo '<html><head><meta http-equiv="content-type" content="text/html; charset=' . $document->getCharset() . '" />'
. '<script>document.location.href=\'' . str_replace("'", "&apos;", $url) . '\';</script></head></html>';
}
else
{
// All other browsers, use the more efficient HTTP header method
header($moved ? 'HTTP/1.1 301 Moved Permanently' : 'HTTP/1.1 303 See other');
header('Location: ' . $url);
header('Content-Type: text/html; charset=' . $document->getCharset());
}
}
$this->close();
}
web.php
public function redirect($url, $moved = false)
{
// Import library dependencies.
jimport('phputf8.utils.ascii');
// Check for relative internal links.
if (preg_match('#^index\.php#', $url))
{
// We changed this from "$this->get('uri.base.full') . $url" due to the inability to run the system tests with the original code
$url = JUri::base() . $url;
}
// Perform a basic sanity check to make sure we don't have any CRLF garbage.
$url = preg_split("/[\r\n]/", $url);
$url = $url[0];
/*
* Here we need to check and see if the URL is relative or absolute. Essentially, do we need to
* prepend the URL with our base URL for a proper redirect. The rudimentary way we are looking
* at this is to simply check whether or not the URL string has a valid scheme or not.
*/
if (!preg_match('#^[a-z]+\://#i', $url))
{
// Get a JUri instance for the requested URI.
$uri = JUri::getInstance($this->get('uri.request'));
// Get a base URL to prepend from the requested URI.
$prefix = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
// We just need the prefix since we have a path relative to the root.
if ($url[0] == '/')
{
$url = $prefix . $url;
}
// It's relative to where we are now, so lets add that.
else
{
$parts = explode('/', $uri->toString(array('path')));
array_pop($parts);
$path = implode('/', $parts) . '/';
$url = $prefix . $path . $url;
}
}
// If the headers have already been sent we need to send the redirect statement via JavaScript.
if ($this->checkHeadersSent())
{
echo "<script>document.location.href='" . str_replace("'", "&apos;", $url) . "';</script>\n";
}
else
{
// We have to use a JavaScript redirect here because MSIE doesn't play nice with utf-8 URLs.
if (($this->client->engine == JApplicationWebClient::TRIDENT) && !utf8_is_ascii($url))
{
$html = '<html><head>';
$html .= '<meta http-equiv="content-type" content="text/html; charset=' . $this->charSet . '" />';
$html .= '<script>document.location.href=\'' . str_replace("'", "&apos;", $url) . '\';</script>';
$html .= '</head><body></body></html>';
echo $html;
}
else
{
// All other cases use the more efficient HTTP header for redirection.
$this->header($moved ? 'HTTP/1.1 301 Moved Permanently' : 'HTTP/1.1 303 See other');
$this->header('Location: ' . $url);
$this->header('Content-Type: text/html; charset=' . $this->charSet);
}
}

highcharts, json data: line and column

May be really basic question:
I'm playing with highcharts with two series, one represented with line and other with column, data is loaded using json, the problem is in how to tell highcharts one serie should be represented with line and the other with column type, like this
The problem (for me) comes when Series options in json mode of highcharts are only like this:
},
series: json
});
whilst in "normal mode" you can set for example:
series: [{
**type: 'column',**
name: 'Name',
data: [],
},{
type: 'spline',
name: 'Max Pax',
data: [],
draggableY: true,
dragMinY: 0,
dragMaxY: 200,
.......
Am I missing something?
php code that retrives data from db:
$con = mysql_connect("localhost", "*******","*******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordpress_8", $con);
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['a1300'];
$rows['data'][] = $r['a1315'];
$rows['data'][] = $r['a1330'];
$rows['data'][] = $r['a1345'];
}
$sth = mysql_query("SELECT overhead FROM projections_sample");
$rows1 = array();
$rows1['name'] = 'Overhead';
while($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = $rr['overhead'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
Output looks like:
[{"name":"MaxPax","data":[40,19,40,21]},{"name":"Overhead","data": [21990,22365,21987,22369,22558,22987,23521,23003,22756,23112,22987,22897]}]
You need to define this parameter in JSON, or parse your json after receive, and set this paraemter, then use in Highcharts.
EDIT:
You can replace this lines
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
with
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
$rows['type'] = 'line';
Similar in next series.
Second solution is push type after getting json like:
$getJSON('path/to/json',function(data){
data[0].type='column';
data[1].type='line';
var options = {
// your options
series: data
};
$('#container').highcharts(options);
});

Image capture/upload with Phonegap (cordova) for iPhone not working

I have been trying to set up an app through PhoneGap (Cordova) to take images and upload them to our server. I have gone through so many of the responses on here and tried the code in them. I can get the camera up and taking a photo, I can access the phone gallery even. But I can not get it to send the image to the server. I've tried sending the image, and even sending the base64 image stream. I can't get it to the server.
Here is the javascript on the client side:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
function ImageUpload() {
this.useExistingPhoto = function(e) {
this.capture(Camera.PictureSourceType.SAVEDPHOTOALBUM);
}
this.takePhoto = function(e) {
this.capture(Camera.PictureSourceType.CAMERA);
}
this.capture = function(sourceType) {
navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFaile, {
destinationType: Camera.DestinationType.FILE_URI,
soureType: sourceType,
correctOrientation: true
});
}
this.onCaptureSuccess = function(imageURI) {
var fail, ft, options, params, win;
success = function(response) {
alert("Your photo has been uploaded!");
};
fail = function(error) {
alert("An error has occurred: Code = " + error.code + "\nMessage = "+error.message);
};
options = new FailUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
params = {
val1: "some value",
val2: "some other value"
};
options.params = params;
ft= new FileTransfer();
ft.upload(imageURI, 'http://style.appdev01.com/app/client-profile.php', success, faile, options);
}
this.OnCaptureFail = function(message) {
alert("Failed because: "+message);
}
};
var imageuploader = new ImageUpload();
Two buttons call imageuploader.takePhoto and .useExistingPhoto on click.
On the server side I have this php:
if(isset($_FILES['file'])) {
$target_path = "/home/style/public_html/images/client_images/app_image.jpg";
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$insert = "INSERT INTO
`fut`
SET
`request` = '".serialize($_POST)."',
`file` = '".serialize($_FILES)."'";
$mysql->query($insert);
}
This is just to store the POST and FILE arrays to the db to make sure they came through and create the image.
But again, nothing is getting to the server. Any help would be GREATLY appreciated. I've tried so many versions of this code from so many questions here and all over the web.
define ('SITE_ROOT', realpath(dirname(__FILE__))); /* echo SITE_ROOT; to dir
move_uploaded_file($_FILES["file"]["tmp_name"],SITE_ROOT."/uploads/".$_FILES["file"]["name"]); // will move file, make sure uplaods has write permission!
That works for me on Android Simulator, not on Tablet, but let me know if you have it working, busy on the same thing.
$myarray = array( $_REQUEST);
foreach ($myarray as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
That you can use to check POST / GET!
Try this is my code. It has worked for me.
Encode your URL by encodeURI method
fileKey with "file" as in your server side script $_FILES['file']
uploadFile: function(refNo){
var uri = fileUpload.fileUri;
var file = uri.substr(uri.lastIndexOf('/') + 1);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType="image/jpeg";
alert("name === "+uri);
options.chunkedMode = false;
var ft = new FileTransfer();
Common.ajaxLoading('show');
ft.upload(uri,encodeURI("http://172.16.1.147:80/upload/home.php") , fileUpload.uploadSuccess, fileUpload.uploadFail, options, true);
},