I have the following query: I want to know if it is possible to use a variable in an attribute in ajax, I don't know if I am explaining myself, but in the following code I will try to explain:
<script>
function active_change_update(ruta, id, status, campo)
{
if(status==1 || status==null){
var estado = 0;
}else{
var estado = 1;
}
var dato = {
'id': id,
'_token': "{{ csrf_token() }}",
//por defecto utilizaba active ya que en mi tabla producto esta asi y lo unico que quiero modificar es el valor del active
//hasta aqui todo bien
'active': estado
};
$.ajax({
type: "PUT",
url: ruta,
dataType: 'json',
data: dato,
success:function(data) {
window.location.reload();
}
});
}
As you can see, I want to modify the value of active, but I realized that I can use this function to modify various attributes of other tables, for example "sold" or "delivered" which are also boolean. What I want to do is the following:
function active_change_update(ruta, id, status, campo)
{
if(status==1 || status==null){
var estado = 0;
}else{
var estado = 1;
}
//recibo el valor de "campo" que en este caso es "vendido" y quiero pasar ese atributo al json
var dato = {
'id': id,
'_token': "{{ csrf_token() }}",
//de esta manera
campo: estado
};
$.ajax({
type: "PUT",
url: ruta,
dataType: 'json',
data: dato,
success:function(data) {
window.location.reload();
}
});
}
This is absolutely not the right way and I have searched for various alternatives, I would really appreciate it if you could help me with this. From already thank you very much.
First create a dynamic text string , you do this by concatenating the values.
it has to be with single quotes as the example shows
then to be able to send your data by ajax you need to convert your string to Json with
JSON.Parse()
your code would look like this:
the result :
you just need to adjust your token.
I hope it helps you, greetings.