I get inconsistent duplicate inserts when running the following Laravel code: (I know I'm breaking all best practices, but this example code isolates the problem.)
App/routes/web.php:
<?php
use Illuminate\Support\Facades\DB; // NOTE: I am using the query builder, not a model
use Carbon\Carbon;
Route::get('formtest', function() {
return view('testing.index');
});
use Illuminate\Http\Request;
Route::post('formtest', function(Request $request) {
DB::table('pers2_testing_inserts')
->insert([
'data' => $request["test"],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
});
App/resources/views/testing/index.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TESTING</title>
</head>
<body>
<form id="form" action="" method="post" novalidate autocomplete="off" onsubmit="disableAndSubmit(event)">
<input type="text" name="test" id="text_box">
<input type="submit" id="submit_button">
</form>
<script type="text/javascript">
var text_box = document.getElementById('text_box');
var submit_button = document.getElementById('submit_button');
var form = document.getElementById('form');
function disableAndSubmit(e) {
submit_button.disabled = true;
if(text_box.value !== '') {
form.submit();
} else {
e.preventDefault();
submit_button.disabled = null;
}
}
</script>
</body>
</html>
My project is built in Laravel 5.4, PHP 7.1.7. I develop on a Mac, using vagrant as a virtual machine. My production server is a Windows Server 2008 R2 Standard Computer with XAMPP v3.2.2. The inconsistent duplicate inserting ONLY happens on the production server. Here is a screenshot of a few tests on the server.
I have inserts all over in my program, and any one of them can duplicate, and it's inconsistent. It shouldn't be that way. Is there something I should change in my XAMPP configuration? PHP configuration? Is there a workaround that I can implement that would prevent this from happening on the server?
try this:
<script type="text/javascript">
var text_box = document.getElementById('text_box');
var submit_button = document.getElementById('submit_button');
var form = document.getElementById('form');
function disableAndSubmit(e) {
e.preventDefault();
submit_button.disabled = true;
if(text_box.value !== '') {
form.submit();
return true;
} else {
submit_button.disabled = false;
return false;
}
}
</script>
Related
So I have an app that can bring up push notifications in the browser. The problem is that I need to create a UI test using Laravel Dusk to test if the push notification actually appears in the user's browser.
In real applications, push notifications are triggered from the server side in real-time using Websocket. Because there is some code logic in the front end before popping the push notification, so I think using Mocking Event Fake is still not enough.
I have tried reading the official documentation on Laravel Dusk but unfortunately haven't found a solution.
With an example page like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>Show Notification</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/push.js/1.0.8/push.min.js" integrity="sha512-eiqtDDb4GUVCSqOSOTz/s/eiU4B31GrdSb17aPAA4Lv/Cjc8o+hnDvuNkgXhSI5yHuDvYkuojMaQmrB5JB31XQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
const button = document.querySelector('button')
button.addEventListener('click', () => {
Push.create('Hello world!', {
body: 'Foo',
icon: 'https://example.com/images/icon.png',
link: 'https://example.com/',
timeout: 4000,
onClick: function () {
window.focus();
this.close();
},
})
})
</script>
</body>
</html>
The solution I might expect is something like this:
<?php
declare(strict_types=1);
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class ExampleTest extends DuskTestCase
{
/**
* #test
*/
public function itShouldBeAbleToShowPushNotifications(): void
{
$this->browse(function (Browser $browser): void {
$browser
->visit('/')
->allowPushNotification() // The actual method doesn't exist, it's just an example I was hoping for
->click('button')
->assertSeePushNotification( // The actual method also doesn't exist
title: 'Hello world',
body: 'Foo',
icon: 'https://example.com/images/icon.png',
link: 'https://example.com/'
);
});
}
}
Is this possible? Or maybe there is a better alternative?
I am testing botman chat. Followed documentation at https://botman.io/2.0/installation
Script open the chat widget at right bottom corner, but when I enter hello, it does not reply. Have tried multiple forums but not getting any solution.
Below is the script I am using
Installed botman
composer require botman/botman
Web Deriver
composer require botman/driver-web
index.php
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>COINS ChatBot</title>
<!-- <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/assets/css/chat.min.css"> -->
</head>
<body>
<script>
// Feel free to change the settings on your need
var botmanWidget = {
frameEndpoint: '/chat.html',
chatServer: 'chat.php',
title: 'ChatBot',
introMessage: 'Hi and welcome to our chatbot how can i help you ?',
placeholderText: 'Ask Me Something',
mainColor: '#F28240',
bubbleBackground: '#F28240',
aboutText: '',
aboutLink: '',
bubbleAvatarUrl: 'https://www.applozic.com/assets/resources/images/Chat-Bot-Icon#512px.svg'
};
</script>
<script src='https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/js/widget.js'></script>
</body>
</html>
chat.html
<html>
<head>
<title>BotMan Widget</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/assets/css/chat.min.css">
</head>
<body>
<script id="botmanWidget" src='https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/js/chat.js'></script>
</body>
</html>
chat.php
<?php
require_once 'vendor/autoload.php';
use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Drivers\DriverManager;
$config = [
// Your driver-specific configuration
// "telegram" => [
// "token" => "TOKEN"
// ]
];
DriverManager::loadDriver(\BotMan\Drivers\Web\WebDriver::class);
$botman = BotManFactory::create($config);
// Give the bot something to listen for.
$botman->hears('hello', function (BotMan $bot) {
$bot->reply('Hello yourself.');
});
$botman->hears('Good Morning', function (BotMan $bot) {
$bot->reply('Hey John');
});
$botman->hears('what is the time in {city} located in {continent}' , function (BotMan $bot,$city,$continent) {
date_default_timezone_set("$continent/$city");
$reply = "The time in ".$city." ".$continent." is ".date("h:i:sa");
$bot->reply($reply);
});
$botman->fallback(function($bot) {
$bot->reply('Sorry, I did not understand these commands. Here is a list of commands I understand: ...');
});
// Start listening
$botman->listen();
?>
After checking I found may be issue with caching, I have installed APCU PHP Cache but still no luck.
I am trying to create a chat application using Socket and using Swoole as backend. I successfully create a connection to server-client but the issue I am facing now is that whenever I close terminal WebSocket is unable to connect.
Server code:-
<?php
//Create the websocket server object
$websocket_server = new swoole_websocket_server("MY_IP", 3000);
// Register function of the opening connection event
$websocket_server->on('open', function($websocket_server, $request){
var_dump($request->fd, $request->get, $request->server);
$websocket_server->push($request->fd, "Hello welcome\n");
});
// Register function of the receiving message event
$websocket_server->on('message', function($websocket_server, $frame){
echo "Message : {$frame->data}\n";
$websocket_server->push($frame->fd, "Server : {$frame->data}");
});
// Register function of the close event
$websocket_server->on('close', function($websocket_server, $fd){
echo "client_{$fd} is closed\n";
});
// Start the server
$websocket_server->start();
Client side Code:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script type="text/javascript">
var wsServer = 'ws://IP:3000';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("Connected to WebSocket server.");
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
console.log('Retrieved data from server: ' + evt.data);
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
</script>
</body>
</html>
Everything is working fine the only issue is when we close terminal web socket id down.
I get the answer on Git. Please add below code in line
$websocket_server = new swoole_websocket_server("MY_IP", 3000);
$websocket_server->set([
'daemonize' => true,
]);
re this post AJAX Post to self in PHP
When using exit() doesn't something have to be printed before this call?
I have written markup/ph with references to external css php scripts. The script uses print (or echo) and a
call to header('type: text/css'). Isn't this useful or necessary in self processing php pages? I find
them endlessly useful. A whole site can be displayed in any state by one page using get queries and posts
from forms. I remember the text I was reading early on when beginning to learn php asserted that when
the page submits to itself, the browser will automatically use asynchronous requests. But in certain situations
an explicit ajax call is useful.
Here is what I am doing and what I am trying to do.
I have a text field and a button in a page
I write text to the text field and click the button
The javascript click event handler for the button gets the text field value
and appends it to a get query attached to the url in the request. The method is get
edit: to specify the environment in which this has been successful.
I am using Firefox v12.0 On Mac OSX with pre-installed apache server on local machine.
(anyone with a Mac running OSX, there is a pre installed apache server, but activating php requires
editing the httpd.com file to un comment the line(s) that load the php module. Also, there is a line
that tells Apache what extensions to use to look for and execute php code. You also must tell it
to take index.php as an index file to run the php in it and have it act as a directory index file)
the javascript code:
function _FETCH()
{
this.init = function(oName, elem, txt)
{
var but = document.getElementById(elem);
but.addEventListener('click', function(){ oName.req('GET', self, '', null, oName, txt) } )
}
this.req = function(method, url, type, msg, oName, txt)
{
var field = document.getElementById(txt);
url+="?ajxTst="+encodeURIComponent(field.value);
var it = new XMLHttpRequest();
it.open(method, url, type);
it.setRequestHeader('Content-Type', 'text/plain');
it.onreadystatechange = function()
{
var elem = document.getElementById('well');
switch(it.readyState)
{
case 0:
case 1:
break;
case 2:
case 3:
elem.childNodes[0].data = " waiting";
break;
case 4:
oName.handleResponse(it.responseText);
break;
default:
alert('ajax processing error');
break;
}
}
it.send(msg);
}
this.handleResponse = function(resp)
{
var elem = document.getElementById('well');
elem.childNodes[0].data = " "+resp;
}
}
The php, javascript and markup in the page:
<?php
/*
created 11/4/2014
*/
$_self = basename($_SERVER['PHP_SELF']);
if($_POST || $_GET)
{
if($_GET['ajxTst'])
{
header("Content-Type: text/plain");
print $_GET['ajxTst'];
exit();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>JS lab 2</title>
<link rel="stylesheet" type="text/css" href="local.css" media="screen" />
<script type="text/javascript" src="local.js">
</script>
<script type="text/javascript">
//<![CDATA[
var self = "<?php print $_self; ?>";
window.onload = function()
{
var ajx = new _FETCH();
ajx.init(ajx, 'send', 'tlk');
}
//]]>
</script>
</head>
<body>
<div class="panel">
<p class="title">Js Lab 2</p>
<p class="norm">Lab 3 home</p>
<p class="norm">Work with ajax and self processing page (this)</p>
<hr />
<p class="norm" id="well"> idle </p>
<p class="norm">
<input type="text" id="tlk" value="" /><input type="button" id="send" value="send" />
</p>
</div>
</body>
</html>
I hope That someone looking for this will find it. It took me a while to get it right
I want to view the data on mysql using ajax, im having a problem with my code. This code doesn't alert anything.
index.php
<script>
function forusedata(id) {
$.post('insert_home.php', {BOOKDATA: id}).done(function(data) {
alert(data);
});
}
</script>
});
insert_home.php
else if (isset($_POST['BOOKDATA'])) {
$ENUM = ($_POST['BOOKDATA']);
$result = mysqli_query($con, "SELECT *FROM book WHERE BOOKID='$ENUM'");
while ($row = mysqli_fetch_array($result)) {
echo $row['BOOKCAPTION'];
}
mysqli_close($con);
}
Try that:
script
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Test POST</title>
</head>
<body>
<script type='text/javascript'>
$(document).ready(function() {
$.post(
'insert_home.php',
{
BOOKDATA: 1
}
).done(function(data) {
alert(data);
});
});
</script>
</body>
</html>
insert_home.php
<?php
if (isset($_POST['BOOKDATA'])) {
// search user
echo 'BOOKDATA = ' . $_POST['BOOKDATA'];
}
In you case, you need to transform your mysql result in a text or json format, like echo json_encode($your_var);
Your problem maybe is in your SELECT/mysqli connection.
Try see the return in you Developers Tools (Chrome):
Press F12
Clique in Network tab
Search for your insert_home.php request
Click in Response
Hope this helps