Return php result to javascript

Asked

Viewed 821 times

1

I’m making the POST request by AJAX:

HTML FORM (administration.php):

<form align="center" width="50" name="excluir_documento" id="excluir_documento" onClick='return confirma_excluir_documento()' method="POST"> 
<input type="text" name="prefixo" id='prefixo' hidden value="DE"></a>
<input type="text" name="sequencial" id='sequencial' hidden value="310"></a>
<input type="text" name="nome_conf" id='nome_conf' hidden value=""></a>
<input type='submit' name='excluir_documento' id='excluir_documento' value='' class='imgExcluir' title='Excluir' ></a> 

Javascript (funcoes.js):

function confirma_excluir_documento() {
            vex.defaultOptions.className = 'vex-theme-default';
            vex.dialog.confirm({
                message: 'Você irá excluir o documento. Deseja continuar?',
                callback: function(resultado) {
                    if (resultado) {
                        $.ajax({
                            type: "POST",
                            url: "excluir.php",
                            data:{
                                prefixo : $("#prefixo").val(),
                                sequencial : $("#sequencial").val(),
                                nome_conf : $("#nome_conf").val(),
                                excluir_documento : 1
                            },
                            success: function (response) {
                                vex.dialog.alert('response');
                            }
                        }); 
                    }
                }
            });
                return false;
        }

We have sent the php delete.php page:

if(isset($_post['excluir_documento']))...
... if($excluir_resultado){
echo "Documento excluído com sucesso";} 
else{
echo "Erro ao excluir";}

The problem I need the return of what happened with the query of the bank, I need to give the result inside the dialog box success: function (response){ vex.dialog.alert('response') ;}, the problem that the information coming from and the entire page, shaping the dialog box.

How do I get only the part echo "Documento excluído com sucesso";}? I have tried in several ways but I could not, I searched the whole afternoon a solution and nothing.

1 answer

1


Initially the exclusion page does not need any extra return, but the confirmation of the deletion, or not. So a 1 for "deleted" and 0 for "not deleted" would be enough. Post her code to help you better.

With the return of the boolean value, you can perform the treatment with an "If" and define the answer you want within the HTML5 element you need.

Using, for example, Jquery’s "ajax()" function you can handle request events, as well as work on many other options.

(See in : http://api.jquery.com/jquery.ajax/)

var menuId = $( "ul.nav" ).first().attr( "id" );
//pega a variavel, monta o objeto e faz o pedido
var request = $.ajax({
  url: "excluir.php",
  method: "POST",
  data: { id : menuId },
  dataType: "html"
});

//se ok com a requisição, trata o resultado (exluido sim ou não)
request.done(function( msg ) {
  $( "#retorno" ).html( msg ); //coloca o resultado dentro do container "#log"
});
 
//caso a requisiçao falhe
request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus ); //alerta do erro
});

I hope I’ve helped.

Hug.

UPDATE//

Your delete.php code will look like this:

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* isso retornara o numero correto de linhas excluidas se houver mais de 1 */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Registros excluídos: %d\n", mysql_affected_rows());

/* se for somente uma linha, retonará sempre 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Registros excluídos: %d\n", mysql_affected_rows());
?>

  • Thanks for the answer, I’ve been looking for this processing of Jquery requests, but I didn’t understand it very well. How will I make that return after I execute and treat the query from the bank? Have I tried echo ?><script>return resposta_banco();</script><?php to call a function with the dialog box, not even the time to execute the function because the page only runs the code and already closes.

  • When you run a Mysql query with PHP, it returns a value with the number of lines affected. You can use this as a basis. If delete 1, it returns that a line was affected. 2, "2 affected lines", so on.

  • You will return plain text, with ECHO or PRINTF. ;) Javascript you do on client side.

  • It worked here, I had even found another solution that gets the same result, but its code gets more objective. Thank you, now a small doubt. How do I submit this request via php class and function up to the delete code?

  • William, try to describe to me better what you want the procedure to do, so I can better guide myself in helping you. What are the steps? What you want the system to do. .

  • I got it now, thank you

  • Thanks! *Steps = steps (broker getting in! rs)

  • I did what you gave me, but I had information that would only contain in php, I would need this return to display in the msg of Alert. Would global variable solve?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.