renaming file with jquery and php from modal window - php

I am trying to rename a file from a modal window. The modal window runs fine and so does the php code for renaming the file. I have tried many different ways to send the data whithout exiting.
The form gets the value of a link image: name, directory and diferent actions: delete, update and resize. So when I click the link it opens the modal window with these values (I have also noticed that the value is the same when I click other image links each time)
The problem is that is not sending any value. I supose that there is a problem getting values: for example val() is a jQuery method. .value is the DOM Element's property, I would like to know how can I solve this.
the html code:
<div id="dialogo" title="Editar Imagen">
<p class="validateTips">Campo titulo requerido.</p>
<!--action="" method="post"-->
<form id="update" >
<fieldset>
<label for="titulo">Titulo</label>
<input type="text" name="titulo" id="titulo" class="text ui-widget-content ui-corner-all" />
<label for="Alt">Alt</label>
<input type="text" name="Alt" id="Alt" class="text ui-widget-content ui-corner-all" />
<label for="descripcion">Descripcion</label>
<input type="text" name="descripcion" id="descripcion" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
the ajax/jquery code:
<script type="text/javascript">
$(document).ready(function(){
var fname=$('a.ico-resize').attr("id");
var directory=$('a.ico-resize').attr("rel");
var deletecount=$('a.ico-resize').attr("value");
$('#titulo').val(fname);
$('#Alt').val(directory);
var descripcion = $("input#descripcion").val();
var dataString = 'descripcion='+ descripcion + '&titulo=' + titulo + '&Alt=' + Alt;
// var data_string = $("#update").serialize();
// Damos formato a la Ventana de Diálogo
var dialog = $("#dialogo").dialog({
// Indica si la ventana se abre de forma automática
autoOpen: false,
// Indica si la ventana es modal
modal: true,
// Largo
//width: 400,
// Alto
//height: 280,
// Creamos los botones
height: 300,
width: 350,
buttons: {
'Rename Image': function() {
// Mostrar Versión de PHP
$.ajax({
// Antes de realizar la llamada mostramos el ajax load
beforeSend: function(){
$('#respuestaAjax').html('<img id="loader" src="images/loading.gif"/>');
},
//cache: false, // Indicamos que no se guarde en cache
type: 'post', // Variables GET
url:'rename_img.php', // srcript a ejecutar
data: dataString,
//'titulo=titulo&descripcion=descripcion&Alt=Alt',
//$("form#update").serialize(),
//{"file":fname,"directory":directory, "descripcion":descripcion}, // paso de datos
// cuando es exitoso el llamado
success: function(response){
$('#respuestaAjax').html(response);
$('#' + deletecount).remove();
dialog.dialog( "close" );
}
});
},
Cerrar: function() {
// Cerrar ventana de diálogo
dialog.dialog( "close" );
}
}
});
$("a.ico-resize").click( function(e) {
e.preventDefault();
// dialog.dialog("open");
dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
});
});
</script>
php code:
<?php
$dir = $_POST['Alt'];
$file = $_POST['titulo'];
$nuevo= $_POST['descripcion'];
$img = $dir."/".$file;
$imagen = $dir."/".$nuevo;
//unlink ($img);
rename($img, $imagen);
echo $imagen;
?>
solved
finally all works with this code:
<script type="text/javascript">
$(function(){
var fname=$('a.ico-resize').attr("id");
var directory=$('a.ico-resize').attr("rel");
var deletecount=$('a.ico-resize').attr("value");
$('#titulo').val(fname);
$('#Alt').val(directory);
var descripcion = $('#descripcion').val();
var data_string = $("#update").serialize();
var dialog = $("#dialogo").dialog({
autoOpen: false,
modal: true,
height: 300,
width: 350,
buttons: {
Send: function(){
str = $("#update").serialize();
$.ajax({
beforeSend: function(){
$('#respuestaAjax').html('<img id="loader" src="images/loading.gif"/>');
},
cache: false,
type: 'POST',
url:'rename_img.php',
data: str,
contentType: "application/x-www-form-urlencoded",
success: function(response){
$('#respuestaAjax').html(response);
$('#' + deletecount).remove();
dialog.dialog( "close" );
}
});
},
Cerrar: function() {
dialog.dialog( "close" );
}
}
});
$("a.ico-resize").click( function(e) {
var id = $(this).attr('data-id');
var rel = $(this).attr('data-rel');
var value = $(this).attr('data-value');
$("#update").find("#titulo").val(id);
$("#update").find("#Alt").val(rel);
dialog.dialog('open');
});
});
</script>

The code looks fine as far as sending itself is considered. I mean it probably does send the request it's just the query that is wrong. (You can check in the firebug's console if the request is really send or not).
What you need to change is the place where you build the dataString. You build it once the page is loaded (in the $(document).ready function) so it's never rebuild after you change the values in your modal window.
You should move the code responsible for building dataString to the click handler of a.ico-resize.
Also I can't see where the titulo and Alt variables are set and, as you can see in your Firebug, they're set wrong.
Try this:
var dataString = 'descripcion='+ $('#descripcion').val() + '&titulo=' + $('#titulo').val() + '&Alt=' + $('#Alt').val();

The dataString value should be a JavaScript object like this
{Key:value, key : value .....}

Related

ajax functions .done and .fail, return without values

good afternoon
I have a problem, I am trying to save the data values from the form in the database.
AJAX is used to send the data using the POST method but when evaluating the outputs from the .done and .fail functions, they return no information.
This is the html
<div class="form">
<h1>Ingreso Alumno-Trabajo</h1>
<form name="formulario_contacto" id="formdata">
<p>
<label for="cest">cedula estudiante</label>
<input type="number" id="cest" name="cest" autofocus required>
</p>
<p>
<label for="nest">nombre estudiante</label>
<input type="text" id="nest" name="nest" required>
</p>
<p>
<label for="aest">Apellido estudiante</label>
<input type="text" id="aest" name="aest" required>
</p>
<p class="full-width">
<label for="tit">Titulo</label>
<textarea name="" id="tit" cols="30" rows="3" name="tit" required></textarea>
</p>
<p>
<label for="nase">nombre asesor</label>
<input type="text" id="nase" name="nase" required>
</p>
<p>
<label for="fsede">Sede :</label>
<select id="fSede" name="fSede">
<option value="Montalban">Montalban</option>
<option value="Guyana">Guayana</option>
<option value="Virtual">Virtual</option>
</select>
</p>
<p class="full-width button">
<input type="submit" value="Ingresar">
<input type="reset" value="Restaurar">
</p>
</form>
</div>
<div id="mensaje">
<h3></h3>
</div>
This is the JS using AJAX
<pre>
$(document).ready(function () {
// This part of the code will automatically execute when doc is ready.
$("#mensaje").html("");
$("input:submit").click(function () {
// We set the default action to be made once we submit.
// Let's validate the form first
if (validaForm()) {
var formulario = $("#formdata").serializeArray();
$.ajax({
// url: "php/enviar.php",
// type: "POST",
type: "POST",
url: "php/enviar.php",
dataType: "json",
data: formulario,
})
//do something when get response })
.done(function (respuesta) {
//do something when any erro
$("#mensaje").html(respuesta.mensaje);
alert("coño de la madre");
})
.fail(function (respuesta) {
//do something when any erro
alert("coño de la madre falla" + respuesta);
});
} else {
// We show this when the validation fails
$("#mensaje").html("falta Ingresar la data");
}
});
$("input:reset").click(function () {
$("#mensaje").html("");
});
});
</pre>
This is the PHP
<?php
echo "Estoy entrando aqui"; #I'm entering here
if(isset($_POST["cest"]))
{
$cedula = $_POST["cest"];
$nombre = $_POST["nest"];
$apellido = $_POST["aest"];
$titulo = $_POST["tit"];
$nomase = $_POST["nase"];
$sede = $_POST["fsede"];
$inserta = "INSERT INTO tbl-est-teg (cedula,nombre, apellido, titulo, nomase, sede) VALUES ('$cedula','$nombre','$apellido','$titulo','$nomase','$sede')";
$conexion = new mysqli("localhost","yguer2","s&4gBz6nPrA8*S7","estudiante-trabajo",3306);
$respuesta = new stdClass();
if($conexion->query($inserta)){
$respuesta->mensaje = "Se guardo correctamente";
}
else {
$respuesta->mensaje = "Ocurrió un error";
}
echo json_encode($respuesta);
}
?>
<script>
$(document).ready(function () {
// This part of the code will automatically execute when doc is ready.
$("#mensaje").html("");
$("#formdata").on("submit",function () {
// We set the default action to be made once we submit.
// Let's validate the form first
if (validaForm()) {
var formulario = $("#formdata").serializeArray();
$.ajax({
// url: "php/enviar.php",
// type: "POST",
type: "POST",
url: "php/enviar.php",
dataType: "json",
data: formulario,
}).done(function (respuesta) {
//do something when any erro
$("#mensaje").html(respuesta.mensaje);
alert("coño de la madre");
}).fail(function (respuesta) {
//do something when any erro
alert("coño de la madre falla" + respuesta);
});
} else {
// We show this when the validation fails
$("#mensaje").html("falta Ingresar la data");
}
});
$("input:reset").click(function () {
$("#mensaje").html("");
});
});
</script>
You could try by just doing that but as some people have told you in the comments, there are some serious vulnerability issues in your PHP file, but I guess you should solve this first,
Use the console, if you're using chrome you could just press F12,
There are several things to be asked, I'm guessing your validaForm() function is working well
If you have more questions please edit the original questions so we can help.
Post this in the Spanish version of this site and I could help you there too, just let me know.
Publica esto en el sitio en Español y te puedo ayudar allí, solo deja un comentario con el link a la pregunta.

upload.php not being called in AJAX request

I select an image, write something and then click submit. Once I click submit it posts to the DB, shows progress bar of upload successfully BUT the upload.php file is never called.
Question: What is wrong with my code, that is preventing the upload.php file from being called in the action="".
It was working at one point in time but I can't remember what changes I made for it.
UPDATED SCRIPT:
$('#feed_form').submit(function(e) {
var data = new FormData(this);
var url = $(this).attr("action");
if($('#file12').val()) {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
type: "POST",
url: "scripts/universal/upload.php",
data: data,
processData: false,
contentType: false,
success: function() {
$("#success_post").slideDown();
setTimeout(function() {
$('#success_post').slideUp();
}, 3000);
},
uploadProgress: function (event, position, total, percentComplete){
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete +' %</div>')
},
resetForm: true
});
return false;
}
});
<form name="feed_form" id="feed_form" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function() {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick">Post</button>
</form>
PHP:
if(!empty($_FILES)) {
if(is_uploaded_file($_FILES['file12']['tmp_name'])) {
$sourcePath = $_FILES['file12']['tmp_name'];
$targetPath = "images/uploads/".$_FILES['file12']['name'];
move_uploaded_file($sourcePath,$targetPath);
shell_exec("ffmpeg -f mp4 -i images/uploads/".$_FILES['file12']['name']." -ss 00:00:5.000 -vframes 1 images/uploads/".basename($_FILES['file12']['name'], ".mp4").".png");
//This line does not affect the code, it works perfectly fine when I try it with some different JS
}
}
You've not specified the url in $.ajax(). Maybe that's the only problem
Below is the corrected code, try it and let me know if it worked or not
<script type="text/javascript">
$(document).ready(function () {
$('#feed_form').submit(function (e) {
var url = $(this).attr("action");
var data = new FormData(this);
if ($('#file12').val()) {
if (!$("#btnSubmitFormClick").val()) {
$("#show_error_message").innerHTML = "Please write something before clicking submit";
} else {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
success: function () {
$("#success_post").show();
},
uploadProgress: function (event, position, total, percentComplete) {
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete + ' %</div>')
},
resetForm: true
});
return false;
}
}
});
$("#btnSubmitFormClick").click(function () {
document.getElementById("close_status_modal").click();
});
$("#feed_form").submit(function (e) {
$.ajax({
type: "POST",
url: "scripts/universal/post.php",
data: $("#feed_form").serialize(), // serializes the form's elements.
success: function (data) {
$('#textarea_writing').val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
</script>
<form name="feed_form" id="feed_form" action="upload.php" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function () {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick" style="display:none;">Post</button>
</form>
I ended up using the following code to solve my problem:
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file12").files[0];
var formdata = new FormData();
formdata.append("file12", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.open("POST", "scripts/universal/upload.php");
ajax.send(formdata);
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress-div").show();
_("progressBar").value = Math.round(percent);
}
function completeHandler(event) {
_("progressBar").value = 0;
$("#progress-div").hide();
}

PHP - MySQL - AJAX and Google chrome - Endless loop responses and other errors

I'm making a user registration form in PHP - MYSQL, AJAX jQuery and Codeigniter and loading the web page of records, Google chrome console launches a series of unlimited answers every second, the image here.
Note: There are also some slightly unusual behavior in Google Chrome I want to know the reason to solve them.
Selection in yellow: the answers are automatically generated limitless.
Selection in purple: Are the result or answer to that selected answer.
Selection Green: Other errors that I would like to know to be.
Code HTML:
<div class="ctn">
<h3>Upload file content ajax</h3>
<form action="" method="POST" id="form_file" name="form_file" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="imagex" id="imagex">
</div>
<button type="submit" id="btn_form" class="btn btn-primary">Subir imagen</button>
<div id="mensaje_status"></div>
</form>
</div><!--End ctn-->
Code AJAX:
$(function() {
//Empty content alert message
$('.alert .close').on('click', function(event) {
event.preventDefault();
$('.alert .msg').html('');
});
$('#form_file')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
imagex: {
validators: {
notEmpty: {
message: 'Obligatorio!'
},
file: {
extension: 'jpg,jpeg,png',
type: 'image/jpg,image/jpeg,image/png',
//maxSize: 9097152, // 2048 * 1024
message: 'imagen no válida ( JPG, JPEG, PNG ) | Max 9MB'
}
}
}
}
})
.on('success.form.fv', function (e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation'),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="imagex"]')[0].files;
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
formData.append('imagex', files[0]);
formData.append('id', Math.random());
$.ajax({
//Star preloader
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Convertimos el porcentaje en valor entero
var porcentageRound = percentComplete * 100;
//Mostramos la ventana modal
$('#modal_progress').modal('show');
//Limpiamos el área de mensaje en caso de que tenga información
$('#form_file #mensaje_status').html('');
//Width bar progress
$('.progress-bar').css({
width: percentComplete * 100 + '%'
});
$(".progress-bar").html('<div id="progress-status">' + Math.round(porcentageRound) +' %</div>');
//Ocultamos el loader
if (percentComplete === 1) {
//Podemos manipular los elementos del DOM
//Ocultamos la barra de progreso
$('.progress').addClass('oculto');
//Reseteamos la barra de progreso
$('.progress-bar').css('width', '0%');
//Mostramos un mensaje mientra recibimos respuesta del servidor
$('#modal_progress .mensaje').html('<i class="fa fa-cog fa-spin font20"></i> Procesando espere por favor!');
}
}
}, false);
return xhr;
},
url: '/upload_ajax_full/do_upload/',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
var data = $.parseJSON(data);
if (data.respuesta == true) {
//Limpiamos el área de mensaje en caso de que tenga información
$('#form_file #mensaje_status').html('');
//Cerramos la ventana modal
$('#modal_progress').modal('hide');
//Habilitamos la barra de progreso
$('.progress').removeClass('oculto');
//Limpiamos mensaje
$('#modal_progress .mensaje').html("");
//Limpiamos el campo de imagen
$('#imagex').replaceWith($('#imagex').clone( true ));
//Mostramos mensaje del servidor
$('#form_file #mensaje_status').append(data.mensaje);
}
if (data.respuesta == false) {
//Limpiamos el área de mensaje en caso de que tenga información
$('#form_file #mensaje_status').html('');
//Cerramos la ventana modal
$('#modal_progress').modal('hide');
//Habilitamos la barra de progreso
$('.progress').removeClass('oculto');
//Limpiamos mensaje
$('#modal_progress .mensaje').html("");
//Limpiamos el campo de imagen
$('#imagex').replaceWith($('#imagex').clone( true ));
//Mostramos mensaje del servidor
$('#form_file #mensaje_status').append(data.mensaje);
}
// You can reset the form if you want
fv.resetForm(true);
// You can enable the submit button
// to allow the user to add new record
fv.disableSubmitButtons(true);
}
});
});
});

Dropzonejs How to send form fields and upload the file when submit button is pressed

I'm new in jQuery and Dropzone.js, So, my issue is that I'm unable to send form data with uploaded file. this is my code:
Form:
<form class="form-horizontal" id="validation-form" method="get">
<div class="form-group">
<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="carrier">Carrier</label>
<div class="col-xs-12 col-sm-6">
<select id="carrier" name="carrier" class="select2" data-placeholder="Select...">
<option value=""> </option>
<option value="FEDEX">FEDEX</option>
<option value="UPS">UPS</option>
<option value="DHL">DHL</option>
<option value="USPS">USPS</option>
<option value="Others">Others</option>
</select>
</div>
</div>
Dropzone Part:
<div id="dropzone" class="dropzone alert alert-success ">
<div class="dz-message dropzone-previews">
<h2 lighter block green>Drag PDF.</h2>
<span class="glyphicon glyphicon-send"></span>
</div>
</div>
This is my script code of the dropzone:
<script type="text/javascript" >
$(document).ready(function() {
Dropzone.autoDiscover = false;
$("#dropzone").dropzone({
url: "uploads.php",
autoProcessQueue: false,
previewsContainer: ".dropzone-previews",
uploadMultiple: false,
addRemoveLinks: false,
//addRemoveLinks: true,
maxFiles: 1,
maxFileSize: 1000,
dictResponseError: "Ha ocurrido un error en el server",
acceptedFiles: 'application/pdf',
});
});
</script>
And this is the ajax that is able to send the data of the form.
submitHandler: function(form, file) {
$("#loading").html('<img src="imagenes/cargando.gif" width="50" height="50" /><br />Grabando Pre-Alerta');
$.ajax({
type: 'POST',
url: "uploads.php",
data: {
carrier: $("#carrier").val(),
store: $("#tienda").val(),
valor: $("#valor").val(),
descripcion_envio: $("#confirmacion").val(),
tracking_number: $("#tracking").val()
},
dataType: 'json',
success: function(data) {
$("#loading").html('');
if (data.resultado == "false") {
$('#texto_popup_error').html("Usuario o contraseña incorrectos");
$('#errorIngreso').modal('show')
} else {
if (data.no_prealerta == "0") {
$('#texto_popup_error').html("Error al grabar la PreAlerta o bien ya fue grabada. Intente de nuevo. Si tiene el mismo error su Tracking Number ya fue grabado.");
$('#errorIngreso').modal('show')
} else {
document.getElementById("tienda").value = "";
document.getElementById("valor").value = "";
document.getElementById("confirmacion").value = "";
document.getElementById("tracking").value = "";
$('#texto_popup_error').html("No. de alerta generada: " + data.no_prealerta);
$('#errorIngreso').modal('show')
}
}
}
});
},
invalidHandler: function(form) {}
});
So, the question is how to upload file and send the data from .ajax at the same time when press submit button.
Instead of invoking an entirely new ajax request, you can just capture the sending event of the dropzone function and append your form values directly to it:
$("#dropzone").dropzone({
url: "uploads.php",
//....etc
sending: function(file, xhr, formData) {
formData.append("carrier", $('#carrier').val());
formData.append("store", $('#tienda').val());
formData.append("valor", $('#valor').val());
formData.append("descripcion_envio", $('#confirmacion').val());
formData.append("tracking_number", $('#tracking').val());
}
//...etc
});
Dropzone has different events and one of them is "sending"
You can do something like this:
$(document).ready(function(){
Dropzone.autoDiscover = false;
$("#dropzone").dropzone({
url: "uploads.php",
autoProcessQueue: false,
previewsContainer: ".dropzone-previews",
uploadMultiple: false,
addRemoveLinks: false,
//addRemoveLinks: true,
maxFiles: 1,
maxFileSize: 1000,
dictResponseError: "Ha ocurrido un error en el server",
acceptedFiles: 'application/pdf',
init: function () {
//append the data in the formData object.
this.on("sending", function (file, xhr, formData, e) {
formData.append("carrier", $('#carrier').val());
formData.append("store", $('#tienda').val());
formData.append("valor", $('#valor').val());
formData.append("descripcion_envio", $('#confirmacion').val());
formData.append("tracking_number", $('#tracking').val());
}
}
});
});

How to do auto complete for same class

The textarea will show when I click add row. The textarea has item in autosuggestion on keyup. My problem is the first one shows autocomplete. anothers are not working
<textarea id="name" class="name" name="name"></textarea><ul></ul>
<textarea id="name" class="name" name="name"></textarea><ul></ul>
<textarea id="name" class="name" name="name"></textarea><ul></ul>
<script type="text/javascript">
$(document).ready(function(){
$(".name").keyup(function(){
var name = $(this).val();
$.ajax({
url:"ajax.php",
type:"POST",
data:{name:name},
success:function(res)
{
$(".name + ul").append("<li class=item>"+res+"</li>");
}
});
});
$("ul").on("click", "li", function(){
var item = $(this).text();
$(".name").val(item);
$("ul li").remove();
});
});
</script>
Here is an example that does not need any id associated with the text areas.
<textarea class="name" name="name1"></textarea><ul></ul>
<textarea class="name" name="name2"></textarea><ul></ul>
<textarea class="name" name="name3"></textarea><ul></ul>
<script type="text/javascript">
$(document).ready(function(){
$(".name").keyup(function(){
var field = $(this);
var name = field.val();
$.ajax({
url:"ajax.php",
type:"POST",
data:{name:name},
success:function(res)
{
field.next("ul").append("<li class=item>" + res + "</li>");
}
});
});
$("ul").on("click", "li", function(){
var li = $(this);
var item = li.text();
li.parent('ul').empty().prev('.name').val(item);
});
});
</script>
try
var name = $(this).val();
var data = name + "&Sessid=" + Math.random();
$.ajax({
url:"ajax.php",
type:"POST",
data:data,
success:function(res)
{
$(".name + ul").append("<li class=item>"+res+"</li>");
}
});
});
First of all, change id and name fields for your textarea. It's not good idea to give same id name to your elements.
<textarea id="name1" class="name" name="name1"></textarea><ul></ul>
<textarea id="name2" class="name" name="name2"></textarea><ul></ul>
<textarea id="name3" class="name" name="name3"></textarea><ul></ul>
Now, get id name by this:
var which_id = $(this).attr('id');
And use which_id variable to your ajax response.
$.ajax({
url:"ajax.php",
type:"POST",
data:{name:name},
success:function(res)
{
$("#"+which_id+" + ul").append("<li class=item>"+res+"</li>");
}
});

Categories