I am a bloody beginner, I apologize if my mistake was too stupid.
So far I cannot get my 'taskone' entry updated. After the click on the button it should be '1' in the row for the current user.
my function
function loadDoc( user) {
console.log('aaa');
$.ajax({
url: "upper.php",
type: "POST",
data: {
'wp_users': user, 'taskeins': '1'
},
success: function(data){
alert(data);
}
});
}
my upper.php
$con=mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$current_user = get_current_user_id();
$Username = $_POST['wp_users'];
$taskeins = $_POST['taskeins'];
$sql = "UPDATE 'wp_users' SET 'taskeins' = 1 WHERE 'id' = '$current_user'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
Basically the function should detect if the user has select the task. If so, 'taskeins' should get the indicator one so that it will be presented in the profile of the user.
The function gets called but that:
(function(event){loadDoc()
})
is my console output.
And I get a POST 500 error...
What I said - I am a total beginner. But maybe someone can help me.
As #MagnusEriksson pointed out, In MySQL, with regards to column names only, you use backticks and not quotes to escape sql reserved keywords otherwise you can leave them out.
Change your query to this:
$sql = "UPDATE `wp_users` SET `taskeins` = 1 WHERE `id` = '$current_user'";
Also you need to start using prepared statements as you are using an api (mysqli) that supports it
I used this, answered.
enter code herefunction loadDoc( user) {
console.log('aaa');
$.ajax({
url: "upper.php",
method: "POST",
data: {
'wp_users': user, 'taskeins': '1'
},
success: function(data){
alert(data);
}
});
}
Related
I'm running a script which is supposed to send a user ID number to a database. The database grabs a bunch of image IDs from whichever row has the matching user ID, then goes to a different table and grabs the image URLs which match the image IDs. Then it returns the URLs.
The PHP script runs fine on its own, it returns the correct URL in either straight text or JSON, as requested.
As for the jQuery, the AJAX call does indeed get to the success function, because I can ask it to document.write something there and it will do it. When I ask it to print out the data, however, the AJAX call runs forever (I think it is repeatedly calling the success function? Based on the browser telling me that it is either waiting or transferring data repeatedly). Regardless, nothing is printed to the screen despite the repeating script.
Oh, also, no errors are returned to the console.
I am not sure why it is doing this and so here I am. I've browsed through the other posts here and randomly on the internet, with no luck. Any help is appreciated!
Here is the PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
// define variables and set to empty values
$servername = "localhost";
$username = "root";
$password = "Wolf*6262";
$dbname = "Game";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET["id"];
}
$query1 = mysqli_query($conn, "SELECT imageids FROM users WHERE id = $id");
// Start user session
if ($imageIds = mysqli_fetch_array($query1)) {
fetchUrls($imageIds, $conn);
} else {
echo "Fail";
}
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = '1'");
$array = mysqli_fetch_assoc($query2);
$url = $array["url"];
exit($url);
}
$conn->close();
The jQuery:
function getUrls (userId) {
$.ajax({
type: 'GET',
data: {id:userId},
URL: 'fetchChar.php',
async: false,
dataType: 'text',
success: function (data) {
document.write(data);
document.write(userId);
}
});
}
Aaand here's where I define userId and call getUrls, it's in a separate HTML file:
var userId = <?php echo $_SESSION["id"]; ?>;
$(document).ready(getUrls(userId));
Can you please modify your script: as standard way what prefer from jQuery:
1. Change URL to url
2. Please avoid async defining
Like this
$.ajax({
type: 'GET',
data:{ id: userId },
url: 'fetchChar.php',
// async: false,
dataType: 'text',
success: function (data) {
console.log(data);
//document.write(data);
//document.write(userId);
}
});
I added console log to show the return data, so that you can make sure that your data is returning correctly from fetchChar.php file using console log.
Ended up doing the following, question solved:
Javascript file:
$.ajax({
type: "POST",
dataType: "json",
url: "fetchChar.php",
data: {id:userId},
success: function(data) {
document.write(JSON.stringify(data));
}
});
PHP file, near the end:
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = 1");
$array = mysqli_fetch_assoc($query2);
$url = $array['url'];
$url = json_encode($url);
echo $url;
exit();
}
I am trying to pass some values to a mysql table but I do something wrong. I call this function from somewhere:
function updatebets(postid, bet, betamount){
alert(postid + " " + bet + " " + betamount);
$.ajax({
type: 'POST',
url: 'current.php',
data: {bankpostid: postid, bankbet: bet, bankbetamount: betamount},
success: function(){
alert('works');
},
error: function(){
alert('something went wrong');
}
});
}
This is the current.php page:
<?php
global $current_user, $wpdb;
$uid = $current_user->ID;
$postid = $_POST['bankpostid'];
$bet = $_POST['bankbet'];
$betamount = $_POST['bankbetamount'];
$sql = "INSERT INTO bets (postid, uid, bet, betamount) VALUES ('$postid', '$uid', '$bet' , '$betamount')";
$wpdb->query($sql);
?>
The fields "postid, uid, bet, betamount" are the name fields of the table I want to update. I get the error 'something went wrong'. I am working with wordpress, the page current.php is in the theme folder.
I know, you need update data in your database but you run SQL INSERT DATA.
If you want Update data in your database you must use SQL UPDATE.
Here is the example
$sql = "UPDATE bets SET postid='$postid', uid='$uid', bet='$bet' , betamount='$betamount' WHERE betsprimary='$betsprimary'
The betsprimary='$betsprimary' syntax you can replace with primary key coloumn and the value in your table.
Why is PHP adding a line break to my simple AJAX result? This couldn't be much easier. Am I missing something?
Here is my JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
alert(data);
if(data === "exists"){
alert(data);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is my php:
<?php
include_once("db_connect.php");
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
if($rowCnt == 0){
echo trim('new');
}else{
echo trim('exists');
}
For whatever reason, my result data string is returned as /r/nexists, rather than just exists, and thus never gets into my if block, even if I only use == to evaluate the condition. I tried adding the trim() function as you can see without result. Your help is much appreciated as this has taken me hours of time for a stupid if condition.
Check if there is an "empty" space after or before the php question marks, those line-breaks are also represented as part of the response.
I mean here
<?php?>
And here
I found a solution but I still do not like or understand what is happening. You should be able to return a simple string for a result. Anyway, what I did was to just echo the number of rows returned from the DB to my ajax success function. I then checked if the result was > 0 on the client and am finally in my IF block. Here is what I did:
JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
console.log(data);
if(data > 0){
console.log("HURRAY! I'm in my IF");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is the PHP:
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
echo $rowCnt;
?>
This works, and is actually maybe alittle more elegant, but you should be able to return a string without issue.
John
My ajax code from javascript
function makeRequest(button) {
alert(button.value);
var no =button.value;
$.ajax({
url: "findques.php",
type: 'POST',
dataType:"json",
data: {id:no},
success: function(response) {
$.each(response, function(idx, res){
alert(res.question);
});
},
error:function(err){
console.log(err);
}
});
}
My php code to retrive data is as follows
<?php
$connect =mysql_connect('localhost', 'root', 'password');
mysql_select_db('test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
if(isset($_POST['id']))
{
$var = mysql_real_escape_string(htmlentities($_POST['id']));
error_log($var);
}
$data = "SELECT * FROM `questions` WHERE no=$var";
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
else{
echo "error";
}
$connect->close();
?>
Im trying to retrive data from Mysql database from ajax through php but it shows me "error.jquery.min.js:6 GET 500 (Internal Server Error)"
Is that a problem with my ajax part or PHP part?? Im using Ubuntu 14.04 with apache 2 server.Some suggest there is a problem with server permissions??
You're using type: 'GET', and in PHP you're using $_POST['id'].
Change type to type: 'POST',
Your problem is invalid php code.
It appears you are using some strange mix of different examples on the server side:
$connect =mysql_connect('localhost', 'root', 'password');
This line returns a handle (a numeric value), and not an object which is what you try to use later on:
if($connect->connect_error)
This leads to an internal error.
To debug things like this you should start monitoring the error log file of your http server. That is where such errors are logged in detail. Without looking into these log files you are searching in the dark. That does not make sense. Look where there is light (and logged errors)!
I used mysqli instead of mysql_connect() and error is gone since mysql_connect() is deprecated on suggestions of patrick
Try changing this...
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
To this...
$result = mysql_query($data);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_assoc($result);
$details =array(
"id"=>$row['no'],
"question"=>$row['Ques'],
"op1"=>$row['op1'],
"op2"=>$row['op2'],
"op3"=>$row['op3'],
"op4"=>$row['op4']);
echo json_encode($details);
}
Not 100% sure that's the problem, but that's how I structure my basic DB functions, and it works fine.
I would also note that if this is going to to be a public page where users can enter data, I recommend using PHP PDO to handle your database interactions.
I have a jQuery script file on a page which requires data to be uploaded. Depending on if the data uploaded has a value or not, the PHP page will either return the current time (if value uploaded !isset()), or some sql data. However, when the variable I upload actually has a value, it still returns the !isset() method. Am I doing something incorrectly?
AJAX
$.ajax({
url: 'download.php',
type: 'REQUEST',
datatype: 'json',
data: ({
last_downloaded: latestTimestamp,
username: username
}),
success: function (data) {
parsedData = $.parseJSON(data);
if (!latestTimestamp) {
latestTimestamp = parsedData.most_recent;
}
}
});
}
if latestTimestamp is null, (it should be the first time this method is run), then the most recent time is run. However when it runs the second time, latestTimestamp has a value when I console.log.
PHP
<?php
// Get variables sent
$last_chat_time = $_REQUEST['last_downloaded'];
$username = $_REQUEST['username'];
// Start echoing JSON
if (!isset($last_chat_time)) {
// User did not send last chat time they have, assume they just joined
// Get the most recent chat date
$SQL = 'SELECT current_timestamp() as "most_recent" from dual';
$results = mysql_fetch_assoc(mysql_query($SQL));
$last_chat_time = $results;
echo '{"most_recent":"' . $results['most_recent'] . '"}';
}
else{
$SQL = 'return some tasty data'
$result = mysql_query($SQL);
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = Array(
'chat' => $row['chat'],
'time' => $row['time_sent'],
'username' => $row['username']
);
}
echo json_encode($messages);
}
On the php, it ALWAYS returns the first if. However, if I visit the url directly for the php page and append ?last_downloaded=somedate, it returns the correct information. Am I doing the AJAX incorrectly?
To me this has to be updated to type : 'post or get' because php's $_REQUEST handles both, so you can change your type to this:
$.ajax({
url: 'download.php',
type: 'post',
or this:
$.ajax({
url: 'download.php',
type: 'get',