Foros del Web » Programando para Internet » Javascript » Frameworks JS »

cargar en la base de datos sin recargar con ajax

Estas en el tema de cargar en la base de datos sin recargar con ajax en el foro de Frameworks JS en Foros del Web. Buenas, cuento rapidamente mi problema... necesito insertar datos en mi base de datos mysql sin hacer un submit ya que si lo hiciera, perderia una ...
  #1 (permalink)  
Antiguo 27/09/2012, 13:52
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
cargar en la base de datos sin recargar con ajax

Buenas, cuento rapidamente mi problema... necesito insertar datos en mi base de datos mysql sin hacer un submit ya que si lo hiciera, perderia una ruta que hago con google maps. Para esto he oido por ahi que necesitaria insertar los datos mediante Ajax... soy nuevo en el tema.... manejo muy bien php, pero esta es la primera vez que me encuentro con un problema de este tipo.... espero que alguien me pueda dar una mano de como puedo hacer.... para utilizar mi php... sin tener que recargar la pagina..... saludos... dejo mi form para ver si mas o menos se entiende lo que quiero hacer....



Código HTML:

           
           <form action="addCity.php" id="add" name="addCity" method="post">
           
           <center>
           
           <table>
   




<tr>

<td>Selected City:</td>

<td><input type="text" id="city" readonly="readonly" style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-weight:bold; color:#F00; font-size:16px;" /></td>



</tr>






   
   
    <tr>
   
   

   
    <td>Arrival Date:
    <br/>
    <input type="text" id="datepicker_value" name="arrival"  readonly="readonly"/>
    
    </td>
    
    <td><div id="datepicker"></div></td><td></td>
    
    </tr>
   
   
    <tr>
    <td>Departure Date: 
    <br/>
    <input type="text" id="otrodatepicker_value" name="departure" readonly="readonly" />
    
    </td>
    <td><div id="otrodatepicker"></div></td><td></td>
    </tr>
   
   <tr>
   
   
   <tr>
   
   <td>Comment:</td>
   
   <td><input type="textarea" id="comment" name="comment" style="width:300px; height:200px;" /></td>
   
   
   
   
   </tr>
   
   
   
   <tr>
   
    <td></td>
    <td>
    <br/>




</td>
    
    </tr>
    
    
    
    <tr>
    <td></td>
    
    <td align="center" class="style1"><input type="button" value="Save City"  id="savecity" onclick="save()" disabled="disabled" /></td>
    </tr>
    
    
    
    
    
    
    
    
    
    
   
    </table>
   
   
    </center> 
  #2 (permalink)  
Antiguo 27/09/2012, 14:00
Avatar de Dradi7  
Fecha de Ingreso: junio-2008
Ubicación: Peru - Lima
Mensajes: 1.518
Antigüedad: 15 años, 10 meses
Puntos: 220
Respuesta: cargar en la base de datos sin recargar con ajax

ejemplo de como debes usar ajax

Código Javascript:
Ver original
  1. function createAjax(){
  2.    if (window.XMLHttpRequest)
  3.    {
  4.       xmlhttp=new XMLHttpRequest();
  5.    }
  6.    else
  7.    {
  8.       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  9.    }
  10. }
  11.  
  12. function save()
  13. {
  14.     createAjax();
  15.     xmlhttp.onreadystatechange=function()
  16.     {
  17.         if (xmlhttp.readyState==4 && xmlhttp.status==200)
  18.         {
  19.             if(xmlhttp.responseText == "OK")alert('REGISTRO ACTUALIZADO');
  20.         }
  21.     }
  22.     xmlhttp.open("GET","save.php",true);
  23.     xmlhttp.send("ID=4");
  24. }
__________________
La clave de todo triunfador es eliminar todas sus excusas y sus limitaciones
  #3 (permalink)  
Antiguo 27/09/2012, 14:11
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: cargar en la base de datos sin recargar con ajax

gracias por la respuesta... entendi algo... el tema es... como seria el html? o el boton por el cual se envia esto?
  #4 (permalink)  
Antiguo 27/09/2012, 14:13
Avatar de Dradi7  
Fecha de Ingreso: junio-2008
Ubicación: Peru - Lima
Mensajes: 1.518
Antigüedad: 15 años, 10 meses
Puntos: 220
Respuesta: cargar en la base de datos sin recargar con ajax

pero ya tienes el boton solo debes quitar el disabled nada mas o en todo caso crear otro boton

Código HTML:
Ver original
  1. <input type="button" value="Save City"  id="savecity" onclick="save()" disabled="disabled" />
__________________
La clave de todo triunfador es eliminar todas sus excusas y sus limitaciones
  #5 (permalink)  
Antiguo 27/09/2012, 14:27
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: cargar en la base de datos sin recargar con ajax

aaa ahora entendi!!! lo voy a probar a ver como me va... luego te cuento....
  #6 (permalink)  
Antiguo 28/09/2012, 12:23
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: cargar en la base de datos sin recargar con ajax

probe el ajax q me pasaste y funciona bien... el tema esta en que no me agrega los campos correctamente en la base de datos... probe cambiando el button a submit y ahi si inserta datos... pero mediante ajax.... ingresa solo un dato en la bd... q viene por la variable session... te dejo mi php... y mi html para ver si alguien puede darme una mano
addCity.php
Código HTML:
<?php


class sites
{
	public $city;
	public $arrival;
	public $departure;
	public $comment;
    public $numrows;
    public $error;
    public $error2;
    public $ok;
    public $fields;
    public $regquery;
    
    public function __construct($city,$arrival,$departure,$comment)
    {
    include "config.php";
	    $this->city=$city;
		$this->arrival=$arrival;
		$this->departure=$departure;
		$this->comment=$comment;
		$this->error="El campo ciudad no puede estar vacio";
		$this->error2="Day of arrival can not be after a day of departure";
		$this->error3="Day of departure can not be until the arrival day";
		$this->query=mysql_query("SELECT * FROM sites WHERE city = '".$this->city."'");
		$this->numrows=mysql_num_rows($this->query);
        $this->ok=header('location:site.php');
       
    }
	
    public function check()
    {
		 session_start();
         
		 
	
	
	
		
		
		
		if($this->city=="")
		{
			echo $this->error;
		}
		
		
		if($this->arrival>$this->departure)
		{
			echo $this->error2;
		}
		
		if($this->departure<$this->arrival)
		{
			echo $this->error3;
		}
		
		else
		{	
         $register = mysql_query("INSERT INTO sites(city,arrival,departure,comment,nombreCirc) VALUES ('".$this->city."','".$this->arrival."','".$this->departure."','".$this->comment."','".$_SESSION['namecirc']."')");
		 echo $this->ok;
		 
		 
	
		 
		 
		 
		 
		}
		
	}
	
}
include_once "clear.php";
$reg = new sites(clear($_GET['city']),clear($_GET['arrival']), clear($_GET['departure']), clear($_GET['comment']));
echo $reg->check();


?>
y este es el php que contiene el form

Código HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Trip Minded - Add Site</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<link rel="stylesheet" href="colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://tripminded.com/app/circuits/colorbox/jquery.colorbox.js"></script>
<link type="text/css" href="js/jquery-ui-1.8.6.custom.css" rel="Stylesheet" /> 
<link type="text/css" href="autocompletado.css" rel="stylesheet" />  
<link href="upload.css" rel="stylesheet" type="text/css" />  
<script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script>
<script type="text/javascript" src="js/colorbox.js"></script>  
<script type="text/javascript" src="js/ciudades.js"></script>
<script type="text/javascript" src="js/funcionalidades.js"></script>
<script type="text/javascript" src="js/jquery.ui.js"></script>
















</head>

<body>

<center>





<table width="800" border="1">
<tr>
    <th width="267" scope="row">&nbsp;</th>

    <td width="225" align="center"><div style="font-weight: 700; font-size:20px; width: 596px">Add Sites for your Circuit</div></td>
    <td class="style1">&nbsp;</td>
</tr>
<tr>
    <th scope="row">&nbsp;</th>
    <td>&nbsp;</td>
    <td class="style1">&nbsp;</td>
</tr>

<tr>
    <th scope="row">City:</th>
    <td>
    
 
   
   
    <input type='text' name='ciudad' id='ciudad'  onfocus="javascript:this.value=''" class='ui-widget' />
        
    <button onclick='agregarCiudad();'  id='add' style='width: 144px'>Add City</button>

  
    
    
    
   
   

   
   
   
    
    </td>  
    <td align="center" class="style1"><a class='inline' href="#inline_content" style="text-decoration:none; font-weight:bold; font-size:18px;"><input type="button" value="+" id="more" disabled="disabled"  ></a>
    <!-- This contains the hidden content for inline calls -->
    
    <div style='display:none'>
    
    <div id='inline_content' style='padding:10px; background:#fff;'>

           
           
           
           
           
           
           
           <center>
           
           
      
           
           
           
           
           <form action="addCity.php" id="add" name="addCity" method="get">
           
           
           
           <table>
   




<tr>

<td>Selected City:</td>

<td><input type="text" id="city" name="city" readonly="readonly" style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-weight:bold; color:#F00; font-size:16px;" /></td>



</tr>






   
   
    <tr>
   
   

   
    <td>Arrival Date:
    <br/>
    <input type="text" id="datepicker_value" name="arrival"  readonly="readonly"/>
    
    </td>
    
    <td><div id="datepicker"></div></td><td></td>
    
    </tr>
   
   
    <tr>
    <td>Departure Date: 
    <br/>
    <input type="text" id="otrodatepicker_value" name="departure" readonly="readonly" />
    
    </td>
    <td><div id="otrodatepicker"></div></td><td></td>
    </tr>
   
   <tr>
   
   
   <tr>
   
   <td>Comment:</td>
   
   <td><input type="text" id="comment" name="comment" style="width:300px; height:200px;" /></td>
   
   
   
   
   </tr>
   
   
   
   <tr>
   
    <td></td>
    <td>
    <br/>




</td>
    
    </tr>
    
    
    
    <tr>
    <td></td>
    
    <td align="center" class="style1"><input type="button" value="Save City"  id="savecity" onclick="save()" disabled="disabled" /></td>
    </tr>
    
    
    
    
    
</form>

    
    
    
    
    
   
    </table>
   
   
    </center>
   
           </div>
       </div>

   
   
   
    </td>
   
   
   
 </tr>
 <tr>
    <th scope="row">&nbsp;</th>
    <td><div id="map_canvas" style="width: 600px; height: 400px"></div> </td>
    <td class="style1">&nbsp;</td>
 </tr>
 <tr>

    <th scope="row">Latitud:</th>
    <td><span id="lat" name="lat" style="width:586px;padding-left:10px; font-size:12px; font-family:Verdana, Geneva, sans-serif;"  /></span></td>
           
           
           
           
           
    <td></td>
 </tr>
 <tr>
    <th scope="row">Longitud:</th>
    
    
    
    <td><span id="long" name="long" style="width:586px; padding-left:10px; font-size:12px; font-family:Verdana, Geneva, sans-serif;"/></span></td>





    <td align="center" class="style1">&nbsp;</td>
 </tr>
 <tr>
    <th scope="row">&nbsp;</th>
    <td>&nbsp;</td>
    <td class="style1">&nbsp;</td>
 </tr>
 <tr>
    <th scope="row">&nbsp;</th>

    <td>&nbsp;</td>
    <td class="style1">&nbsp;</td>
 </tr>
</table>






</center>



    
    
    





</body>
</html>


  #7 (permalink)  
Antiguo 28/09/2012, 12:24
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: cargar en la base de datos sin recargar con ajax

aaa y dejo la function save() que es donde tengo el ajax... puedo insertar en la base de datos... pero me quedan campos vacios!


Código HTML:

function createAjax(){
   if (window.XMLHttpRequest)
   {
      xmlhttp=new XMLHttpRequest();
   }
   else
   {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
}

    function save() {
      
       document.getElementById('savecity').disabled = true;
       document.getElementById('more').disabled = true; 
	   document.getElementById('ciudad').value = "Select other city";
	   document.getElementById('add').disabled = false;
	   
	createAjax();
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            if(xmlhttp.responseText == "OK")alert('REGISTRO ACTUALIZADO');
        }
    }
	
    xmlhttp.open("GET","addCity.php",true);
    xmlhttp.send("ID=4");
	   
	   
	   
	   
    }
   

Última edición por maximendez88; 28/09/2012 a las 13:40
  #8 (permalink)  
Antiguo 28/09/2012, 15:03
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: cargar en la base de datos sin recargar con ajax

he arreglado la funcion save() intentando insertarle los campos... pero aun asi sigue enviando los campos de texto vacios. a la base de datos....... no se en que puedo estar fallando, la verdad me ha llevado todo el día esto.... y no veo la solución, ni en que estoy fallando ya que si al boton que le pongo la funcion save() lo hago del tipo submit.... me agrega los datos correctamente.... pongo nuevamente los ajustes en el codigo



Código HTML:
function objetoAjax(){
 var xmlhttp=false;
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
 }
 return xmlhttp;
}

	



    function save() {
      
       document.getElementById('savecity').disabled = true;
       document.getElementById('more').disabled = true; 
	   document.getElementById('ciudad').value = "Select other city";
	   document.getElementById('add').disabled = false;
	   
	   
	   
	    //valores de los cajas de texto
 city=document.getElementById('city').value;
 arrival=document.getElementById('datepicker_value').value;
 departure=document.getElementById('otrodatepicker_value').value;
 comment=document.getElementById('comment').value;
	   
	
	
 ajax=objetoAjax();


 ajax.open("GET", "addCity.php",true);
 ajax.onreadystatechange=function() {
  if (ajax.readyState==4) {
 
 if(xmlhttp.responseText == "OK")alert('REGISTRO ACTUALIZADO');
  }
 }
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

 //enviando los valores
 ajax.send()
}
   

Última edición por maximendez88; 28/09/2012 a las 15:29
  #9 (permalink)  
Antiguo 28/09/2012, 23:00
Avatar de Dradi7  
Fecha de Ingreso: junio-2008
Ubicación: Peru - Lima
Mensajes: 1.518
Antigüedad: 15 años, 10 meses
Puntos: 220
Respuesta: cargar en la base de datos sin recargar con ajax

pero tu error esta claro no estas enviando tus parametros en el ajax si vas a usar el GET entonces en tu URL deberia quedar asi

"addCity.php?city="+city+"&arrival="+arrival+"&dep arture="+departure+"&comment="+comment

en caso uses POST esto deberia ir en el ajax.send() asi

ajax.send("city="+city+"&arrival="+arrival+"&depar ture="+departure+"&comment="+comment)
__________________
La clave de todo triunfador es eliminar todas sus excusas y sus limitaciones
  #10 (permalink)  
Antiguo 01/10/2012, 12:58
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: cargar en la base de datos sin recargar con ajax

muchas gracias por la ayuda!! por fin lo logre solucionar!!! saludos

Última edición por maximendez88; 01/10/2012 a las 13:22

Etiquetas: ajax, input, php, select
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:41.