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/
Related
I Fetch Data From Laravel API and I want to show dynamic meta title and description but when i set dynamic data in inspect element it show's dynamic values but not updated in page source and also when share on social media like whatsapp, facebook etc it not showing dynamic title and description.
Here is My Code..
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="theme-color" content="#084594" />
<meta property="og:title" id='metaTitle' content="Static Title">
<meta property="og:description" id='metaDescription' content="Static Description">
Now I am Change it Using Jquery
<script>
$(document).ready(function() {
const API = "<?= API ?>";
$('#metaTitle').attr('content','Dynamic Title')
$('#metaDescription').attr('content','Dynamic Description')
function getCategory() {
$.ajax({
type: "get",
url: `${API}/all_category`,
success: function(response) {
console.log("responseCat", response.category);
$.each(response.category, function(key, item) {
let cat = item.name.split(' ')[0];
$("#filter").append(
`<li data-filter=".${cat}">${item.name}</li>`
);
});
isotopFilter();
},
});
}
function getPortfolio() {
$.ajax({
type: "get",
url: `${API}/all_portfolios`,
success: function(response) {
console.log("responseCat", response.portfolio);
$.each(response.portfolio, function(key, item) {
let cat = item.category.split(' ')[0];
let url_title = item.title.toLowerCase().replace(/[ ().]/g, '-');
url_title = url_title.replace('--', '-');
$(".masonry_wrapper").append(
`<div class="col-md-4 col-sm-6 flex-active item ${cat}"><div class="tutorial_card"> <div class="service-content"> <a href="portfolio/${url_title}" > <h3>${item.title}</h3></a > </div><div class="read"> <a href="portfolio/${url_title}" class="btn btn-default" >View Portfolio</a > </div></div></div`
);
});
isotopFilter();
},
});
}
getCategory();
getPortfolio();
});
But It is showing Static Title And Description in ctrl + u Page Source code But In Inspect Elements It change With Dynamic Title And Description.
And Also When Share Page It Shows Static Title And Description
As #brombeer already stated in the comments, most social media and robots don't care about the client side changes (Javascript is executed on the client's computer).
You'll need to set the meta properties on the server side, using PHP.
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
I have a div tag with many anchor tags in it. On clicking a lick it should open a php page in another div tag of the same page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<header>
<h2>Test</h2>
</header>
<div class="topnav" id="myTopnav">
page1
page2
page3
page4
</div>
<div id="content" >
</div>
<script>
$(function(){
$("#myTopnav a").click(function(e){
e.preventDefault(); //To prevent the default anchor tag behaviour
var url = this.href;
$("#content").load(url);
});
});
</script>
</body>
</html>
I have a nav bar and on clicking the links it should load a php page in content div. I tried the above code but it does not work.
The Reason is that its a local file at your system, you need to set up a webserver.
If the problem exist further then you can add "Cross Origin" headers to the called php files.
If it's not working for you, try the full context and see what the error message might be:
$( "#content" ).load( url, function( response, status, xhr ) {
if ( status == "error" ) {
window.alert(xhr.status + " " + xhr.statusText);
}
});
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 have this issue where, I can see the echo of a variable via the preview on Chrome Developer Tools, but it's blank on the actual web page.
I am guessing this is down to a timing issue, so to make it clear this is how I have it.
As page (index.php) loads, it links a .js file that does a FLQ query on FB to get the users name.
It then uses ajax to repost to the index.php with the information.
Back at the index.php page, it reloads and collects via $_POST
It then displays some of the user info held in $_POST
I am guessing why I am doing is not possible, but it's odd that in the Chrome dev tool, all the variables echo on the page, but the actual page is blank where the variable should display.
I can only suggest I have a holding page, collect the detail and then load then moves to the main page to display the data.
<!--
Index.php
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<?php
global $uid;
global $una;
global $uem;
global $uph;
?>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"> </script>
<script type="text/javascript">
// initialize the library with the API key
FB.init({ apiKey: '2847xxxxxxxx689' });
</script>
<?php
?>
<script type="text/javascript">
FB.login(function(response) {
// handle the response
}, {scope: 'email,publish_stream'});
</script>
<script type="text/javascript" src="jquery/op.js"></script>
<?php
$uid = $_POST['uid'];
$una = $_POST['una'];
$uem = $_POST['uem'];
$uph = $_POST['uph'];
echo $_POST['una'];
?>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="stylesheets/op_main.css" media="Screen" type="text/css" />
<?php
//include('assets/opPHP.php');
include('sql/ajaxsql.php');
include('sql/phpsql.php');
$opapp = new opapp;
?>
<body>
<div id="mainbody">
<div id="topbanner">
Beta Name <?php echo $una; ?>
</div>
<--
.js File
-->
$(window).load(function() {
FB.api('/me', function(response) {
var query = FB.Data.query('select uid,name,email, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var uid = rows[0].uid;
var una = rows[0].name;
var uem = rows[0].email;
var uph = '<img src="' + rows[0].pic_square + '>';
$.ajax({
url: '../index.php',
type: 'POST',
data: 'uid=' + uid + '&una=' + una + '&uem=' + uem + '&uph=' + uph
});
});
});
});
I can see it posts the information, so my question is. Is their another way to collect the information, while being on the same page. Even explain why I can see it it dev tool, but not the main page?
Thanks
Andrew
echo $_POST['una']; is echoed in the head tag so it will be shown in Chrome dev tools but not in web page.
Regarding <?php echo $una; ?>, I am not seeing anyplace were this variable is getting set. So this may be the reason why it is coming blank