5

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>
8
  • Because you're checking for specific things in the POST array and your AJAX hasn't passed anything to the PHP, you're not getting a result. Have a look at this. Commented Aug 31, 2015 at 17:57
  • @JayBlanchard I think I even remove the if statements once. Result was the same. It updated once but not the second time. Commented Aug 31, 2015 at 17:58
  • These statements, isset($_POST['bad'] and isset($_POST['good'] will never process because you're not sending anything via AJAX to the PHP script. You have no data: property in your AJAX request. Open your browser's console to see what is going on. Commented Aug 31, 2015 at 18:01
  • It also looks like you're not starting the session in your PHP. Commented Aug 31, 2015 at 18:02
  • @JayBlanchard I actually did via include. Session(start) is the first thing I set up. I tested all of the php side of the code and it works. Commented Aug 31, 2015 at 18:05

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

11 Comments

Should I use prepared statements?
Oh and why do all tutorials do the ajax method. Will I still be able to see the updated votes every time I click on bad or good?
You certainly could, but you don't have too. Just make sure you avoid mysql_* functions and instead use mysqli_* or PDO.
Sure you could. post, get, load, and getJSON all use ajax internally, but their syntax is easier to work with.
Oh I see, later I will try to understand what is "under the hood". Is jquery faster in the long term due to less code repetition? Oh and I use mysqli functions. I will use PDO in the future for OOP.
|
2

TL;DR version:

You didn't include a data field inside your $.ajax call. Also, your script isn't checking which button was pressed.

The long version

When you're performing your $.ajax call, you fail to attach any data to the request. This can be done easily like so:

  $.ajax({
    method: 'POST',
    dataType: 'json',
    data: ...someJSONData...
  });

Usually, you're going to want to pass JSON to anything, because it can contain complex object structures that you would usually want to communicate between the client and the server. You're clearly not in this example, but if you're trying to learn this stuff, it's better to start off the right way.

Both javascript and php make using the JSON format extremely easy: JS JSON.stringify() and JSON.parse(), PHP json_encode() and json_decode().

function vote(e) {
  // e.target.id stores the id of the button that was clicked
  var data = {vote: e.target.id}

  $.ajax({
    method: 'POST',
    dataType: 'json',
    data: JSON.stringify(data),
    ... callbacks and other properties ...
  });
}

document.getElementById("good").addEventListener("click", vote);
document.getElementById("bad").addEventListener("click", vote);

This would be a simple example of how you could solve your problem. If you did a simple var_dump in your php script after running the data through json_decode() you would get a nice associative array:

[
  'data' => 'good',
]

I hope this illustrates how easy it is to pass data around in this format.

Also notice I defined the event handlers in the javascript. This is generally better, because you keep all your javascript in one place and it makes things cleaner and easier to debug.

11 Comments

I will read it through. Majid Fouladpours method is very short but yours seems very attractive as well. What do you say? I like the way you explain things
It may seem long and intimidating at first, when you're first learning about it, and this is not the simplest solution for this particular example, but it scales well when you're trying to do more complex things, which I'm sure you'll run into if you do any more webdev :)
do I need a json file in order to use your ajax method? I never worked with json files before.
No, you can convert javascript objects and arrays to a JSON string using the methods I mentioned above, then you can send that in the data field of your ajax request. Your php script can the read that string from the POST fields and decode it, and you've got a nice associative array. Vice versa works as well of course. No files needed. You can use files, but for a simple server client request there's no need for files.
I noticed you did not specify an url to the php file, is there a reason or did you leave those parts out for the sake of simplicity?
|
0

Like Jay said you're not sending POST data through the AJAX. You also need to echo your results from PHP.

function vote(event) {
     event.preventDefault();
     $.ajax({
         url: "php/core/voting_system.php",
         type: "POST",           
         dataType: 'html',
         data: 'bad='+$('input[name="bad"]').val()+'&good='+$('input[name="good"]').val(),
         success: function(data){
             var votes = $("#votes").val().empty();
             $("#votes").html(data+votes);
         }
    ]);
}

2 Comments

Could you comment your code? Especially the data part.
You have events for your ajax request like beforesend, complete, success, etc... Success accepts three parameters: data (any type), textStatus (404, 302, etc) and the jqXHR object. What i did there was just use the data parameter to append (in this case add) the result to the div with id votes. Data can be anything you want, if you need an array you need to json_encode it in your PHP function and return it to the ajax with and echo. api.jquery.com/jquery.ajax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.