Вопрос

I have a jquery/php voting system I'm working on. Once a user clicks a vote button a jquery modal pops open and they must confirm their vote by clicking "Confirm". This will send an ajax request to update the database and what not. After clicking confirm the modal will close. I would like to be able to update the number of votes dynamically on the page. I can easily grab that data from the mySQL table. My question is how does this get sent back for me to then update the html page dynamically?

Currently the page does nothing, so to the user it doesn't look like they've voted. Ideally I'd want to update the total number of votes and also inject an image that shows what they voted for.

function vote(el, id) {
    $.ajax({
        type: 'POST',
        url: '/path/morepath/',

        dataType: 'json',
        data: {
            'action': 'castVote',
            'vote': id
        },
        success: function (data) {}
    });
    $.modal.close();
}
Это было полезно?

Решение

On the server side, respond to the POST request with a JSON object containing the number of votes and possibly the image path.

Then inside the AJAX callback, data will be that object. Then you can use jQuery to select an element in the DOM and call .text() or .html() on it to update the content.

Другие советы

If you're passing poorly formed data back from PHP, you can make it a bit better by giving it some structure and then making it json for javascript's ease-of-use:

$sqlResult = ...;
$responseArray = array();
$responseArray['result'] = true; //or false if it failed
$responseArray['data'] = $sqlResult;
print json_encode($responseArray);

Before you can really expect the page to respond properly to an ajax response, you must be sure your response data is being parsed correctly.

Inside of your success function, try console.log'ing your response to see what it looks like

console.log(data);

if there is something you can reference in the return data that is reliable, do a check for it:

success: function(data) {
  if(data.result == 'true') {
    $('someElement.someClass').someFunction();
  }
}

You can change the value or html content of the voting number using a few different options such as:

...
        success: function(data)
        {
            var $newTotal = ...//get total from data
            $('voteCountContainer').html($newTotal); // or you can also use .val() if it's an input
        }    
...

Hope that helped,

Dan

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top