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!
Related
I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.
An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});
I am having trouble getting a basic ajax POST to work. I switched to an onclick after I was having trouble getting using a jquery .click, among other things. Just wondering if I am making some blatant mistake or what. If no obvious mistake, it may be something with apache? Not too much experienced here so any help would be appreciated.
Here is a link to a function:
click this for php page
Here is the function:
function postData() {
console.log("outside ajax is working");
$.ajax({
type: "POST",
url: "/markerpages.php",
data: {
source1: "some text",
source2: "some text 2"},
success: function (data) {
console.log("inside ajax is working");
},
error: function () {
console.log("ajax post failed")
}
});
here is what I have on my php webpage:
<?php
if (isset($_POST['source1']))
$src1 = $_POST['source1'];
else $src1 = "post data not obtained";
echo $src1;
echo "<pre>" . print_r($_REQUEST, 1) . "</pre>";
print_r($_POST);
var_dump($_POST);
var_dump($_POST);die;
?>
I am not returning errors in firebug, and I am getting the log statements I placed inside ajax and outside, just not getting empty arrays on the PHP page.
Sincere thanks for any help.
You are sending the user to the page using the anchor tag. If you do this, all post data is lost. You need to replace the url in the anchor tag with # to make sure the user stays on the page:
click this for php page
First of all you should put a return false; in the js function, doing so there will not be any redirects,
Check in Developer Network your request, if the url is correct and if you are retrieving any errors during the ajax post.
When clicking the link, postData() is being called, but then the browser is loading the URL specified in your <a href>. You can do one of three possible things:
Add the following line at the top of your postData() function: event.preventDefault(). That will stop the original event clicking action, and is the preferred method.
Change your onclick attribute and add return false to prevent the URL clicking behavior. Ex: onclick="postData(); return false;
Change the <a href="/markerpages.php"> to <a href="#">. But this is not a good approach since the page's URL will change to mypage.htm#.
Another helpful debugging tip: you can output the data variable (the returned value from your PHP script) like so: console.log(data);.
And since you seem to be hand building a form which will eventually pass values from the server back to the front-end, I suggest looking at this article: Pass a PHP Array to Javascript as JSON using AJAX and json_encode()
I am working on a Computer Base Test project where user will be tested and graded on selected subject. I have a set of questions with options in the database. I want to be able to display the question in a way the user will be able to select option and navigate the questions. I am using php/mysql.
Here is my question table structure:
question(id,subject,question,optA,optB,optC,optD,answer).
My php code is:
$query = "SELECT * from {$table} WHERE subject={$subj}";
$question_set = mysql_query($query, $connection);.
I know I will need javascript to do this, Pls help me out.
You should send a ajax request to the server to get these data. You can use jquery AJAX for that.
$.ajax({
url: "question.php",
context: document.body
}).done(function(data) {
$('#question').html(data);
});
After getting the questions from the server through AJAX request. You can display the question below the option.
For more info about Jquery Ajax, Refer http://api.jquery.com/jquery.ajax/
I am using this plugin to enable me to display what I am currently listening to live on my website: https://github.com/derekmartinez18/Simple-Ajax-Spotify-Now-Playing
A piece of JavaScript will run on page load, which connects to the PHP which via API checks what I am listening to, grabs the title etc, if successful sends back to the JavaScript and displays via HTML.
I've echoed out what the PHP is getting and can see it's correctly grabbing all the recent songs, names etc. Therefore because nothing is appearing on the page maybe it's the JavaScript. I've pasted it below with pastebin link to php too.
JavaScript
<script type="text/javascript">
function get_spotify() {
$.ajax({
type: 'POST',
url: '/Scripts/last.fm.php',
data: { request: 'true' },
success: function(reply) {
$('.now-playing').html("<p>" + reply + "</p>");
}
});
}
window.onload = get_spotify;
</script>
Pastebin of PHP - http://pastebin.com/eZUH6BNU
A snippet of the API output which is being past over to the PHP (it's huge so didn't paste it all.):
{"recenttracks":{"track":[{"artist":{"#text":"LMFAO","mbid":"ed5d9086-e8cd-473a-b96c-d81ad6c98f0d"},}
Live Link - http://bit.ly/1ewTe8l
Based on the example you have given below your question, the problem is that there is no element with a class of now-playing.
Your page seems to have been cut short, perhaps due to an error, but the ajax request fires and in the console I can see the response (the url is actually echoed before that as well):
I am currently listening to 01. Circles Around The Sun by Dispatch on Spotify.
Adding a <div class="now-playing"></div> should do the trick.
Edit: Note that your key is visible in the response as you are echoing the url you are making a request to. It might be a good idea to change the key when you have solved your problem.
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.