How to debug Event Source in JS? - javascript

I have the following code in js:
var eventSource = new EventSource(base_url + 'files/chatgpt.php?q=' + $el.val());
var div = document.getElementById('divID');
eventSource.onmessage = function (e) {
if(e.data == "[DONE]"){
div.innerHTML += "<br><br>Hello";
}
div.innerHTML += JSON.parse(e.data).choices[0].text;
};
eventSource.onerror = function (e) {
console.log(e);
};
And the onerror executes, so I'm keep getting this in the console:
Also this is the PHP code I have:
$opts = [
'prompt' => $_GET["q"],
'temperature' => 0.9,
"max_tokens" => 150,
"frequency_penalty" => 0,
"presence_penalty" => 0.6,
"stream" => true,
];
header('Content-type: text/event-stream');
header('Cache-Control: no-cache');
$open_ai->completion($opts, function ($curl_info, $data) {
echo $data . "<br><br>";
echo PHP_EOL;
ob_flush();
flush();
return strlen($data);
});
Well, what's the error? how can I find it?

Related

Submitted chat not posting and retrieving chat not working

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>

Unble to display json code correct on morris.js bar

I have a controller function where it gets my json data for my bar graph
The json code from controller is
{"xkey":[["0","Sun"],["1","Mon"],["2","Tue"],["3","Wed"],["4","Thu"],["5","Fri"],["6","Sat"]],"user":[[2,"1"],[3,"1"]]}
Question from the controller function how am I able to pass the
json['xkey'] and json['user'] to my script
I have looked at Morris Js and Codeigniter pass data from a controller but not work for me.
Here is what I have tried
<script type="text/javascript">
$( document ).ready(function() {
$('#range').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'get',
url: "<?php echo base_url('admin/dashboard/chart/chart_data');?>/" + $( "#range" ).val(),
dataType: 'json',
success: function(json) {
if (typeof Morris != 'undefined') {
Morris.Bar({
element: 'bar-example',
resize: true,
stacked: false,
xLabelAngle: 50,
grid: true,
gridTextSize: 10,
data: [{m: json['xkey'] a: json['user']}],
xkey: 'm',
ykeys: ['a'],
labels: ['Users']
});
}
}
});
});
});
</script>
Controller
<?php
class Chart extends MX_Controller {
public function index() {
return $this->load->view('template/dashboard/chart_view');
}
public function chart_data() {
$json = array();
$json['xkey'] = array();
$json['user'] = array();
$uri_segment = $this->uri->segment(5);
if (isset($uri_segment)) {
$range = $uri_segment;
} else {
$range = 'month';
}
switch ($range) {
case "week":
$results = $this->getUserTotalByWeek();
foreach ($results as $key => $value) {
$json['user'][] = array($key, $value['total']);
}
$date_start = strtotime('-' . date('w') . ' days');
for ($i = 0; $i < 7; $i++) {
$date = date('Y-m-d', $date_start + ($i * 86400));
$json['xkey'][] = array(date('w', strtotime($date)), date('D', strtotime($date)));
}
break;
default:
echo "Your favorite color is neither red, nor green!";
}
$this->output->set_header('Content-Type: application/json; charset=utf-8');
$this->output->set_output(json_encode($json));
}
public function getUserTotalByWeek() {
$user_data = array();
$date_start = strtotime('-' . date('w') . ' days');
for ($i = 0; $i < 7; $i++) {
$date = date('Y-m-d', $date_start + ($i * 86400));
$customer_data[date('w', strtotime($date))] = array(
'day' => date('D', strtotime($date)),
'total' => 0
);
}
$this->db->select('COUNT(*) AS total, date_reg');
$this->db->from('user');
$this->db->where('date_reg >=', date('Y-m-d', $date_start));
$this->db->group_by('DAYNAME(date_reg)');
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$user_data[date('w', strtotime($result['date_reg']))] = array(
'day' => date('D', strtotime($result['date_reg'])),
'total' => $result['total']
);
}
return $user_data;
}
}

ajax post size limitation or server limitation

Upload large files using PHP well done. I set the value of upload_max_filesize and post_max_size in php.ini :
upload_max_filesize = 64M
post_max_size = 64M
But while large files can not be loaded using Ajax. Less than 5 KB file to be uploaded correctly with Ajax.
For large files I get the following error in my console:
Object {readyState: 4, responseText: "", status: 200, statusText: "OK"}
How do I upload large files using the code below?
My ajax code:
$("#submit-edit-order").click(function () {
//*****get data input
var formData = new FormData();
formData.append('action', 'update_order');
formData.append('order_id', $('input[name=order_id]').val());
formData.append('customer_name', $('input[name=customer_name]').val());
formData.append('customer_id', $('input[name=customer_name]').data("cid"));
formData.append('date', $('input[name=date]').val());
formData.append('order_status', $('#order_sataus').find(":selected").val());
formData.append('total_price', $('input[name=totalprice]').val().replace(/,/g, ''));
formData.append('quits', $('input[name=quits]').val().replace(/,/g, ''));
formData.append('desc', $('#desc').val());
formData.append('desc2', $('#desc2').val());
$.each($("input[type=file]"), function (i, obj) {
$.each(obj.files, function (j, file) {
formData.append('orderpic[]', file);
});
});
//ajax start and ajax complatet
ajax_loading();
$.ajax({
url: "../../includes/ajax/ajax.php",
data: formData,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.type == 'error') {
output = '<div class="alert alert-danger" style="margin-top:12px;">' + response.text + '</div>';
} else {
location.reload();
output = '<div class="alert alert-success" style="margin-top:12px;">' + response.text + '</div>';
}
$("section").find("#results").html(output).fadeIn('slow');
},error: function(data){
console.log(data);
}
});
});
PHP code:
if($_POST['action']=='update_order'){
$order_id = $db->escape($_POST['order_id']);
$customer_id = $db->escape($_POST['customer_id']);
$date = explode("/", $_POST['date']);
$date = jDateTime::toGregorian($date[0], $date[1], $date[2]);
$date = $date[0]."/".$date[1]."/".$date[2];
$status = $_POST['order_status'];
$total_price = $_POST['total_price'];
$quits = $_POST['quits'];
$desc = $_POST['desc'];
$desc2 = $_POST['desc2'];
//file settings
$files = array();
$uploaddir = '../../uploads/orders/';
for($i=0; $i<count($_FILES['orderpic']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['orderpic']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$time = time();
$ext = pathinfo($_FILES['orderpic']['name'][$i], PATHINFO_EXTENSION);
//$FilePath = $uploaddir . $time .'.'. $ext;
$FilePath = $uploaddir . $time. basename($_FILES['orderpic']['name'][$i]);
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $FilePath)){
$resizeObj = new resize($FilePath);
$resizeObj -> resizeImage(200, 350, 'portrait');
$newFilePath = $uploaddir ."200_350". $time. basename($_FILES['orderpic']['name'][$i]);
$resizeObj -> saveImage($newFilePath, 100);
unlink($FilePath);
$files[] = "200_350". $time. basename($_FILES['orderpic']['name'][$i]);
}
}
}
$files = implode("|", $files);
$data = array(
"user_id"=>$customer_id,
"productImgLink"=>$files,
"totalPrice"=>$db->escape($total_price),
"quits"=>$db->escape($quits),
"orderDesc"=>$db->escape($desc),
"orderDesc2"=>$db->escape($desc2),
"status"=>$db->escape($status),
"date"=>$db->escape($date)
);
$db->where("order_id",$order_id);
$res = $db->update("orders",$data);
if (!$res) {
$output = json_encode(array('type'=>'error', 'text' => 'fail'));
die($output);
} else {
$output = json_encode(array('type'=>'message', 'text' => 'Done.'));
die($output);
}
}

How can I unserialize my query results from MYSQL?

How my code looks now
$client = $_GET['client_number_search'];
$sql=("SELECT * FROM tobytemp.fcl_reports WHERE client_number = '" . $client . "'");
$result = $dbLink->query($sql);
$arr = array();
while ($r = $result->fetch_object()) {
$temp=[
"client_number" => $r->client_number,
"client_name" => $r->client_name,
"service" => unserialize($r->service),
"volume" => $r->volume,
"deliver_point" => $r->deliver_point,
"port_orgin" => $r->port_orgin,
"size" => $r->size
];
array_push($arr,$temp);
}
echo json_encode($arr);
/* ERROR
Request Method:GET
Status Code:500 Internal Server Error
*/
Current Data populated in my table like this -
service - a:2:{i:0;s:6:"Inport";i:1;s:6:"Export";}
I would like it to be shown something like -
Service-
Import
Export
(I CANT USE PHP ON MY clientreports.html page as I want to later use this as an APP on Phone gap).
AJAX CALL (clientreports.html)
<script type="text/javascript">
$("#show_clientx").click(function(e) {
$("table#client_profile").empty();
$.ajax({
url: "http://cmlsys/toby/client_profile.php?client_number_search=" + $("#client_number").val(),
type: "GET",
dataType: "json",
success: function(html) {
// $("table#client_profile").append('<tr><th>Client Number</th><th>Client Name</th><th>Address</th></tr>');
jQuery.each(html, function(key, value) {
$("table#client_profile").append('<tr><td>' + value.client_number + '</td><td> client_name - ' + value.client_name + '</td></tr><tr></br><td>service - ' + value.service + '</td></br><td>size - ' + value.size + '</td></br><td>volume - ' + value.volume + '</td></br><td>deliver_point -' + value.deliver_point + '</td></br><td>port_orgin - ' + value.port_orgin + '</td></tr>');
});
},
error: function(e) {
console.log("Error: " + e);
}
});
});
</script>
TO - client_profile.php
$client = $_GET['client_number_search'];
$sql = ("SELECT * FROM tobytemp.fcl_reports WHERE client_number = '".$client.
"'");
$result = $dbLink - > query($sql);
$arr = array();
while ($r = $result - > fetch_object()) {
array_push($arr, array("client_number" => $r - > client_number, "client_name" => $r - > client_name, "service" => $r - > service, "size" => $r - > size, "volume" => $r - > volume, "deliver_point" => $r - > deliver_point, "port_orgin" => $r - > port_orgin));
}
echo json_encode($arr);
Please Help
use unserialize in php
for example
$demo=unserialize('a:2:{i:0;s:6:"Inport";i:1;s:6:"Export";}');
echo json_encode($demo);
on your code you can change while loop
while ($r = $result->fetch_object()) {
$temp=[
"client_number" => $r->client_number,
"client_name" => $r->client_name,
"service" => unserialize($r->service),
"volume" => $r->volume,
"deliver_point" => $r->deliver_point,
"port_orgin" => $r->port_orgin,
"size" => $r->size
];
array_push($arr,$temp);
}
$arr = array();
while ($r = $result->fetch_object()){
array_push($arr, array (
"client_number" => $r ->client_number,
"client_name" => $r->client_name,
"service" => unserialize($r ->service),
"size" => unserialize($r ->size),
"volume" => unserialize($r ->volume),
"deliver_point" => unserialize($r ->deliver_point),
"port_orgin" => unserialize($r ->port_orgin))
);
}
echo json_encode($arr);

Unable to insert Ajax return into HTML

I'm trying to use a PHP file to process serialized info from an Ajax request. I want to send back the value of each form field to be further manipulated by javascript (inserted into a div). The result is not being inserted into the HTML. When I alert the result I get {"return":["<p>form value for name<\/p>","<p>form value for description<\/p>"]} Any suggestions?
EDIT: Updated question with relevant HTML and revised PHP code.
HTML:
<div class="col-md-4">
<h5>Heading</h5>
<div id="formBasicResults"></div>
</div>
Javascript:
.on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('formValidation');
$.post($form.attr('action'), $form.serialize())
.done(function (result) {
$('#formBasicResults').html(result.responseText);
alert(result);
},'json');
});
PHP:
if (!isset($_SESSION)) {
session_start();
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
} else {
$token = $_SESSION['token'];
}
}
foreach($_POST as $key = > $value) {
$temp = is_array($value) ? $value : trim($value);
$_SESSION[$key] = $temp;
}
$expected = array(
'name' = > 'string',
'description' = > 'string',
);
foreach($expected AS $key) {
if (!empty($_POST[$key])) {
$ {$key} = $_POST[$key];
} else {${$key} = NULL;
}
}
foreach($expected AS $key = > $type) {
if (empty($_POST[$key])) {
$ {$key} = NULL;
continue;
}
if (!isset($ {
$key})) {
$ {$key} = NULL;
}
}
function safe( $value ) {
htmlentities( $value, ENT_QUOTES, 'utf-8' );
return ($value);
}
$name = $_POST['name'];
$description = $_POST['description'];
$return['result']=array();
if(!empty($name)){$return['result'][]= '<p>' . safe($name) . '</p>';}
if(!empty($description)){$return['result'][]= '<p>' . safe($description) . '</p>';}
echo json_encode($return);
try something like this:
$('#formBasicResults').html(result['return'][0]);
or
$('#formBasicResults').html(result['return'][1]);
Instead of this:
if ($_POST['token'] == $_SESSION['token'])
{$return['return']=array();
if(!empty($_POST['name'])){$return['return'][] = '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){$return['return'][] = '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
echo json_encode($return); }}
do this:
$return['responseText']='';
if ($_POST['token'] == $_SESSION['token'])
{
if(!empty($_POST['name'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
}
}
echo json_encode($return);

Categories

Resources