Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.
Related
I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.
so basically i want to make a webpage to detect how many times user clicked on it and send that value to database. I know i should use ajax but just can't figure out how to use it.
var count = 0;
$("body").click(function() {
$("#track").text("you clicked " + count + " times");
count++;
});
$.ajax({
url: "index.html",
cache: false,
success: function(html){
$("#results").append(count);
}
});
Assuming the following things. You:
have AMP Stack installed with PHP & MySQL.
have a working DataBase in MySQL (most commonly used with PHP).
are running the web server and looking at HTTP version and not file version in Chrome.
I would go by this method:
On load, I'll get the current count from DataBase using a PHP backend.
In the PHP backend, I'll write a code to query MySQL and get the current value.
Use a single file, say count.php as a file to get and set the counts.
Using GET method, the file responds with the count.
Use an AJAX code and get the count data.
Using jQuery with the AJAX's response, update the DOM with the current count.
Once you load the page and update the value, set the event listener on click.
Update the current count in the UI by adding one more.
Use the same code as you have to update the UI to increment the count.
Fire a POST request using AJAX to the count.php and send the new value.
In the count.php, write an UPDATE query to update the count.
Send a success message.
When you reload the page or look at the database, the count will be preserved.
This question already has answers here:
Fire Greasemonkey script on AJAX request
(2 answers)
Closed 3 years ago.
I'm using greasemonkey with Firefox to alter what content is displayed when I visit a particular domain. One of the pages contains a dropdown with two elements, let's call them element0 and element1. Whenever it detects a switch from one to the other, it performs an ajax query that alters the page content depending on which one you've selected. So it looks something like this:
$(".dropdown").change(function(){
if($(this).val()=='element0'){
$.ajax({
// fetch some html
});
}
else{
$.ajax({
// fetch some other html entirely
});
I'm happy with what is displayed when element0 is selected - it's element1's associated content I want to alter. So I need a way to trigger my own userscript function only in the second case. I also somehow need it to execute only after the ajax query is complete of course. How do I do this?
I have some basic experience with programming, but know absolutely nothing about jquery, ajax, json etc etc. A friend helped me locate the above ajax for that page so that I could even post a meaningful question. Please bear my level of experience in mind, because I'd really really like to move forward with whatever knowledge/wisdom you guys can offer, but will only be able to do so if I understand it.
Many thanks!
EDIT: The above is javascript that the host is running. I accessed it by saving the page and looking around manually. I am writing userscripts on the client side to alter what my browser displays. So I want to write my own function that responds to their js in the way I described.
AJAX
In ajax you have a tow useful method,
success & compleate
success: with execute if ajax request are work truth
complete: are work when finished ajax function, so you can use this method
example:
complete: function(){
// call another ajax, hide somthing, do any somthing
},
another example:
var all_data = {'user':txtuser,'pass':txtpass};
$.ajax ({
url:"ajax.php",
type:"post",
data:all_data,
beforeSend:function(){
// do somting before send a data
},
statusCode:{
404:function(){
$("#ma").html("Page not found");
},
401:function(){
$("#ma").html(".....");
}
},
success:function (data) {
$("#ma").html(data);// if sucsess
},
complete:function(){ // when complete
$("#user").hide(2000);
$("#pass").hide(2000);
$(".q").hide(2000);
}
});
I am working on a social networking site where user Posts are displayed on the home page. They can be liked and commented on. If a post is liked,
it updates the like table through AJAX and have like count incremented by one.
AJAX code:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var $this=$(this);
var post_id = $(this).val();
var user_id = $(".user_id").text();
alert('Post: '+post_id +' User: '+user_id);
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { post : post_id , user : user_id },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.likecount').html( msg );
});
});
In the home.php page I have some PHP variables ($userID, $userName) that are data fetched from MySQL and they all work fine but they
don't work with the variables ($viewedUserID, $viewedUserName) in the user.php. In the user.php, only posts related to profile been
viewed are fetched but when you press the like button and try to comment on any of the post it says undefine variables; $viewedUserID, $viewedUserName. And these
variables are defined from the beginning of the page in user.php.
I have been thinking of what might be the possible cause of this and was also thinking the AJAX was suppossed to have effect on the clicked
button only.
NOTE: The alert works just fine.
Thanks in advance.
Was going to write as a comment, but I guess an answer will be clearer:
Ajax
How does AJAX work?
I think you're getting confused with what Ajax's job is. The problem is Ajax is literally just a connector between your front-end (JS / HTML) and back-end (PHP / Rails etc)
Your statements that "Ajax isn't updating MYSQL" lead me to believe you're relying on Ajax to update your table. It won't
Your table will update by using PHP, which is why most of the comments are focused on the PHP & not the JS
PHP
Your Ajax needs to send the correct data to PHP, but then it's your server-side scripts' job to sort it all out, sending a worthy response
Your JS looks like it will work well, but I think your problem will be with your backend. If you update your question with your PHP you'll get a lot more clearer answers!
So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.
The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......
Main PHP Page:
$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
var selr= null;
if(rowid != null){
selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
$.ajax({ // I believe I need to use AJAX so here is my attempt
type: "POST",
url: "getId.php", //This is another PHP page for the reuslt. See below
dataType: "json",
data: {selr:selr},
success: function(data) {
alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
}
});
}
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call
getId.php
<?php
$rId = $_POST["selr"];
echo $rId;
?>
Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?
Thank you, I love you all.
By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.
It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.
Example of how you can send that data to another PHP page
//Your existing jQuery
success: function(data) {
// alert (data);
var result=data;
$.ajax({
type: "POST",
url: "anotherpage.php",
data: { data: result }
});
}