I would like to update my input text type (id="textbox2") when i typed something at another input text type (id="textbox1").
Here's my initial code:
$("#textbox1").keyup(function(){
$.ajax({
type: "POST",
url: "idgetter.php",
data: 'id='+$("#textbox1").val(),
success: function(n) {
$('#textbox2').val(n);
},
error: function(n) {
$('#textbox2').val(n);
}
});
});
And my idgetter.php :
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) return "none";
else{
$r = mysql_fetch_array($q);
return $r["name"];
Long story short, this did not work, any idea why?
In idgetter.php, Instead of returning using return give
echo "none";
and
echo $r["name"];
You should try echo instead of return:
your code would be like this:
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) echo "none";
else{
$r = mysql_fetch_array($q);
echo $r["name"];
Think there are a few amends needed in your php:
change return to echo (like stated in the other answers)
change your if statement to
if(mysql_num_rows($q)==0){
echo 'none';
}else{
$r = mysql_fetch_assoc($q);
echo $r['name'];
}
That should do it hopefully. Also as an FYI its worth trying to avoid adding $_POST[''] items to SQL statements directly, as its prone to SQL injection breaches.
Related
I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.
I want to check if a user has favourited an item but I'm unsure how to return the result of a database query to ajax.
I will show different html depending on the result.
Php
$query = "SELECT itemID from favourites WHERE userid = '" . $user. "'";
$result = mysql_query($query);
echo json_encode($result);
Jquery
$.ajax({
url: "inc/functions.php",
type: "POST",
data: {--result--},
success: function () {
// if result found in database
$('favourite').hide();
// if result not found
$('favourite').show();
}
});
I can't figure out how to display $result in the jquery code.
Any help much appreciated.
$result in this case is a PHP object representing a result.
You will have to use a fetch() method in order to extract the result before sending it back to your JS.
See this link. There's a list of all fetch-family method right above the comments.
Also, you will need to make a connection with you database beforehand using mysqli_connect (or mysql_connect in your case).
As stated in the comments, you should however use mysqli* functions family instead of mysql*.
Thanks to the comments for info regarding mysqli. I updated the code and solved the ajax part.
For anyone else stuck, I got it working like this:
PHP
require ("../../connection.php");
$sql = "SELECT * FROM favourites WHERE userID = ? AND itemID = ?";
$user = $_POST['userID'];
$item = $_POST['itemID'];
$statement = $db->prepare($sql);
if($statement === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db->error, E_USER_ERROR);
}
$statement->bind_param('ii',$user,$item);
$statement->execute();
$statement->bind_result($user,$item);
while($statement->fetch()){
echo 1;
}
$statement->close();
Jquery
$.ajax({
url: "inc/userList.php",
data: userList,
type: "POST",
success: function (result) {
if (result == 1){
$('#addItem').css('display', 'none');
$('#removeItem').css('display', 'inline-block');
} else {
$('#addItem').css('display', 'inline-block');
$('#removeItem').css('display', 'none');
}
}
});
I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];
How will i process this Ajax in php.
What i want to do is send the data to process.php and if mode=loadlinks it will do a mysql query
function PresentLinks(div_id){
$("#loading-status").fadeIn(900,0);
$("#loading-status").html("<img src='img/bigLoader.gif' />");
$.ajax({
type: "POST",
url: "process.php",
data: "mode=loadlinks",
success: function(msg){
$("#loading-status").fadeOut(900,0);
$("#"+div_id).html(msg);
}
});}
What i want to process is
if($_POST['mode'] == loadlinks){ // this is what i want to ask
$query = "SELECT * FROM site ORDER BY link_id DESC";
$result = MYSQL_QUERY($query) or die (mysql_error());
while($data = mysql_fetch_row($result)){
echo ("$data[1]");
}}
else {
}
You need to quote strings in PHP. Otherwise they will be assumed to be constants. You should also be using PDO.
if($_POST['mode'] == 'loadlinks'){
$pdo = new PDO('mysql:host=HOST;dbname=DATABASE'), 'username', 'password');
$stmt = $pdo->execute('SELECT * FROM site ORDER BY link_id DESC');
$sites = $stmt->fetchAll();
foreach($sites as $site) {
echo "<div>" . $site['name'] . "</div>"; // Or whatever info you want to output
}
}
For performance you should be specifying table column names to retrieve instead of using *.
you need to quote the string value
if($_POST['mode'] == 'loadlinks'){.....
I am creating a facebook like posting system..
My problem today is it doesn't seem to insert the value i get from the text area into my data base..
here is my java script:
$("#share").click(function()
{
//var typeNew = document.getElementById("content").value;
var update = $( "textarea#content" ).val();
//document.write(update);
if(update.length == 0)
{
alert("empty, please type something.");
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
}
else
{
//$("#flash").show();
$("#flash").html('<img src="loader.gif" />Loading Comment...').fadeIn("slow");
$.ajax({
type: "POST",
url: "post_update.php",
data: 'update=' + update,
success: function(msg)
{
$("#flash").ajaxComplete(function(event, request, settings){
//alert("Successfully Inserted")
$("#flash").hide();
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
});
}
});
}
return false;
});
then here is my php code:
<?php
$post=$_REQUEST['update'];
$post=$_POST['update'];
//echo '$post';
# $db = new mysqli('localhost', 'root', '', 'wall');
if(mysqli_connect_errno())
{
echo "Error! Could not connect to database. Reset fields.";
exit;
}
$sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
$result = $db->query($sql);
if($result){
echo 'OK';
}
else{
echo 'FAIL';
}
$db->close();
?>
can someone tell me what's wrong?
it worked well when the delete function was in error but now that it's functional my share function does not work..
In your PHP code you have the following lines:
$post=$_REQUEST['update'];
$post=$_POST['update'];
You shouldn't have these both. In Your case, You actually need only the second one but for testing, try commenting it out leaving only the $_REQUEST line. Now you can pass parameters by GET too.
To see, if the query is correct, print it out too like this:
echo $sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
Now direct your browser to that location your.domain/post_update.php?update=testmessage and see the output.
If everything seems to be working, replace the POST/REQUEST lines with this:
$post=$db->real_escape_string($_POST["update"]);
I ran into this the other day. Use autocommit or start and commit transactions. Also, try a semicolon at the end of your statement (probably not the issue).
http://dev.mysql.com/doc/refman/5.0/en/commit.html
If your $post is coming out to be fine then try:
$post = $db->real_escape_string($_POST["update"]);
if (!db->query("INSERT INTO posts(update,date_posted) VALUES('$post' ,NOW())")) {
echo $db->sqlstate; //show error
}
else {
echo "inserted";
}
Assuming the column type of update is varchar / charand date_posted is datetime:
$sql = sprintf("INSERT INTO posts(update,date_posted) VALUES('%s',NOW())",
mysql_real_escape_string($post));
$result = $db->query($sql);
Please change the column name "update" to anyother. it may works. And Avoid some predefined varibales for column names.
Hope it helps.