I'm trying to return variables within the success of an ajax request to validate that "something" was done within the system, in this case not letting it proceed until it adds elements to a list.
$("#saveList").on(\'submit\',(function(e) {
e.preventDefault();
formString = $("#previewList").serialize();
$.ajax({
url: "lists/list.php",
data: formString,
type: "GET",
dataType: "json",
success: function(data){
if(data.valida == "zero"){
toastr.warning("Agrega al menos un elemento a la lista");
}else{
alert("Lista guardada");
location.reload(true);
}
},
error: function(data){
console.log("error")
}
});
})
);
And in the list.php script, I do the validation in this way, return a variable with the string value "zero" and finish the execution of the script:
$result = mysqli_query($link,"SELECT * FROM lists WHERE emp = $idemp");
$count = mysqli_num_rows($result);
// if there is no rows
if($count == 0){
$data['valida'] = 'zero';
echo json_encode($data);
exit;
}
And when I do have elements in the list, I have to create a pdf, but when printing the pdf with the script the else of the validation in the succes:
}else{
alert("Lista guardada");
location.reload(true);
}
It doesn't work, it doesn't make the alert and it doesn't refresh the page, my question is, is there any other way that isn't through json to return variables from the script to the success of the request to be able to use them inside the success??
You have several bugs, and well a limited idea abstraction. I will leave you an example so you can see how the front and back can interact harmoniously
in your javascript
Now your PHP has several syntax and logic errors, I tried to fix it and "I suppose" that your server should do it that way, you can modify it to your liking.
Remember to add your database connection script.
I hope the example will serve you, greetings.