user2728875 user2728875 - 1 year ago 43
HTML Question

AJAX get data from sql by php and then display data value onto html element

HTML

<input id="box1" type="submit">

$('#box1').click( function() {
$.ajax({
url:"insert.php",
type:"POST",
});
});


PHP insert.php

$link = mysqli_connect("localhost", "root", "", "votingcount");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// attempt update query execution
$sql = "UPDATE vote_result SET vote_count = vote_count + 1 WHERE photo_no=1";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


When the submit button (#box1) is clicked, the UPDATE statement would increase the vote count in SQL by 1. After running the insert.php, at the same time a overlay would appear to show the CURRENT vote count from the SQL, I would want the overlay box content to display the int vote count with the following sql statement : $sql = "SELECT
vote_count
FROM
vote_result
WHERE
photo_no
=1";

How would I allow the .click function for #box1 be able to run another php where I could retrieve the value and update the #clicked value in the following overlay?

<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<img src="tyedit.jpg" height="1024" width="724" />
<div id="imagine">
<span id="clicked">0</span><br/>
<span id="word">VOTES</span>
</div>
</div>

</div>

Answer Source

Why don't you run your select query after the insert query in insert.php itself. After successful update query, just run another query to select the vote count from your table.

$sql = "SELECT vote_count FROM vote_result WHERE photo_no=1";

if($result = mysqli_query($link, $sql)){
    echo mysqli_fetch_assoc($result)['vote_count'];
} 

The echoed statements are you ajax response, so use callback function on success to update your overlay.

on your ajax call

$.ajax({
   url:"insert.php",
   type:"POST",
   success:function(response){
       $("#clicked").html(response);
   }
});

also if you wish to have multiple echoes on your insert.php file you could get a json response using json_encode() to all your echoes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download