Ajax + PHP Collaboration Error - php

NOTE: UPDATE - Please Read
Please Read, updated code, much better:
Also, I added an ajax error function and it doesn't call an error, the first time I do it, but the next time it happens, an error occurs, and the third and fourth times, and so on.
I have some code that doesn't seem to be working, and the problem is probably located in the Ajax request or the PHP receiving function, and I don't know what the problem could be.
Here is the important code, ask for any other code that could also be of help to you.
Jquery Ajax request
$(document).ready(function()
{
$("#secretcoin").mouseover(function()
{
$.ajax(
{
type: "POST",
url: "achievements.php",
data: { Home_Coin_Locator: "Yes" },
error: errorAlert
});
});
});
Receiving side, PHP, which takes this info and stores it in a database:
$achieve4 = $_POST["Home_Coin_Locator"];
$astrSQL = "SELECT * FROM Awards_Inv WHERE Username = '$username'";
$rs3 = mysql_query($astrSQL, $connection);
if ($achieve4 == "Yes")
{
while($row3 = mysql_fetch_array($rs3)){
$soar4 = $row3["Home_Coin_Locator"];
if ($soar4 == "Yes")
{
$soa4 = "Yes";
}
else
{
$soa4 = "No";
$awardSTRsql = "UPDATE Awards_Inv SET 'Home_Coin_Locator' = 'Yes' WHERE Username = '$username'";
mysql_query($awardSTRsql, $connection) or die(mysql_error());
$updatestatsSTRsql = "UPDATE User_Info SET `Coins` = Coins + 120, `Skill Points` = Skill Points + 10, `Awards` = Awards + 1 WHERE Username = '$username'";
mysql_query($updatestatsSTRsql, $connection) or die(mysql_error());
}
}
}
else
{
}
Ok, so my code might be weird, but just try to read it and see what the problem is.
I guess any other advice is also accepted, thanks for looking, and I hope you find something!
I added an error callback function and combined 3 mysql queries into 1, but the problem still exists.
Finally, read this code for info about the $connection and $username variables
$connection = mysql_connect("mysql1.000webhost.com", "username hidden", "password hidden") or die (mysql_error ());
mysql_select_db("a7347456_usersdb") or die(mysql_error());
session_start();
$username = $_SESSION["Username"];
Another factoid:
The error is that the info does not get updated to database, as far as I know.

first thing, make sure that you required the config file witch identify the $connection variable. and it will be easier if you describe what the problem exactly is.

Related

Implement Ajax for a PHP Function

I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.
As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).

Problems updating MySQL, "username" in a table using PHP

I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.

Testing a Database for TRUE/FALSE using AJAX/PHP/SQL

Let me begin with stating that you are about to see that I am still using some Mysql code in this question. It is only because I am new to PDO and in an effort to troubleshoot, I wanted to make sure my sql and queries were working so I went with what I know. Once I get the function working and the scripts running, I will convert to PDO.
Heres the question I have. I am submitting a form that subscribes a user to a email list (database). It takes all their info and inserts it into a DB. So far this all works. My Call back function is then supposed to check to see if this user was already in the DB or not.
I was testing to see if a row got returned from the DB based off of the email column being set as a unique column. The problem is that even though the user is already in the DB, the sql returns a line saying "Duplicate entry", so my code is reading the line DUPLICATE ENTRY as a result. Can someone point me in the right direction?
My jQuery code...
$('#contForm').submit(function() { //contForm is the name of my form
var formData = $(this).serialize();
$.post('contact.php',formData,dispAdd); //dispAdd is the callback
function dispAdd(result) {
if (!result) {
$('#main').html('<div>Your have been added to the mailing list</div>');
} else {
if ($('#fail').length==0) {
$('#main').append('<div id="fail">This email address is already subscribed to our mailing list</div>');
}
}
}
return false;
});
My PHP/SQL script
function dispAdd()
{
$email= $_POST['email'];
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
$rows = array();
if(mysql_num_rows($result) > 0)
{
while ( $row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
echo json_encode( $rows );
}
After playing around a lil more I figd out how to make it work but if anyone has other tips or ideas Im happy to hear them. I learn a lot on here so Im welcome to all comments please. Here is how I made it work:
function dispAdd()
{
$email= $_POST['email'];
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) > 0)
{
while ( $row = mysql_fetch_assoc($result)) {
}
return;
}
}

FaceBook Registration Plugin Async Validate form (to check Username availbility)

Ok, So I have Google the hell out of this problem and the FB Advanced Registration documentation also did not help. I want to have a Facebook Registration where a user can choose(& Check availability of) his username like this:
(Screenshot of what I plan to do but have failed to do, since I cant post picturesin this question directly)
A link to Screenshot of what I wanted!
I plan to check the availability of the username from my DB in mysql using PHP, but I am stuck with this weird JSON callback thing which I have failed to understand.
My Registration Plugin looks something like this
<fb:registration
fields='[{"name":"name"},{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"
redirect-uri="http://mysite.com/loginFB.php"
fb_only="false"
width="530">
</fb:registration>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
function validate_async(form, cb) {
// $.getJSON('https://graph.facebook.com/' + form.username + '?callback=?',//CODE obtained from FB documentation
$.getJSON('https://mysite.com/checkUsername.php?username=' + form.username + '?callback=?',
function(response) {
if (response.error== "false") {
// Username isn't taken, let the form submit
cb();
}
cb({username: 'That username is taken, Sorry!'});
});
}
</script>
I wanted to know WHAT EXACTLY do I write the in the checkUsername.php.
Right now I have come up with the following code for checkUsername.php which does NOT work:
<?php
$conn = dbconnect(GLOBAL_Db);
$username = $_GET['username'];
$data = array();
$table = mysql_real_escape_string(GLOBAL_Db. "." . GLOBAL_Users);
$sqlCommand = "SELECT * FROM ".$table." WHERE username='$username'";
$query = mysql_query($sqlCommand) or die (mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows>0){
$data['error'] = "true";
} else {
$data['error'] = "false";
}
echo json_encode($data);
?>
This code does not give me that that "The username is taken, Sorry" Message , WHY???
I would really appreciate it if anyone could actually help me out with this getJSON function in the script , AND Also help me out with the checkUsername.php since I have a very crude knowledge of JSON, (JSONP) etc. !
Would be glad to put in more effort to explaain my problem coz this is bugging me for like a Week now!
Happy to accept some valuable help from you guys!
$username = $_GET('username');
$_GET is not a function … maybe you should familiarize yourself with some PHP basics first?
Besides that, your script logic looks a bit weird …
if($num_rows>0){
$data['error'] = "true";
} else {
$data['username'] = $row['username'];
}
If now rows are found, then you want to access the username field in a row that’s not there?
(And you’re not even quoting the username you get as a GET parameter, OMG …)
Set error to true or false depending on if there are rows or none.
And then, in your JS function, give the „username is taken”-message if error=true.

Updating HTML Element Every Second With Content From MySQL Database

I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.

Categories