M
M
Medvedoc2018-03-16 08:24:41
JavaScript
Medvedoc, 2018-03-16 08:24:41

How to modify the phrase generator so that they are loaded via ajax?

Hello! There is this code

<?php 
  //Генерируем фамилию
  $famtxt = file('comments.txt'); 
  $famstr = $famtxt[ array_rand($famtxt) ]; 
  unset($famtxt);
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
  <title>Генератор</title>
  <meta name="keywords" content="генератор" />
  <meta name="description" content="Генератор" />
  <link href="css/bootstrap.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">
  <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
</head>

<body>

<div class="wrapper">
  <main class="content">
    <div class="ribbon"><div class="ribbon-stitches-top"></div><strong class="ribbon-content"><h1>Генератор</h1></strong><div class="ribbon-stitches-bottom"></div></div>
    <div class="gendata">
      <div class="form-group">
          <?php echo $famstr; ?>
      </div>
      <button onClick='parent.location="javascript:location.reload()"' class="btn btn-success">Хочу другую фразу</button>
    </div>
  </main>
</div>


It takes phrases from the comments.txt file and randomly displays them on the page.
1. How to generate without reloading the page via ajax?
2. How can I start the whole thing with mysql so that the phrases are in the database and take them from there?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mysterion, 2018-03-16
@Medvedoc

1. It is better to put the PHP code in a separate file, write there:

<?php
if(isset($_POST['fam']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $famtxt = file('comments.txt'); 
    return $famtxt[array_rand($famtxt)];
}

In template:
$(document).ready(function(){
$.ajax({
type: 'GET',
url: '/random_phrase.php',
data : 'fam=1',
timeout: 25000,
success: function( data) {
$('div.gendata div.form_group').html(data);
}
});
});
2 And about getting data from the mysql database to php in Google, well, there are a lot of articles with ready-made code. Just give the result of receiving when requested and that's it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question