i have this action where i get the data via post in array format and save it to a database , this part works but im trying to do this via ajax, i think im having problems getting the data from the form or maybe sending the data to my php script.
<?php
$elegido = $_POST['producto'];
if(empty($elegido)) {
echo("No has seleccionado suficientes productos");
}
else {
$N = count($elegido);
for($i=0; $i < $N; $i++) {
$elegidos = $elegido[$i];
$conn=mysql_connect('localhost', 'user', 'pass');
mysql_select_db("database",$conn);
$query = "INSERT INTO table (column)";
$query .= "VALUES ('".$elegidos."')";
mysql_query($query) or die("Error sending data.<br>");
}
echo("Los datos fueron enviados correctamente, ¡gracias por participar!");
}
?>
i implemented this but it doesnt work
jQuery(function($) {
$("#enviar").click(function(e) {
e.preventDefault();
var opciones = {
method:"post",
url:"procesar.php",
producto = [];
data:{
data: {producto:producto},
},
success:function(result){
$("body .mensaje").remove();
if(result=="exito"){
$("body").append("<div class='mensaje'>Datos Enviados!</div>");
}else{
$("body").append("<div class='error'>ERROR</div>");
}
}
};
$.ajax(opciones);
});
});
any clue on whats going on?
data
should be like this:
// data: { name: "John", location: "Boston" }
jQuery(function($) {
$("#enviar").click(function(e) {
e.preventDefault();
var opciones = {
method:"post",
url:"procesar.php",
producto = [],
data:{ producto: producto }, // 'producto' will be an empty array, as you defined above.
},
success:function(result){
$("body .mensaje").remove();
if(result=="exito"){
$("body").append("<div class='mensaje'>Datos Enviados!</div>");
}else{
$("body").append("<div class='error'>ERROR</div>");
}
}
};
$.ajax(opciones);
});
});
You have a syntax error (the whole line of producto = [];
) and you are not sending the variables from the form to the php script.
This:
url:"procesar.php",
producto = [];
data:{
data: {producto:producto},
},
Should be something like:
url:"procesar.php",
data: $('form').serialize(),