Problem UPDATE with AJAX

3

I want to update the data of a form using AJAX (jQuery 1.10.2) and the answer goes through the error.

HTML

<form name="formulario">
  <p id="identificador">9</p>
  <input id="opcion-1" type="radio" name="opcion" value="1">Opción uno
  <input id="opcion-2" type="radio" name="opcion" value="2">Opción dos
  <input id="opcion-3" type="radio" name="opcion" value="3">Opción tres
  <textarea id="texto"></textarea>
  <button onclick="update()">Update</button>
</form>

JavaScript

// Variables
var form   = document.formulario;
var id     = document.getElementById('identificador');
var radio  = document.getElementsByName('opcion');
var text   = document.getElementById('texto');


// Devolvemos la hora
function getUpdatedAt() {

  var d = new Date();
  var day = d.getDate();
  var month = d.getMonth() + 1; //Months are zero based
  var year = d.getFullYear();
  var hour = d.getHours();
  var minutes = d.getMinutes();
  var seconds = d.getSeconds();

  return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;

}


// Gestionamos el UPDATE
function update() {

  // Guardamos los valores que vamos a enviar
  var valor_1 = parseInt( id.textContent );
  for(var i=0; i<2; i++) { // radio.length = 2
    if (form.radio[i].checked) {
      var valor_2 = parseInt( form.radio[i].getAttribute('value') );
    }
  }
  var valor_3 = text.value;
  var valor_4 = getUpdatedAt();

  // Mandamos los datos al servidor
  $.ajax({
    url: 'classes/update.php',
    type: 'post',
    dataType: 'json',
    data: { id: valor_1, opcion: valor_2, texto: valor_3, updatedAt: valor_4 },
    success: function(response) { console.log('success'); },
    error: function(response) { console.log('error'); }
  });

}

PHP

// Nos conectamos
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT) or die("Error de conexión");

// cambiamos el juego de caracteres a UTF-8
$db_connection->set_charset("utf8");

$data = array();

// Hacemos el UPDATE de el input radio 'opcion' y el textarea 'texto' relacionados con el id N
$sql = "UPDATE nombre_tabla SET opciones = ".$_POST["opcion"].", textos = ".$_POST["texto"].", updated_at = ".$_POST["updatedAt"]." WHERE ids = ".$_POST["id"]."";

// pon el resultado en la variable result
$result = $db_connection -> query($sql);

$row_goal_detail = mysqli_fetch_assoc($result);

$data[] = $row_goal_detail;

echo json_encode($data); //devolvemos los datos


$db_connection->close();

The code that is described in the question is a simplified code to make it more readable. Below is the answer that paints the console of the code without simplifying:

console.log (response)

Object {
  readyState: 4,
  responseText: "<br />↵<font size='1'><table class='xdebug-error x… 11.759 alunos na Educação de joven' à la ligne 1",
  status: 200,
  statusText: "OK"}
  abort: (e)
  always: ()
  complete: ()
  done: ()
  error: ()
  fail: ()
  getAllResponseHeaders: ()
  getResponseHeader: (e)
  overrideMimeType: (e)
  pipe: ()
  progress: ()
  promise: (e)
  readyState: 4
  responseText: "<br />↵<font size='1'><table class='xdebug-error xe-warning' dir='ltr' border='1' cellspacing='0' cellpadding='1'>↵<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\new-g\classes\update.php on line <i>24</i></th></tr>↵<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>↵<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>↵<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0000</td><td bgcolor='#eeeeec' align='right'>144312</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\new-g\classes\update.php' bgcolor='#eeeeec'>..\update.php <b>:</b>0</td></tr>↵<tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0010</td><td bgcolor='#eeeeec' align='right'>152720</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysqli-fetch-assoc' target='_new'>mysqli_fetch_assoc</a>↵(  )</td><td title='C:\wamp\www\new-g\classes\update.php ' bgcolor='#eeeeec'>..\update.php <b>:</b>24</td></tr>↵</table></font>↵[null]Erreur de syntaxe près de 'o fim de março de 2014 foram matriculados  11.759 alunos na Educação de joven' à la ligne 1"
  setRequestHeader: (e,t)
  state: ()
  status: 200
  statusCode: (e)
  statusText: "OK"
  success: ()
  then: ()
  __proto__: Object
    
asked by Pablo García 05.05.2016 в 17:10
source

1 answer

3

First you must know that this way you will never save anything in database since you never execute the query:

$repuesta=$db_connection->query($sql);

Second; it seems to me that he is going through the error because you tell him that he is going to return a reply json:

dataType: 'json',

but you do not return anything, you just close the connection:

$db_connection->close();

and then you kill the process (this is what is more wrong How will you respond to javascript if you tell it to die?). die is to finish the processes when there is an error (eg failure in the connection to bd), is not to finish the scripts at all times:

die();

The die should be used like this:

$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT) or die("Error de conexión");

Greetings

    
answered by 05.05.2016 / 17:32
source