I've been following this guide: https://www.freecodecamp.org/news/how-to-build-a-keyword-density-tool-with-laravel/ and have found right at the end my app won't return any array. In fact when I click the submit button I notice I get a 419 console error. After checking most issues relate to the CSRF token but from check I have this is place properly.
Can anyone spot or guide me in the right direction so that my app returns something. It's not very advanced in fact it's a very simple application, but It's my first time using Laravel so any guidance is appreciated.
My index.blade.php (This contains the form and ajax request)
#extends('layouts.master')
#section('content')
<form id="keywordDensityInputForm">
<div class="form-group">
<label for="keywordDensityInput">HTML or Text</label>
<textarea class="form-control" id="keywordDensityInput" rows="12"></textarea>
</div>
<button type="submit" class="btn btn-primary mb-2">Get Keyword Densities</button>
</form>
#endsection
#section ('scripts')
<script>
$('#keywordDensityInputForm').on('submit', function (e) { // Listen for submit button click and form submission.
e.preventDefault(); // Prevent the form from submitting
let kdInput = $('#keywordDensityInput').val(); // Get the input
if (kdInput !== "") { // If input is not empty.
// Set CSRF token up with ajax.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({ // Pass data to backend
type: "POST",
url: "tool/calculate-and-get-density",
data: {'keywordInput': kdInput},
success: function (response) {
// On Success, build a data table with keyword and densities
if (response.length > 0) {
let html = "<table class='table'><tbody><thead>";
html += "<th>Keyword</th>";
html += "<th>Count</th>";
html += "<th>Density</th>";
html += "</thead><tbody>";
for (let i = 0; i < response.length; i++) {
html += "<tr><td>"+response[i].keyword+"</td>";
html += "<td>"+response[i].count+"</td>";
html += "<td>"+response[i].density+"%</td></tr>";
}
html += "</tbody></table>";
$('#keywordDensityInputForm').after(html); // Append the html table after the form.
}
},
});
}
})
</script>
#endsection
My master.blade.php (CSRF token in the head)
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Keyword Density Tool</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
body {padding-top: 5em;}
</style>
</head>
<body>
...
<main role="main" class="container mt-3">
#yield('content')
</main><!-- /.container -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
#yield('scripts')
</body>
</html>
My controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Html2Text\Html2Text;
class ToolController extends Controller
{
public function index()
{
return view('tool.index');
}
public function CalculateAndGetDensity(Request $request) {
if ($request->isMethod('GET')) {
if (isset($request->keywordInput)) { // Test the parameter is set.
$html = new Html2Text($request->keywordInput); // Setup the html2text obj.
$text = strtolower($html->getText()); // Execute the getText() function and convert all text to lower case to prevent work duplication
$totalWordCount = str_word_count($text); // Get the total count of words in the text string
$wordsAndOccurrence = array_count_values(str_word_count($text, 1)); // Get each word and the occurrence count as key value array
arsort($wordsAndOccurrence); // Sort into descending order of the array value (occurrence)
$keywordDensityArray = [];
// Build the array
foreach ($wordsAndOccurrence as $key => $value) {
$keywordDensityArray[] = ["keyword" => $key, // keyword
"count" => $value, // word occurrences
"density" => round(($value / $totalWordCount) * 100,2)]; // Round density to two decimal places.
}
return $keywordDensityArray;
}
}
}
}
?>
and my routes
Route::get('/tool', 'App\Http\Controllers\ToolController#index')->name('KDTool');
Route::post('/tool/calculate-and-get-density', 'App\Http\Controllers\ToolController#CalculateAndGetDensity');
and the error I get is this
https://imgur.com/lRYqo09
I have checked all otherwsie answer suggestions on stackoverflow but nothing I do seem's to get my any further. Thanks for any help in advance
Related
I am trying a simple Stripe API implementation on my Laravel app, and for some reason, I cannot get the Elements to load. I have copy and pasted direct from the Docs, a simple form with an element and for the life of me, I can't figure out why it will not load.
Everything seems to be in order.
- My JS files are in the public directory
- I have tried with scripts NOT defered
- I have tried hard coding into one page
- I have read through the Docs seemingly 10 times
- I have checked line by line to make sure the id tags are the same as referenced in the js files.
So far, I am at a loss. I have been working on this for a few hours and I'm just staring at the screen baffled at this point. Any ninjas around who can spot a likely rookie mistake I've made? Here are my current files:
app.blade.php:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Springs Fat to Fit</title>
<!-- Scripts -->
<script src="https://js.stripe.com/v3/" defer></script>
<script src="{{asset('js/stripe.js')}}" defer></script>
<script src="{{asset('js/app.js')}}" defer></script>
<script src="{{asset('js/custom.js')}}" defer ></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<link href="{{asset('css/style.css')}}" rel="stylesheet">
</head>
<body>
<div id="app">
#if(Auth::guest() || Auth::user()->is_admin == 0)
#include('partials.navbar')
#else #if(Auth::user()->is_admin == 1)
#include('partials.admin_navbar')
#endif
#endif
<main class="py-4">
#yield('content')
</main>
</div>
</body>
</html>
testPage.blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
<form action="{{route('testPage')}}" method="post" id="payment-form">
#csrf
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display Element errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
</div> {{-- This is the end of the container--}}
#endsection
stripe.js:
// Create a Stripe client.
var stripe = Stripe('pk_test_key right here');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', { style: style });
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function (event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function (event) {
event.preventDefault();
stripe.createToken(card).then(function (result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
you need to rule out your errors.
rule out whether if it's js error or not: please check your browser console log, network tab, etc, see if there's exception. see if your js is loaded. see all your required js are loaded, not showing 404.
put breakpoints on your js on chrome dev tools. put a lot of them on your switch blocks, if blocks,etc.
fix if you find any problem.
make sure stripe assets is not blocked by your chrome plugins e,g. adblocks
check api keys / secrets if there's any
I'm having some difficulty with AngularJS. Any constructive help is greatly appreciated.
This is the Angular code I'm working with
app.controller('customersCtrl', function($scope, $http) {
$scope.element = function(num){
var element_id = num;//num;
$http.get("customers.php",{params:{"id":element_id}}).then(function (response) {
$scope.myData = response.data;
}
,function errorCallback(response){
$scope.e=response.data;
console.log(e);
});
};
});
And here is my php code I'm using. All this does is return the 401 code. The section works as I can return it in a console log.
http_response_code(401);
$message = http_response_code()." No data found";
header('Content-Type: application/json');
echo json_encode($message);
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>page2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src = "javascript.js"></script>
</head>
<body ng-app="input">
<div ng-controller="customersCtrl">
<h1>Click on the contact name for company and location</h1>
<br>
<button ng-click="element(0)">Bob</button>
<button ng-click="element(1)">Jim</button>
<button ng-click="element(2)">Kim</button>
<br>
<br>
<ul>
<li ng-repeat="x in myData">
{{x}}
</li>
</ul>
<div ng-show="error != null">
<p>{{e.error}}</p>
</div>
</div>
View full list
</body>
</html>
I'm having a problem displaying the 401 message in the HTML page. What is a good way of doing this? The code will return the message but only as a console log. I need it in a HTML page. I'm quite confused on this one as I've tried multiple ways and none of them are working. Any help would be greatly appreciated
Thank you in advance!!!
Hey Man try that below:
$scope.e = '';
$scope.myData = [];
$scope.element = function(element_id){
$http({
method: 'GET',
url: "customers.php?id=" + element_id,
headers: {
'Content-Type': 'application/json'
}
})
.then(
function successCallback(response) {
$scope.myData = response.data;
callback(response);
},
function errorCallback(response) {
$scope.e = response.data;
callback(response);
}
);
}
Check on browser the network, and if no work, plz upload the network with log to "customers.php"
Best Wishes
In my website the clients can update their personal data. After the update is done on the database, I want the page updates itself and show the data as it is at that time. For doing this, I do an ajax call to an external php file to update the mysql database. After that, I do a get of the client data page (location.href) and I update some div info to show up the new data.
This is the AJAX call from my JS file:
$.ajax({
type: "POST",
url: "factupdate.php",
data: {
datos: stringDatos,
token: $("#token").val(),
isAjax: 1
},
success: function (codi) {
$.get(location.href, function (datos) {
($(datos)).find("#eltoken").html());
var eltoken = $(datos).find("#eltoken");
var result = $(datos).find("#cuenta_menu_fac");
console.log($(eltoken).html());
console.log($(result).html());
$(result).find(".facturacion").hide();
$(result).find("#fac_" + num).show();
$(result).find(".afac").removeClass("aliselected");
$(result).find("#menu_fac_" + num).addClass("aliselected");
$(result).find("#acc_fac").append('<span class="goodvalid">Datos de facturaciĆ³n actualizados</span>');
$("#cuenta_menu_fac").html($(result).html());
$("#eltoken").html($(datos).find("#eltoken").html());
$("#cargandoacc").hide();
});
},
error: function (e) {
$("#cargandoacc").hide();
alert('Ha habido un error: ' + e);
}
});
The problem is that I can see the result data but not the eltoken's, the console prints undefined.
Moreover, when I try to do a console.log($(datos).html()); it also shows up as undefined. On the other hand, if I do a console.log($(datos).text()); it does return the correct data of the website.
This is some of datos info:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="es" xml:lang="es">
<head>
...
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
...
</head>
<body>
<!-- Some layout divs -->
<div id="cuenta_menu_fac" class="c-menu-content">
<div class="content" id="acc_fac">
<!-- Some label and input for updating data divs -->
</div>
</div>
<!-- /Some layout divs -->
<div id="eltoken">
<input type="hidden" id="token" value="2d5951d1e3b31dfb7fd2dcc172df17fd">
</div>
</body></html>
I do not understand what is wrong in my code. Any possible solution to this?
Datos is not a parent for eltoken. Just add eg. a common div for it.
$.get(location.href, function (datos) {
datos = $('<div></div>').append(datos);
($(datos)).find("#eltoken").html());
...
See my similar example
https://jsfiddle.net/011g253w/1/
Update
Your code has 2 divs on one level in the body. And get returns it as a result of selector $(*, 'body') = array of 2 divs.
I found a better way for your case.
var eltoken = $(datos).filter("#eltoken");
var result = $(datos).filter("#cuenta_menu_fac");
https://jsfiddle.net/011g253w/2/
My jQuery Mobile page does not load content via $.get which is bind into pageinit event, but does so when I hit refresh (F5), why is that so?
My HTML page igra.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- stili za custom temo, jquery, jquery mobile, phonegap-->
<link rel="stylesheet" href="themes/what.min.css" />
<link rel="stylesheet" href="jquerymobile.css" />
<script src="jquery191.js"></script>
<script src="jquerymobile.js"></script>
<script src="phonegap.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="stil.css" />
</head>
<body>
<div data-role="page" id="igra">
<div data-theme="a" data-role="header">
347 coins
<h3>WHAT?</h3>
Home
</div>
<div data-role="content" class="igracontent"> </div>
</div>
</body>
</html>
My main.js with jQuery Mobile code:
$( document ).delegate("#igra", "pageinit", function() {
var par = qs["battlefield"];
$.get('igra.php?battlefield='+par, function(data2) {
$('div.igracontent').append(data2).trigger('create');
});
});
//parse url parameter
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
In igra.php I make SQL query and retrieve some data which I format in jQuery Mobile style and echo it back.
I know jQuery Mobile does not load head into DOM in subsequent pages, so main.js is also included in index.html head which is landing page of my app. All transitions to new pages are by normal ajax querying (I do not prevent default behaviour).
So what happens? When I navigate to igra.html?battlefield=3 the pageinit event does happen but content which I load via $.get from php page does not get inserted! If I hit F5(refresh) the content does get loaded into page. Can anybody explain and help? :) Thank you!
i want to delete a record that are showing in while loop from the database but before deleting i want to display a confirmation box.The code i have written is below.it is working fine but to delete record i need to pass an id that i haave described in the code
------index.php starts
<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
<div class="item">
<div class="delete"></div>
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
----index.php ends
----jquery.confirm.js file starts
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
----jquery.confirm.js file ends
-----script.js file starts
$(document).ready(function(){
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
elem.slideUp();
//sql delete query will be written here... in where condition i need to pass the fetched record id from index.php file in where condtion
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
});
-----script.js ends
You can use the html data attribute and retrieve it with .data jQuery method
In your HTML:
<div class="delete" data-id="{$id}"></div>
In your Javascript
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
var id = elem.data('id'); /* this is your db id */
});
Are you sure you want to send a query from Javascript? The usual way to do this is to send a request (via jQuery) with that specific id, to a script which runs the query (server side), and returns a response.
Now, since you add the item divs, using a while, why not add an id property to the divs, which contain the id from the database, something like
<div id="item<?php echo $row['id'];?>" class="item">
<div class="delete">
</div>
This way, the $('.item .delete').click handler has access to the item's id, by parsing the target's id property, and you don't need to pass it explicitly to jQuery.
Here you can use hidden field to save value for id and then use jquery to retrieve it from hidden field..
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<input type="hidden" id="hid_id" value="<?php echo 'fetched id';?>" />
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
And then in jquery when using confirm box you can get value by id hid_id .