Add elements to a list

Asked

Viewed 676 times

0

Good evening, I have an idea but don’t know how to perform it. I’m doing a order system, where a customer and their respective requests, and the most correct way I thought of doing that was to get the user to add the orders to a list, but here comes the problem, I can’t think of a way for the list to be completed without the page being reloaded. In short, when the user clicks "OK", a new order would be added to the table on the same page, without it being reloaded.

2 answers

1

Try using Ajax and COOKIES, you create a PHP file that adds the requests to the list (that would be the cookie) and puts a javascript function that calls this file via ajax on the button "OK", takes the response from the XML file and adds to the JS page.

Example of how I used in a project:

PHP:

<?php // Página que adiciona os produtos no carrinho    
    $id = $_GET['id'];  // ID do produto selecionado

    if (!isset($_COOKIE['carrinho'])) { // Verifica se o carrinho está vazio
        $carrinho = [0 => $id]; // A 1ª posição do array $carrinho (criado aqui) recebe o id do produto
        setcookie('carrinho', serialize($carrinho), time()+60*60*24*14, '/'); // Serializa o array no COOKIE carrinho
    } else {
        $carrinho = unserialize($_COOKIE['carrinho']); // Se não estiver vazio, cria um array com todos os produtos do carrinho
        $colocar = false; // Booleano que uso pra não repitir o mesmo produto

        // Checo se o produto selecionado já está no carrinho
        for ($i=0; $i < count($carrinho); $i++) { 
            if (!(in_array($id, $carrinho))) {
                $colocar = true;
            }
        }

        // Só adiciono ao carrinho se não tiver o produto nele ainda
        if ($colocar == true) {
            $carrinho[] = $id;
        }

        // Serializo o array dentro do COOKIE carrinho
        setcookie('carrinho', serialize($carrinho), time()+60*60*24*14, '/');
    }

    // Mando o número de produtos no carrinho como resposta, apenas para atualizar a tela do usuário
    echo count($carrinho);
?>

JS:

// Função que adiciona o produto no carrinho
function adicionarCarrinho(id) { 
	id = $(id).val(); // Pego o ID do produto como parâmetro (vc pode colocar o id no value do botão)
	
	AjaxRequest();

	if (!Ajax) {
		alert("Erro na chamada Ajax");
	} else {
		Ajax.onreadystatechange = respostaCarrinho;
		Ajax.open('GET', '_assets/ajax/adicionarCarrinho.php?id='+id); // Mando o ID para a página PHP por meio do Ajax
		Ajax.send(null);
		Ajax.close;
	}
}

// Função de resposta
function respostaCarrinho() {
	if (Ajax.readyState == 4) {
		if (Ajax.status == 200) {
			$("#itens").text(Ajax.responseText); // Mudo o valor escrito no carrinho
			if (Ajax.responseText == '0') {
				alert('Você não tem produtos no carrinho');
				window.location.href='index.php'
			}
		}
	}
}

  • So, sorry, one thing I didn’t comment, the products are already registered in the bank, calling the bank products would not be a problem, but rather add the list using them without reloading the page

  • So, I don’t really know if this is the best way to do it, but in an old project I used ajax to call a page that set a cookie containing an array of products selected by the user.

  • You can show me an example, I’m still in doubt, about how it works, I’m trying with Session, but it’s not working

  • I left as an example the code I used in a course work, remembering that I am not completely sure q this would be the best method, I started a short time with Ajax, but for me it worked as expected.

1


This you must do with ajax and jquery friend. When the person clicks, he adds the data in the div:

$(".adicionar").click(function(){
$.ajax({
type: 'POST',
url: 'resultado.php',
success: function(data) {
$(".tabela").append(data);
}
});
});

1) .add is the class you should add to a button in your HTML.

2) php result. is the file that makes the SQL query and returns the data. You can use echo.

3) .table is the class you should add in the div that will display the table.

  • So, I don’t need to perform the query again, because I already search the products and store them in attributes within an option. In this function resultado.php i would have to save in an array and add it to table?

Browser other questions tagged

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