Ir para conteúdo
Fórum Script Brasil

Pergunta

Bom dia, estou criando um CRUD  e no momento de criar meu update  os seguintes erros aparece 

index.html:22 Uncaught ReferenceError: viewData is not definedonload @ index.html:22

 

index.html:120 Uncaught SyntaxError: Unexpected token function

E minha tabela não aparece a não ser que eu comente o formulario no documento server.php entre a linha 47 e 81

segue o codigo do meu index.html e do meu server.php

 

INDEX.HTML

<!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">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>CRUD AJAX</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Latest compiled and minified CSS -->
    
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body onload="viewData()">

    <div class="container">
    <p></p>
      <button class="btn btn-primary" data-toggle="modal" data-target="#addData">Insert DATA</button><!-- Botão para inserir os dados-->
      <!-- Modal -->
      <div class="modal fade" id="addData" tabindex="-1" role="dialog" aria-labelledby="addLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="addLabel">Insert Data</h4>
            </div>
            <form method="POST">   <!-- Começo do Formulario -->
              <div class="modal-body">              
                <div class="form-group">
                  <label for="nm">Full Name</label>
                  <input type="text" class="form-control" id="nm" placeholder="NAME">
                </div>
                <div class="form-group">
                  <label for="em">EMail</label>
                  <input type="email" class="form-control" id="em" placeholder="Email">
                </div>
                <div class="form-group">
                  <label for="hp">Phone Number</label>
                  <input type="number" class="form-control" id="hp" placeholder="Phone Number">
                </div>
                <div class="form-group">
                  <label for="al">Address</label>
                  <textarea class="form-control" id="al" placeholder="Address"></textarea> 
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" onclick="saveData()" class="btn btn-primary">Save changes</button>
              </div>
            </form><!-- Termino do Formulario-->
          </div>
        </div>
      </div>
      <div id="result"></div>
    <p></p>
      <table class="table table-bordered table-striped">
        <thead>
          <tr>
            <th width="40"></th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Address</th>
            <th width="180">Action</th>
          </tr>
        </thead>
        <tbody>
          
        </tbody>
      </table>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery-3.1.1.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script>        /* Começo AJAX */
      function saveData(){
        var name = $('#nm').val();
        var email = $('#em').val();
        var phone = $('#hp').val();
        var address = $('#al').val();
        $.ajax({
          type: "POST",
          url:"server.php?p=add",
          data: "nm="+name+"&em="+email+"&hp="+phone+"&al="+address,
          success: function(data){
          
            viewData();
          }
        });
      }

      function viewData(){
          $.ajax({
            type: "GET",
            url: "server.php",
            success: function(data){
              $('tbody').html(data);
            }
          });
      } 
      function updateData(str){
        var id = str;
        var name = $('#nm-'+str).val();
        var email = $('#em-'+str).val();
        var phone = $('#hp-'+str).val();
        var address = $('#al-'+str).val();
        $.ajax({
          type: "POST",
          url: "server.php?p=edit",
          data: "nm="+name+"&em="+email+"&hp="+phone+"&al="+address+"&id="+id,
          success function(data){
            viewData();
          }
        });
       }
    </script>
  </body>
</html>

 

 

SERVER.PHP

<?php

$db = new PDO('mysql:host=localhost;dbname=ajaxdata', 'root', '');

$page = isset($_GET['p']) ? $_GET['p'] : '';
if ($page === 'add'){
	$name = $_POST['nm'];
	$email = $_POST['em'];
	$phone = $_POST['hp'];
	$address = $_POST['al'];
		$stmt = $db->prepare("INSERT INTO crud (name, email, phone, address) VALUES (?, ?, ?, ?);");
		$stmt->bindParam(1, $name);
		$stmt->bindParam(2, $email);
		$stmt->bindParam(3, $phone);
		$stmt->bindParam(4, $address);
		$status = $stmt->execute();

}else if ($page === 'edit') {
	$id = $_POST['id'];
	$name = $_POST['nm'];
	$email = $_POST['em'];
	$phone = $_POST['hp'];
	$address = $_POST['al'];
		$stmt = $db->prepare("update crud set name=?, email=?, phone=?, address=? where id=?");
		$stmt->bindParam(1, $name);
		$stmt->bindParam(2, $email);
		$stmt->bindParam(3, $phone);
		$stmt->bindParam(4, $address);
		$stmt->bindParam(5, $id);
		$status = $stmt->execute();
}else if ($page === 'del') {
	# code...
}else{
	$stmt = $db->prepare("SELECT * from crud order by id asc");
	$stmt->execute();
	while($row = $stmt->fetch()){
		?>
		<tr>
			<td><?php echo $row['id'] ?></td>
			<td><?php echo $row['name'] ?></td>
			<td><?php echo $row['email'] ?></td>
			<td><?php echo $row['phone'] ?></td>
			<td><?php echo $row['address'] ?></td>
			<td>
				<button class="btn btn-warning" data-toggle="modal" data-target="#edit-<?php echo $row['id'] ?>">Edit</button>
					<!-- Modal -->
					<div class="modal fade" id="edit-<?php echo $row['id'] ?>" tabindex="-1" role="dialog" aria-labelledby="editLabel-<?php echo $row['id'] ?>">
					  <div class="modal-dialog" role="document">
					    <div class="modal-content">
					      <div class="modal-header">
					        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
					        <h4 class="modal-title" id="editLabel-<?php echo $row['id'] ?>">Edit Data</h4>
					      </div>
					      <form>
						      <div class="modal-body">
						        <div class="form-group">
				                  <label for="nm">Full Name</label>
				                  <input type="hidden" class="form-control" id="nm-<?php echo $row['id'] ?>" value="nm-<?php echo $row['name'] ?>">
				                </div>
				                <div class="form-group">
				                  <label for="em">EMail</label>
				                  <input type="email" class="form-control" id="em-<?php echo $row['emid'] ?>" value="
				                  em-<?php echo $row['email'] ?>">
				                </div>
				                <div class="form-group">
				                  <label for="hp">Phone Number</label>
				                  <input type="number" class="form-control" id="hp-<?php echo $row['id'] ?>" value="hp-<?php echo $row['phone'] ?>">
				                </div>
				                <div class="form-group">
				                  <label for="al">Address</label>
				                  <textarea class="form-control" id="al-<?php echo $row['id'] ?>" value="al-<?php echo $row['name'] ?>"></textarea> 
				                </div>
						      </div>
						      <div class="modal-footer">
						        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
						        <button type="submit" onclick="updateData(<?php echo row['id'] ?>)" class="btn btn-primary">Update</button>
						      </div>
					      </form>
					    </div>
					  </div>
					</div>

				<button class="btn btn-danger">Edit</button>
			</td>
		</tr>
		<?php
	}

}


/*else if ($page === 'select') {
	$_GET['id'] = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_SPECIAL_CHARS);

	try {
		$stmt = $db->query("SELECT * FROM crud WHERE id = {$_GET['id']};");
		if (!$stmt)
			throw new Exception("Não foi possível executar QUERY");

		$result = $stmt->fetch();
	} catch (Exception $ex) {
		$result = $ex->getMessage();
	}

}
*/

Att,

Mateus Guedes

Editado por Mateus Guedes da Conceição
Link para o comentário
Compartilhar em outros sites

1 resposta a esta questão

Posts Recomendados

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...