Sending variables in Ajax to PHP

Asked

Viewed 780 times

2

Using php I do a BD search and send the data to AJAX via JSON:

echo json_encode(array('sucesso'=>true, 'mensagem'=>'Dados inseridos com sucesso','idservico'=>$idServico));

In AJAX I manipulate the variables and now I need to send the idservice variable to the view. For this I created input id='idservico', in my html(.php) file, and in Ajax I assign the value

msg = $.parseJSON(msg);
$('#idservico').val(msg.idservico);

In my html file I need to do a new search, without there being a refresh on the page. My question is how do I capture a value in AJAX, send to a new PHP request?

I tried to store cookies in Ajax and then read in PHP but I don’t know if I did it right.

recording in AJAX: $.cookie("idservico",msg.idservico);

Reading in PHP: $_COOKIE['idservico];

My Jquery code:

$('#abrirServico').click(function () {
    // - Requisitamos os valores dos campos...
    var data  = $("#data").val();
    var idcliente = $("#idCliente").val();
    var idcarro = $("#idCarro").val();
    var page = 'grava_servico.php';
    $.ajax({
        type: 'POST',
        dataType: 'html',
        url: page,
        beforeSend: function () {
            $("#abrirServico").html("Salvando os dados");
        },
        data: {data:data, idcliente:idcliente, idcarro: idcarro},
        success: function (msg) {
            msg = $.parseJSON(msg);
            if(msg.sucesso == true){
                alert(msg.mensagem);
                // exibe o formulário para adicionar novas peças
                $('#itensServico').css("display","block");
                //atribui o valor do idservico para ser usado na hora de salvar na tabela peca_servico
                $('#idservico').val(msg.idservico);
                $.get('new.php', {'idservico': msg.idservico});    
            } else {
                alert(msg.menssagem);
            }
            $("#abrirServico").html("Serviço Aberto");
            $("#abrirServico").attr('disabled', true);
            $("#buscarCliente").attr('disabled', true);
            $("#resetCliente").attr('disabled', true);
            $("#buscarCarro").attr('disabled', true);
            $("#resetCarro").attr('disabled', true);
        },

    });
})
  • Why not send via GET or via POST?

  • Can’t... GET and POST would refresh the page

  • They wouldn’t do GET or POST inside Ajax, unless you want to keep the idservico for the next browsing.

  • I don’t need to keep idservico in the next navigation. There’s an example of how to do this?

  • Something like $.get('pagina.php', { 'idservico': $('#idservico').val() }) will send the previously caught id to supposed next AJAX request (no paging)

  • how do I capture the idservico variable on the php page? I did <?php echo $_GET['idservico'] ? >, but it didn’t work.

  • It’s because you did something wrong in sending GET. Without seeing your JS code I won’t be able to know where the failure was.

  • edited my question with jquery code

  • You just put the $.get('new.php', {'idservico': msg.idservico}); randomly, this is not how you use ajax, there is no way to know if new.php received the variable, you have to apply the .done and the .fail to get answers to Ajax HTTP requests. Example: $.get('pagina.php', { 'idservico': $('#idservico').val() }).done(function (resposta) { alert(resposta); }).fail(function () { alert("Erro"); });, so go run and you’ll know if it worked out in the back-end

  • the code you sent me fell on the .fail. How should I receive in the back-end?

  • do so .fail(function (a, b) { alert([a, b]); }); and tell me what it looks like

Show 6 more comments

1 answer

3


It’s easy, young man, this is your request:

$('#abrirServico').click(function () {
// - Requisitamos os valores dos campos...
var data  = $("#data").val();
var idcliente = $("#idCliente").val();
var idcarro = $("#idCarro").val();
var page = 'grava_servico.php';
$.ajax({
    type: 'POST',
    dataType: 'html',
    url: page,
    beforeSend: function () {
        $("#abrirServico").html("Salvando os dados");
    },
    data: {data:data, idcliente:idcliente, idcarro: idcarro},
    success: function (msg) {
        msg = $.parseJSON(msg);
        if(msg.sucesso == true){
            alert(msg.mensagem);
            // exibe o formulário para adicionar novas peças
            $('#itensServico').css("display","block");
            //atribui o valor do idservico para ser usado na hora de salvar na tabela peca_servico
            $('#idservico').val(msg.idservico);
            $.get('new.php', {'idservico': msg.idservico});    
        } else {
            alert(msg.menssagem);
        }
        $("#abrirServico").html("Serviço Aberto");
        $("#abrirServico").attr('disabled', true);
        $("#buscarCliente").attr('disabled', true);
        $("#resetCliente").attr('disabled', true);
        $("#buscarCarro").attr('disabled', true);
        $("#resetCarro").attr('disabled', true);
    },

});

})

now you assign a variable to this your service id, so:

meu_id_servico = $('#idservico').val(msg.idservico);

note that the variable is global. A hint Ajax works in a way assíncrona or if you put two ajax, the two will start to run together so you need to wait the first end to pick up the value of meu_id_servico and send to another request right? How to do this?

Simple, just put this other request inside .done() of the first ajax. ie it will be executed when the first one is ready. (in other words when its variable id_serviço is filled).

at the end of your request let her so:

        $("#resetCliente").attr('disabled', true);
        $("#buscarCarro").attr('disabled', true);
        $("#resetCarro").attr('disabled', true);
    },

}).done(function() {

       //aqui o código da sua nova requisição    
       $.ajax({
            type: "POST",
            url: "url_nova.php",
            **data: { meu_id_servico : meu_id_servico},**
            cache: false,
            beforeSend: function() {

            },
            complete: function() {

            },
            success: function (retorno) {

            },
            error: function(data) {
                console.log(data);
            }
        });

});
  • Dude, ball show your explanation... Still on to understand the logic of AJAX’s asynchronousness. I was sinning precisely on this. Your explanation worked out.

  • Hahaha I also took a long time to understand how it worked, I read in a question that they passed me

Browser other questions tagged

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