Search posts, tags, users, and pages
There's no end of your script after returning your likes, so it's returning not only your likes, but also the entire script.
First, why are you echoing out all the likes?
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['likes'];
}
Don't you want to count them and echo a count?
Second, end your script at the end of your this if statement:
if (isset($_POST['liked']))
{
.
.
.
// Make sure you close your database stuff properly, then:
exit();
}
Third, seriously consider talking JSON in your Ajax responses. You'll be a whole lot more compatible with other stuff down the road.
Fourth, while it's very tempting to do everything in one script, you might want to consider creating an api.php that handles all your Ajax-y stuff. If you want some help with how to structure that, let me know. I can give you a template to use that might make your programming life way easier.
First,why are you echoing out all likes? Do you want to count them and make a count? Absolutely yes,according to a tutorial am following to achieve this. Thirdly,seriously consider talking JSON in your ajax responses.WHY? Am doing everything in one script because, the whole system is on the same webpage. By the way, am a junior developer,so i like to stay simple to accomplish task for now.I will glad if you help me make the script work, After the script work, then i use your suggestion to optimize the script to make things better.
Ok, a couple of things. In your ajax call, you are sending in two parameters:
data : {
'liked' : 1,
'postid' : postid
},
In your code that updates the lines, it references $_POST["likes"] and $_POST["userid"], neither of which are being passed in. I don't think you'll need "likes", but you will need "userid" if you want to attribute the like to a particular user.
Next, in the code that handles the ajax call, things look like they're happening out of order. First, you're attempting to get the number of likes for the post, but that's happening before you actually update the user_post with the like from the user pressing the Like button. Also, the while loop threw me there. I realize now that it will only iterate once. You might want to change that while to an if since it will only grab the one and only one row.
This is what I would do. Apologies for any typos, and if it doesn't work, keep in mind, I don't have this set up on my system, so it's untested. Hopefully it gets you a little closer.
if (isset($_POST['liked']))
{
$userid = isset($_POST['userid']) ? $_POST['userid'] : '';
$postid = isset($_POST['postid']) ? $_POST['postid'] : '';
// First, update the user_post with the like. I recommend simply
// incrementing it, but not sure if this works in MySQL.
// You also need to have it on the specific post, so...
$stmt = $dbh->prepare("UPDATE user_post SET likes = likes + 1 WHERE postid =:postid");
$stmt->bindParam(':postid', $postid);
$stmt->execute();
$updated = $stmt->rowCount();
if ($updated > 0) {
// Probably don't need to do anything here... if it fails, it fails. Maybe log it???
}
// Next, add the like for the user, if there is any
if ($userid != "") {
$stmt = $dbh->prepare("INSERT INTO user_likes(userid,postid) VALUES(:userid,:postid)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':postid', $postid);
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
// code...
}
}
// Finally get the current number of likes for the post
$stmt = $dbh->prepare("SELECT likes FROM user_post WHERE postid =:postid");
$stmt->bindParam(':postid',$postid);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['likes']; // This is what returns
}
// Be sure to clean up your database stuff. Don't want to leave an open connection lying around.
$stmt->close();
$dbh = null;
// Exit here so you don't continue the rest of the script
exit();
}
Right now, the the increment of the likes is not working. I checked for the format for writing the query and it's in correct order.
Ok. I had to install MySQL and get my system set up to test this. There are numerous issues.
Issue #1: the first thing you're doing is inserting a message, but when you're doing the ajax call, there is no message or comment, so you should wrap that in an if ($message != "")
Issue #2: The ajax call is setting postid to $(this).data('id'). That's fine, but the Like button with the "first" classname does not have a data-id attribute. The ajax call will never get a postid. You need to add data-id="<?php echo $data['postid']; ?>" to your button.
Issue #3, possibly: You are using this same data-id in a span above the button for a thumbs up icon, but the span is referencing $data['id']. I could be wrong, but where does "id" come from? Did you mean "postid" or "userid" instead?
Issue #4: Your posts will never display. Notice the closing } in the line below? You're looping through the posts, but nothing will ever happen due to this being a while loop that does nothing. I'm sure you didn't mean that, but it's a bug.
<?php while ($data = $test->fetch(PDO::FETCH_ASSOC)) { }?>
Issue #5: If you have your bootstrap stuff in the header.php, you need to move that and the link to main.css into your <head> section, and give it a doctype. Assuming header.php contains all the Bootstrap and jQuery stuff. Don't start your career doing badly formed HTML.
Wrong:
<link rel="stylesheet" type="text/css" href="css/main.css">
<html>
<body>
<!-- end of navbar -->
<?php include("header.php"); ?>
<!-- end of navbar -->
Right:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
<!-- end of navbar -->
<?php include("header.php"); ?>
<!-- end of navbar -->
</head>
<body>
Actually, even that's not really right. For optimization purposes, you'd want your stylesheets in the head section, and the bootstrap and jquery script stuff at the bottom, before you start your own javascript code. But, it will work at the top, too.
All this said, I created a working version of the Likes system here: pastebin.com/P26v1SQV
I didn't test anything else. Hope this is enough for you for now.
issue #3.i meant for userid. <?php while ($data = $test->fetch(PDO::FETCH_ASSOC)) { }?> i need to change that to an if statement because, it was duplicating my comment div.But this is the bad results so far,which means something is wrong. 1.page refreshes when posting which wasn't initially. 2.the number of likes keeps on increasing for any post.It cannot reset to zero for any post but keeps on increasing for any post.
i tried of using php built-in function(reset()) to reset the the likes to zero after every post but it will not work since am using an if statement and not looping through $data.What is the best way to this?
Oh, my goodness. I didn't even look at that stuff. You have so many issues with this script that it's hard to tell what's working and what's not, or even what your intention is.
The reason it's refreshing the page is likely due to some javascript error somewhere that is causing other things to fail. The reality is, your Ajax will never run. And even if it did, it doesn't do anything except send the post back, and even then, it's not right. What I will do is show you where you have issues with this part and tell you how to fix them. But there are still further issues after this. Many, in fact. This isn't meant to be insulting, but this script is really messed up. If you're doing this page as a single page application with all ajax, then you don't need form tags at all. Get rid of all of them and use event handlers.
Remove this and the closing </form> tag.
<form name="myForm" method="post" action="index.php" onsubmit="return validateForm(); return false">
Your share button should be:
<button type="button" class="btn btn-primary" id="shareBtn">SHARE</button>
The validateForm function needs to go away. Not the whole function. The guts of the function needs to stick around. The function declaration needs to go. This function only sets up an event handler on the share button, so the first time you click Share, the event handler is set up. The next time you click Share, it runs. Sort of. Don't do that. Just remove the function validateForm() { and the ending } to that function, but keep the shareBtn handler. This way, when the script first runs, the event handler will be set up on the share button, and when clicked, then it will run.
In that handler, you have issues with the ajax call. It will never run the way it is. Get rid of these two lines:
var dataString = message + category;
return false;
Change your data parameter to this:
data : {
message: message,
category: category
},
Next, look at this:
success : function($result){
if (result == "ok") {
First, result is undefined because your passed in variable is $result, not result. Change the function to function(result).
Next, you're looking for "ok". You never return "ok" anywhere. For this to work, you need to add that in. Likely here in the if ($data > 0) area, like I did below.
if ($message != "") {
$sql = $dbh->prepare("INSERT INTO user_post(message,category) VALUES(:message, :category)");
$sql->bindParam(':message', $message, PDO::PARAM_STR);
$sql->bindParam(':category', $category, PDO::PARAM_STR);
$sql->execute();
$data = $sql->rowCount();
if($data > 0){
echo "ok";
exit();
}
}
Once this is all working, I'm not even sure what you're trying to do once the message gets posted. You seem to be setting up a focus and blur on the .textarea1 class, but, why? The rest of it does nothing. I'm not even sure why you're iterating through all the .textarea1 classes when you only have one of them. I'm not sure what your intention is here.
BIG NOTE HERE:
Your post never passes in a userid, either, so any posts that make it won't have one, which means your likes system won't work. Just making that observation. This could throw off your likes. I've fixed this by hard-coding a userid at the top of your script and making sure it's set in the message posting and passed in.
Your code has many other problems. I can't fix them all for you. I'm not even sure of your intent with some of this. But, as an overview:
Your comments aren't associated with a post, so it will display ALL comments for each post. I fixed that in the pastebin. Actually, I fixed numerous things. I spent a bunch of time on this this morning. The commenting system was not working. Now it is.
When you post, it does nothing but send the data back. The rest of that code seems pointless. If you want to clear the post and the likes and the comment area, then you should just do this (I added this to the code in the pastebin):
$('.textarea1,.textarea2').val('');
$('.likes_count').text('0 likes');
On my machine, the posts work. The comments work for each post. Likes also work for each post. There's stuff in here you'll want to change, I'm sure. This is probably as far as I can take you. Study the code. Look at my notes in it. Comments that begin with JOE are for you to take special note of. You can and should remove those comments.
I've fixed ALL of the above in the pastebin. pastebin.com/s9jpvie5
Study it. Understand why it's doing what it's doing. Understand HTML id attributes and what they're used for and why I had to make some unique the way I did.
Hope this works better for you. I can't spend any more time on this, so I'm really hoping this jumpstarts you a little.
Not to doubt you,everything was working fine before adding the like system.But when i added the like system script to it, the codes messed up and so for the application.By the way, you are using the concept of SPA(single page application) now here.I will look into that later. The messed up of the application is from the like system since everything was working perfectly before adding it.As a result, it there is any nail to hit, in my opinion it should be the like system.I have not made your last changes but want your opinion about this before making the changes.
Maybe it was before the Likes. I have no idea. But after the Likes, it wasn't working well at all. Most of what I found was due to the lack of associating comments with a specific post and the lack of associating Likes with a specific user.
As you said, the page refreshed. The reason for that is because of some javascript error, but because the Share button was in an input type="submit", whatever cause the javascript error still allows that to continue, so the page refreshed. Look at your validateForm function. Can you see what's wrong here? I'm going to point it out:
//AJAX FORM SUBMISSION
var dataString = message + category;
return false; // JOE: This returns BEFORE the ajax call, so the ajax call never happens
$.ajax({
type: "POST",
url : "index.php",
data : dataString, // JOE: this just passes in a concatenated message and category... no real parameter
success : function($result){ // JOE parameter is $result, but...
if (result == "ok") { // <-- this is evaluating result, not $result
// It's also looking for "ok" to be returned, but it never is
I could go on and on. I fixed a whole lot. This is just a tiny portion of what was going on that had nothing to do with the Likes system.
BTW, SPA (single-page application) is when you use all ajax calls to communicate with the server without doing a page refresh. You were doing that anyway, but you were intermingling form submits, too, which in the case of posting the Share didn't make sense since you were trying to do both at the same time. SPAs eliminate the form submits and uses just ajax. That's all that is. It's not anything special. You were already attempting to do it here. In the latest code I sent in the pastebin, since you were already doing the ajax calls, or at least attempting to, I eliminated the form submits and had the click events of those buttons handle the ajax calls the way it seemed you were attempting to do.
You're not under any obligation to use the code I sent in the latest pastebin. You can go back to your original code and try to work out the Likes and hope everything else is good to go. I can tell you it's not, but you don't have to believe me.
Hello,nothing is absolutely working at my end here after making the changes.I wonder why the codes are working at your end.
Are you using my code, or did you try fixing your original code? In either case, you can start putting echo statements in various places to see how far the code executes. Something like:
echo "trace1<br/>";
.
. then a bit further down
.
echo "trace2<br/>";
You can also display the contents of arrays and objects like this:
echo "<pre>\n";
echo print_r($yourarray, true);
echo "</pre>\n";
Obviously, $yourarray is whatever array or object variable you have. For example, near the top of your script, you can echo out the contents of $_POST to see what you actually are sending back in.
If it were me, I'd probably start logging to a file, or use a PHP debugger, but I think that would complicate things too much for you right now. Just remember to remove any extra echo lines after you're done debugging.
In your javascript, you can use console.log() or alert() to see your javascript variables, too. You can use the browser debugger to view the Console if you're using console.log(). And if you haven't used the debugger prior to now, it would be a good time to do so. You can set breakpoints in your javascript code and run the code line by line and evaluate the values of variables. I also recommend, if you're using Chrome, to add on the JavaScript Errors Notifier extension (chrome.google.com/webstore/detail/javascript-erro…). I've used this for years. It puts a red exclamation point right on the page to indicate if you have an error, so you can see right away what might be breaking things. You could have one tiny error and your whole page would break. Very, very handy,
One other thing, if you are using my latest code, go down to where your javascript code starts and remove the reference to jquery there. I left it in the code accidentally. I don't have your header.php, so I put a jquery and bootstrap reference in there. I thought I removed those lines, but looks like I missed the jquery line. You might have two references to jquery, one from your header.php and one from this line. That doesn't appear to affect things adversely, but get rid of that line anyway, if you're using my latest code.
It also skipped me.Have done that,but still the same.Absolutely zero percent working.i wish i could show you a screenshot of the interface. The comment div is being duplicated as a result of this line of code. <?php while ($data = $test->fetch(PDO::FETCH_ASSOC)) { ?> if you change the line to an "if" statement, the duplicate stops but am also thinking of how to proceed with the conditional statement.
So, $test is the results of user_post. The way it should work, it seems, is that the comment div should duplicate for as many comments as there are for the post. Then the next post, with its comments, and so on. Like so:
POST
Comment div
Comment div
POST
Comment div
POST
Comment div
Comment div
Comment div
You get the picture. The problem you had in your code initially was that the SQL to get the comments would get ALL the comments without regard to which post it was associated with, then loop through those, and only display the earliest comment. If you're still using your original code with this, look at what it's doing:
<?php
global $post_comment; // <-- this isn't necessary
global $time; // <-- this isn't necessary
$sql = $dbh->prepare("SELECT * FROM comments ORDER BY post_time DESC");
$sql->execute();
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$post_comment = $row['comment'];
$time = $row['post_time'];
} // <-- notice that you're closing your while loop here.
?>
<div id="single-comment">
<p><?php echo $post_comment;?></p>
<p><?php echo $time; ?></p>
</div>
The SQL is selecting all the comments, and sorting them by post_time in descending order. However, the next while loop is closed before you ever display a comment. That means only the very earliest comment will display since you're saving the comment to $post_comment and $time. Because of this, that same comment will display for every single post. That's why it's duplicating.
What you really want is a change in the SQL and a change in the while loop to close after the "single-comment" div. This is what I changed it to in my code, so as to produce the comments that belong to the post in reverse chronological order.
<?php
$sql = $dbh->prepare("SELECT * FROM comments WHERE postid =:postid ORDER BY post_time DESC");
$sql->bindParam("postid", $data["postid"]);
$sql->execute();
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$post_comment = $row['comment'];
$time = $row['post_time'];
?>
<div class="single-comment">
<p><?php echo $post_comment;?></p>
<p><?php echo $time; ?></p>
</div>
<?php } // end comment loop ?>
If this doesn't resolve it, you can post a screenshot using tinypic.com and send me the link to it. Also, if you want to post your most recent code in a new pastebin and send me the link, I'll take a look at it. But before you do that, see if the above helps you at all.
The above did not help with my original code.You even solved that problem in your code, so thinking it will work but did not. Promise,i will get back to you for continuation.
Check your data, too. You may have duplicate comment records with the same comment for the same post. If you're using my code, you may want to clear your tables and start over. The issue might not be with the code, but with the data. Worth looking at, I suppose.
Am using my original code with little modification you showed me. I normally check my data as am developing.I dont even know what to again,but there is always a way. Even i wonder with all the changes i implemented from the changes you showed me ,yet still the page still refreshes.
In your original code, you have:
<button type="submit" name="submit" class="btn btn-primary" id="shareBtn">SHARE</button>
This should be an input tag, not a button tag. Button tags don't get type="submit" and neither really needs the name="submit", either.
<input type="submit" class="btn btn-primary" id="shareBtn" value="SHARE"/>
Now, here's what's happening. Your form has an onsubmit event. That calls validateForm.
onsubmit="return validateForm(); return false"
Notice, it's returning whatever validateForm() returns. The "return false" will never run because it's returning before that. It should just be:
onsubmit="return validateForm();"
So, let's look at validateForm().
function validateForm(){
$('#shareBtn').on('click',function(e){
Your validateForm function only sets up an event handler for shareBtn. It doesn't actually DO anything. Just sets up the event handler. Look at the bottom of the validateForm function.
} //end of else statement
return true;
})
}
Notice the "return true"? That's inside the shareBtn click handler. The }) is the end of the handler. There is no return statement for the function. When there's no return at all, an onsubmit will proceed with the submit, thus refreshing the page. If you add a return false right before that last curly brace, you will stop the page refresh from happening. However, the Share button will seem to do nothing on the first click because the first click only sets up the shareBtn click handler. Prior to that, there is no shareBtn click handler, so nothing else happens. Only on the second click of Share will it actually run the ajax in the shareBtn click handler.
If it were me, I would keep the shareBtn click handler, but get rid of validateForm. OR, I would get rid of setting up the shareBtn click handler and keep validateForm, essentially making validateForm the click handler. You're trying to do both a click handler and an onsubmit function all in one pass and that won't work.
In my code, I got rid of validateForm in favor of the shareBtn click handler. However let's try the other way as it may be simpler. Let's try getting rid of the shareBtn click handler, in favor of keeping validateForm. Inside validateForm, get rid of these lines at the top of the function:
$('#shareBtn').on('click',function(e){
// default action of the event will not be triggered
e.preventDefault();
And at the bottom of validateForm,
} //end of else statement
return true; // <-- change to return false;
}) // <-- remove this
}
Your validateForm function should look like this in its entirety:
function validateForm(){
var message = document.myForm.message.value;
var category = document.myForm.category.value;
if (message == "") {
alert("field required");
return false;
}else if (category == "Gender") {
alert("Please select category");
return false;
}else {
//AJAX FORM SUBMISSION
var dataString = message + category;
return false;
$.ajax({
type: "POST",
url : "index.php",
data : {
'message':message,
'category':category
},
success : function(result){
if (result == "ok") {
$('.textarea1').each(function(){
var default_value = this.value;
$(this).focus(function(){
if (this.value == default_value) {
this.value = '';
}
});
$(this).blur(function(){
if(this.value == ''){
this.value = default_value;
}
});
})
}
},
error:function(xhr,desc,err){
console.log(xhr);
console.log("Details: "+ desc + "\nError:" + err);
}
}); //end of ajax request
} //end of else statement
return false;
}
Your post will still not work 100%, but you'll be closer. After this, you'll have to address the ajax call itself. It actually returns false before the call runs. (See two lines after the AJAX FORM SUBMISSION comment.) Once you fix that, you'll have to look at where it's evaluating result to check for "ok". Nothing in the entire script echos out "ok", so you have to deal with that.
my validate function so far. pastebin.com/fNhpv09u What is still wrong.I truely know this is supposed to work but it's not. Have a look at the duplicate i was talking about.It seems you did not get that statement well.Below is the link. [IMG]i65.tinypic.com/106egbk.png[/IMG]
So far, so good. I plugged your validate function, and it seems to be running fine for me. That is, it's getting to the success function and displaying what you have in the console.log() statements. Do you get "success" and result value in the Console in your browser debugger? Hopefully, you do. If so, then your posting is working. If you do not, paste your entire script as it is right now to a new pastebin so I can take a look.
The next issue there is that in the success function from the ajax call to post the share, it doesn't really do anything. All it's doing is setting up a focus event handler and a blur event handler for each .textarea1 class. What do you want it to do?
As for the duplicate likes and comments, can you tell me if "king of the world" is coming from user_post or comments?
In your original, you had this:
<?php while ($data = $test->fetch(PDO::FETCH_ASSOC)) { }?>
Notice that there is an ending curly brace, which meant that this while loop did nothing and therefore, the Likes and Comments button only displayed once since it wasn't included in this loop. So, it depends on how you've fixed this and where you put the ending curly brace.
Maybe I've misunderstood what you want to happen here, but it seems to me, you'd want to have a post, followed by the Likes and Comments button, followed by each comment associated with the post, then have the next post, with its own Likes and Comments button, followed by comments associated with that post, and so on, through all the posts. After all, the $test variable contains the results of your SQL statement, "SELECT * FROM user_post". And the "while ($data..." implies you want to loop through all of those.
If this is not what you want to happen, then please explain to me what you want to happen. I can advise better once I know what you're wanting.
I can see the "success" in my console. This is what i want to achieve in the success function. i want the user post(#exampleTeaxtarea) to appear in this div(#receivingPost). king of programming is not found in my database currently.As a result, i cannot give vivid answer. For where to place the end of the curly braces, i will just have to keep on trying.It will work one day for me. Please below is the flow of logic for my application. First, the user makes a post in the #exampleTextarea div.The post the leaved the div and must appear in the #receivingPost div. When the #comment-section is clicked,the #comment-two div appears.Here is where user's will input their comment. When user's input their comment,the comment must appear in the #single-comment div. So if you get the scene well, you will noticed that the current post and it's comment will appear in the frontpage of the application and the post likes,not all post,comments and likes. Truly, i will like to know you can do screen sharing with me.I helps speed development faster that commenting ,stand to be corrected. Just to make the scene more clear. When another makes a post, the first one will have to be saved in the database and leaves the div automatically.When the comment button is clicked, a new comment area appears for the user and the comment is being displayed in a div.
Hello, i have not heard from you so far.What is going on?
Oh, hey. Hashnode never notified me of your reply. I just went back to check my previous notifications and there nothing for this one. Sorry!
Screen sharing will be difficult. We seem to be on opposite sides of the planet, so you're awake while I'm sleeping and vice-versa.
Have you made any progress on this? I would have hoped so by now.
First, you said you get "success" in the console. Great! That's only part of the battle. You really do have a large number of problems that are hindering you. I was hoping you would be able to go through this logically to figure out where your issues were. Such as, where does the userid come into play since it's not set anywhere? Or how are you associating comments to posts? (Hint, you're not). And, what do you display when you first come into the page? (Hint, it's probably not what you are expecting).
This would be an extremely long and confusing post if I have to explain everything. So, instead, I made a new pastebin with some of the fixes based on your description of what's supposed to happen.
I left some things for you to fix. For example, when first coming into the page, only the earliest comment will display, and possibly not even related to the post. Why? Hint: check your database code in the #display-comment div, and how the while loop is working. Also, likes will count for posts, but who actually clicked Like? Hint: your ajax call does not pass back the userid.
Grab the code from the pastebin, and do a diff from this to your current code. If you need a utility for that, I recommend WinMerge. winmerge.org
Fix one:earliest comment to display related to a specific post. In the pastebin you provide recently, you are using an "if" statement instead of the while loop.I have manged to show earliest comment related to a specific post but it's not the best.I will have more time to fix that. This is just by the way.I want the application to go live now as am loosing motivation for it.I struggle a lot to get things done and sometimes help from other developers.Dont mine me too much here,part of the journey. Currently, am on the like system and am facing the problem i first made,that's the display of html codes when the "like" button is clicked. This is a gist of the code currently. pastebin.com/fNhpv09u
Yes, I used an "if" instead of "while" for the posts since you said you only wanted the most recent post. No need to loop for just one post.
Ah, yes, the HTML code that comes back. Paste your code again. I fixed that in the version I pasted, but I don't remember what that was. I'll find it for you if you haven't found it already.
Also, I did change the Like system a bit in the version I pasted so the Likes are associated to the post being displayed. The added "data-id" attribute on the Like button has something to do with that.
Man, i need your help authentication system This is the problem am facing now.There is a successful message or the registration but data does not insert. Secondly, there is a success message for the login but there is no redirection.What is wrong please?Here is a link to my code.. pastebin.com/b0DPUp0b
Am able to register user now but not able to login.Getting an error of "an error ocuured" when i tried logging in. pastebin updated.
Hey... sorry, I've been out of town and haven't checked Hashnode since last week.
$hashed_password = password_hash($password,PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO signup(username,email,password) VALUES(?,?,?)");
$stmt->execute([$username,$email,$password]);
Not sure if you found this already, or if this is it, but you are passing in $password instead of $hashed_password in the execute statement, so the hashed password is not being stored in the database, but probably the clear text password is instead. You probably want:
$stmt->execute([$username,$email,$hashed_password]);
I have have been able to upload my site on a live server.Check it out. startupfailure.000webhostapp.com Free hosting for now bcos am on low budget for now.Currently, u gave me some suggestion and i want to act upon it now. 1.First, i should take JSON in my ajax response.For this, i just need to search and i will get online resource for that. 2.Secondly, creating an api.php to handle all my ajax request.I will be glad if you can give me the template for the structuring.
Sorry for my delayed reply. I'm taking care of a terminally ill parent and things are nearing the end, so my time is limited. I'll put together a sample for you of a simple way of doing an API. It won't include any authentication scheme. There's plenty of resources out there for you to figure that part out. But I'll stub it out in the code so you can fill it in with whatever you want. Give me a day or two to get something together for you.
Grab the sample api.php from here: pastebin.com/hacvyzUr
The file is a fairly simple HTML POST implementation, and does not include any sort of authentication. I'll leave that to you. This is not RESTful. That's a whole other sort of implementation. This is just normal $_POST processing, but returning JSON instead of plain text. You could, of course, use this to return plain text, if you wanted.
It includes a few helper functions: ajaxResponse() - creates a JSON response for returning results ajaxError() - creates a JSON response for returning error messages ajaxSuccess() - creates a JSON response with just "ok" as the result
The processing starts at the very bottom of the file as I like to define functions at the top. The first thing it does is call evalCommand(). That's where all the main processing happens. The evalCommand() function will get the "cmd" $_POST variable to see which command to process. Follow the flow to see how that works. I usually put each command's process into a separate function, or in a larger system, even other objects. But keeping it simple here, just separate functions.
To call it, you'd do an ajax call similar to what you're already doing. You'll need to make sure you set a dataType parameter to 'json', though, so that the browser knows the returned data is in JSON format. The data parameter will have at least one element called "cmd", with the name of the command. You can call the command whatever you'd like, but it has to match one of the ones you're looking for in the evalCommand() function in api.php.
Here's an example of what a call might look like to "like" a post. Notice, the dataType is "json", and data has three parameters, "cmd", "postid" and "userid". The cmd is set to "like-post". The postid is set to whatever the id of the post is, and the userid is set to the id of the user liking the post. In api.php, there is a stub function with pseudocode that is there for you to fill out to update the number of likes for a post.
var postid = 1; // you would have to get this from somewhere
var userid = 1; // you would have to get this from somewhere
$.ajax({
url: 'api.php',
type: 'POST',
dataType: 'json',
cache: false,
data: {
cmd: 'like-post',
postid: postid,
userid: userid
},
success: function(response) {
if (response.error) {
console.log(response.error);
return;
}
$('#likes-count').text(response.response+ ' likes');
}
});
Hope this helps, and hope it makes some sense to you. It might take you some time to get it working the way you want.
Piece of advice: if your ajax call doesn't return anything, change dataType to 'html', then put console.log(response) as the first thing in the success function and look at the developer console in the browser to see if there are any PHP error messages. If so, take care of them. When those messages go away and you get the result in the console, then switch the dataType back to 'json' and remove that console.log line.