Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php AJAX not working in conjunction with my php script and mysql

Tags:

ajax

php

So here I am posting my first PHP function that I am proud of but I just recently learned about AJAX and wanted to test it out. Unfortunately I can't get it to work.


My experience: PHP (3 weeks). CSS3, HTML, Basic Javascript.


My Problem: Getting AJAX to work. I want ajax to get my data from the php file which gets the votes from my test server (Xampp) database. So each time the user clicks on good or bad AJAX should display the new results without refreshing the page. The issue is however that: A) My if statements work by checking isset($_POST) which wont work anymore if I call by AJAX. B) Preventing refresh. C) Making AJAX update after every click. I know im nearly there, im just missing something and I dont know exactly what it is to be honest.


What I tried: Checked my database connection. Checked if my php code worked without ajax and it does perfectly fine (I am just displaying half of the functionality here, a lite version, for the sake of simplicity). Tried to change submit to button. Cache clearing. Jquery is in the head of my document and the path is correct. Watched tutorials and read the documentation but I am just not heading anywhere, probably due to lack of experience.

Edit: Sessions and everything php works fine. I my session start and database connection are included on the very top.


Summary: How do I fix this ajax so that it always updates my numbers?


Let me know if you want me to explain parts of my php code. Im willing to comment the parts if neccesary.


JQUERY / AJAX CODE

function vote() {
        var request = $.ajax({
            url: "php/core/voting_system.php",
            type: "POST",           
            dataType: 'html'
        });

        request.done(function(vote_sum) {
            $("#votes").html(vote_sum);         
        });
}

HTML CODE:

<div id='votes'></div>

<form id="good" action="" method="post">
    <input type="submit" name="good" onclick="vote()" value="+">
</form>

<form id="bad" action="" method="post">
    <input type="submit" name="bad" onclick="vote()" value="-">
</form>
like image 425
Asperger Avatar asked Sep 26 '22 21:09

Asperger


1 Answers

In HTML you don't need <form>, you are doing it with AJAX, right?

<div id='votes'></div>
<button onclick="vote('good');">+</button>
<button onclick="vote('bad');">-</button>

In JavaScript, it is easier to use post rather than ajax function

function vote(gb) {
  $.post("php/core/voting_system.php", { vote: gb }, function(vote_sum) {
    $("#votes").html(vote_sum);         
  });
}

In PHP, extract the vote and use it as needed (add validation/sanitation):

$vote = $_POST['vote']; // either 'good', or 'bad'
// do what you need with it
like image 160
Majid Fouladpour Avatar answered Sep 30 '22 09:09

Majid Fouladpour