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.
Related
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);
}
});
}
Using google maps, I have events saving to a database using mysqli. These events are then displayed as markers on the map and when clicked the relevant data is displayed in an info box (Name, date, etc). I want the option to delete an event event by deleting a row from the DB when the Remove (remove-event) button is clicked. The button is contained in the data displayed with the javascript:
var eventContent = $('<div class="event-info">' + '<h4 class="event-name">' + point.name + '</h4><hr>' +
'<span><h5>Date: </h5>' +
'<p class="event-date">' + point.edate + '</p></span>' +
'<p class="event-description">'+point.description+'</p>' +
'</span><button id="remove-event" name="remove-event" class="remove-event btn btn-danger btn-sm" onclick="tidy_maps.delete()" title="Remove Event">Remove Event</button>'+
'</div>');
// Display Event details on marker click
google.maps.event.addListener(event_markers[i], "click", function () {
infowindow.setContent(eventContent[0]);
infowindow.open(map, event_markers[i]);
The script that sends it to the php (removedata.php):
tidy_maps.delete = function() {
$.ajax({
type:'POST',
url:'removedata.php',
success:function(data) {
if(data) {
alert("Are you sure?");
}
else {
alert("ERROR!!!!");
}
}
});
}
The removedata.php is:
$con = mysqli_connect("localhost", "root", "password", "gmaps1");
if (!$con) {
die("Can not connect: " .mysql_error());
}
$sql = "DELETE FROM events WHERE id = 'id' ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
As it is, it does not delete the row in the DB, but when i change the line:
$sql = "DELETE FROM events WHERE id = 'id' ";
to a specific ID No. Example:
$sql = "DELETE FROM events WHERE id = '5' ";
And i run the removedata.php in the browser, it deletes the row with ID=5 from the DB. There seems to be no errors when the console when clicking the remove button so it must be sending to PHP script ok.
I would like when the Remove button is clicked that it asks are you sure and then it deletes that specific Row form the DB.
As far as I can tell you don't pass the ID of the row to be deleted.
You can send data two ways, either as a url parameter, or post it using the
data tag:
$.ajax({
type:'POST',
url:'removedata.php',
data: {id : 5}
});
Access the ID in removedata.php:
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
WHERE id = 'id' you need to remove the '' and add the $ symbol if you want id to be a variable.
Ok I've played around a little and amended the JS slightly:
tidy_maps.delete = function() {
var confirm_remove = confirm("Do You Want to Remove This Event?")
if(confirm_remove) {
$.ajax({
type:'POST',
url:'removedata.php',
});
window.location = "http://www.google.com/";
}
else {
alert("ERROR!!!!");
}
}
So when Confirm is YES, i threw in a redirect to Google just to see what happens. When YES is clicked in the confirm box, it redirects the page to Google but does not delete the row from the DB
Try this
var id = 5;
var request = $.ajax({
url:'removedata.php',
type: "POST",
data: "id="+id,
success: function(data){
console.log(data);
}
});
get post value in removedata.php
//get post value
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
I'm a student who is doing an app with jQueryMobile and gonna be compiled with Phonegap. I want to posting data to a server using jQuery but I have problems loading my .php file in the server.
I have the last version of jQuery.
Here I put my script for post the data from a form:
$(document).ready(function() {
var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
$.ajax({
type: 'post',
data: postData,
url: 'http://www.smartweb.cat/app/Habana/user_register.php',
success: function(data) {
alert('Usuari registrat correctament.');
},
error: function() {
alert('Hi ha algun problema amb el registre.');
}
});
return false;
});
});
Thanks a lot and sorry for my english wrinting.
Your post data are empty. You retrieve them directly when the DOM is loaded and not when the form is submit. You should move your var postData.
$(document).ready(function() {
//var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
var postData = $('#registerForm').serialize(); // here
$.ajax({
//...
});
});
});
First of all I want to say that you should use prepared statements.
Althought you sanitize user input(GOOD) its still recommended using prepared statements.
Not only does it help with readability its also more secure.
Make sure your form sends following postdata:
{name:"YourName", surname:"Yoursurname",date:"<dateobject>",email:"sample#mail.com",user:"username",password:"password}
== THIS LOOKS OK ==
$name = mysql_real_escape_string($_POST["name"]);
$surname = mysql_real_escape_string($_POST["surname"]);
$date = $_POST["date"];
$email = mysql_real_escape_string($_POST["email"]);
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
enter code here
If the conditions above are the same the server should receive all your data. I do see a problem in your query that may be the problem.
What you are doing is inserting everything as string in the database. You have to make sure when you try to execute a query given values for a table that the given values correspond with the database.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
('$name', '$surname', '$date', '$email', '$user', '$pass')"); //insert
Make sure everything is correct for example your date column in the database is it a string or a mysql date TYPE. Try to lose the '.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
($name, $surname, $date, $email, $user, $pass)");
This has been an ongoing issue for me. You all have already helped so much. However, I am stuck again. I cannot get my .ajax() to run. For some reason the .click() won't even work without if(field != text) above my .ajax() call, but I digress.
My question is: Why is my ajax() not functioning properly and if this gets fixed will the table is have displayed update after the query is sent to the database without a page refresh?
Here is my script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
alert("made variables");
if(field != text)
{
alert("in if");
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
Here is my table_edit_ajax.php
<?php
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo 'in table_edit';
$id = mysqli_escape_String($_POST['id']);
$table = "owners";
$field = mysqli_escape_String($_POST['field']);
$text = mysqli_escape_String($_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($query);
//close connection
mysqli_close($con);
?>
The first argument to all mysqli functions is the connection, statement, or result object.
$id = mysqli_escape_String($con, $_POST['id']);
$table = "owners";
$field = $_POST['field'];
$text = mysqli_escape_String($con, $_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($con, $query);
$field shouldn't be escaped, since it's not a string value. Therefore, you need to validate it carefully, to prevent SQL injection. Perhaps instead of allowing the client to submit the field name to update, have them submit an integer, which you look up in an array to convert to a field name.
In your AJAX call, you may have a problem due to not encoding your parameters properly. Change the dataString assignment to:
var dataString = { id: id, field: field, text: text };
Then jQuery will encode it for you.
you are sending a data string
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
and retrieving it through $_POST.
first check what is in $_POST
and use $_GET instead of $_POST
and change post in ajax to get
and what is first and last in success callback??
Hi I'm trying dynamically remove database entries using JS and AJAX without refreshing whole page.
Here is my data.php file:
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM message";
mysql_query("SET NAMES 'UTF8'");
$qq=mysql_query($query);
$i = 1;
echo '<div id="rezult">';
while($ff = mysql_fetch_array($qq)){
echo '<div id="id'.$ff['id'].'">'.$i++.'. Name: '.$ff['name'].' Message:'.$ff['message'].'</div>';
}
echo '</div>';
}
?>
With this code I'm retrieving a data from mysql table:
index.php
function list() {
$.get('data.php?list=1', function(o) {
$('#list').html(o);
});
}
How to dynamically delete desired entry without refreshing a page?
tried to add this code below as a link to the entry, but it getting cut javascript:$.post( like that.
<a href="javascript:$.post('delete_post.php', { id: '$ff[id]' } );" class='delete_post' title='delete post'>delete post</a>
Thanks for advices
Be careful!, if someone make a call to your php file data.php?list=ANYNUMBER he will be able to delete any row, be sure you are using security tools to avoid that.If you use ajax and Jquery I think it will be easier.
try something like this:
$.ajax({
type: "POST",
url: "list.php",
data: { list: "1", session_id: session_ID }
}).done(function( msg ) {
alert( "Data deleted: " + msg );
});
where session_id is the value of the field (in your example is 1), session_id is when someone go to your page you assign him a SESSION_ID, after he click the delete button, you compare if the session ID that you assign is equal to the the session_id from the server (you avoid people from another site to call your list.php). If session_id from the ajax is equal to session session_id on the server allow to delete take a look to this: PHP Session Security