Multiple one-time PHP database updates using jquery's .error() - php

I have a webpage with some broken images, these images are being show by a database. I am using the following jQuery to hide the images that are broken.
//images are wrapped in an anchor
$("img").error(function() {
$(this).parent().hide();
});
I would like to utilize the "status" column in the database to set all of the broken images to "hidden". Every anchor that wraps an image on the page has a "id" attribute that matches the primary database key "id".
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: "status=hidden&id=".error.""
});
});
// changestatus.php
<?php
mysql_connect("localhost", "stackoverflowexampleuser", "stackoverflowexamplepass") or die(mysql_error());
mysql_select_db("stackoverflowexampledatabase") or die(mysql_error());
$id = $_POST['id'];
$status = $_POST['status'];
$query="UPDATE stackoverflowexampletable SET status = '".$status."' WHERE id ='".$id."'";
mysql_query($query) or die ('error');
mysql_close();
header( 'Location: MYSOURCE' ) ;
?>
This is my first stab at ajax, and I know I got some stuff seriously wrong. I saw a couple of examples using KEY VALUE pairs but I don't know what the $_POST['var'] should be.
Can you even request something like this "when the page loads"? I tried wrapping it in an arbitrary button and it didn't work.
Since this just needs to be used once I'm not really focused on using AJAX.

Try this:
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: {
status: "hidden",
id: error
}
});
});
If you're wanting to initiate it on page load, be sure to include it in the $(document).ready() function.

Related

How to use onclick on a button with an insert function for multiple buttons php

I have a page with several buttons whose values and names are retrieved from the database. I'm trying to run an insert query on any button clicked, my code so far:
<?php
$sqlGetIllness = "SELECT * FROM illnissesandconditions ";
$resultGetIllness = $conn->query($sqlGetIllness);
while ($rowGetIllness= mysqli_fetch_array($resultGetIllness)){
echo "<div class='col-md-3'style='margin-top:20px;'><button onclick='insert(".$rowGetIllness['illness'].");' class='button button1' style=' color:white;' value='".$rowGetIllness['illness']."'>".$rowGetIllness['illness']."</button></div>";
}
function insert($value) {
$value='';
$sqlGetId = "SELECT commonID from common group by commonID DESC LIMIT 1 ";
$resultGetId = $conn->query($sqlGetId);
$r=mysqli_fetch_array($resultGetId);
$id=$r['commonID'];
$sqlGetIllness = "INSERT INTO medicalrecords (CommonID,Medical_Condition) VALUES (".$id.",'".$value."')";
$resultGetIllness = $conn->query($sqlGetIllness);
}
The value passed to the function inside onclick is correct when I inspect it in the browser, however nothing happens. I have a database connection on already, what could be wrong? Is it possible to do it like that in php without refreshing the page? Or do I need to use a client side lang like AJAX? Please note that I've never worked in AJAX btw.
New EDIT:
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
condition: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Condition Inserted!');
},
error: function(result) {
alert('error');
}
});
});
</script>
Solution:
I got it worked out, after writing the script, i retrieved the variable value on top of the page
if (isset($_POST['condition'])) {
$value=$_POST['condition']; }
inside $_SERVER['REQUEST_METHOD'] == 'POST' ) and now it inserts the value when ever any button is clicked, my next step is to give the clicked button a background color
Solution is in the post under Solution, was my first time trying ajax and it did work indeed, gave the button an id, and took its value ( any button clicked ) through this.val and sent via post, retrieved and used the value in a variable for the insert query.

Increment MySQL value on click with +1

What I have
An url like this: http://localhost:8888/website/?key=ABC
A MySQL table with many rows, one with a key called ABC. I have a button that I want users to click (upvote) the MySQL row corresponding to key=ABC.
In my scripts.js I have this (incomplete?) Ajax code:
function increment() {
$.ajax({
type: 'POST',
url: '../js/ajax.php',
success: function(data) {
alert("function saved: " + data);
}
});
}
And my ajax.php looks like this:
<?php
if (isset($_GET['key']) {
$rowKEYtest = $_GET['key'];
$sql2 = "UPDATE database SET Score = Score + 1 WHERE UniqueKey = '$rowKEYtest'";
$conn->query($sql2);
} else {
echo "lol";
}
?>
It's not updating. I have no idea what to do.
Please have a look in your code, There is 2 mistakes.
1. In your ajax call you are using type: 'POST', you should use GET.
2. You are nor parsing your 'key' param in ajax call.
Actually you are using POST method in ajax but in ajax.php trying to get the value with GET method. second thing you are not passing any param in ajax call.
Hope this will help.

Fetching id from database of submitted data

So I am submitting data to the database. Each data sent contains an id that is auto incremented. With ajax or PHP (I am very much new to this, and trying to learn I'm sure it's ajax along with some php) I need to fetch the id of the data that was submitted.
The idea is, after the form is submitted, the user gets the link back to the submitted page. Example:
Quote was submitted! [link] Click to go to the link or go back.
The link will look like this: http://example.com/quote-192
I pretty much have everything else set, I just don't know how I'll get the id and add it to the link.
Here is the PHP that processes the form:
require('inc/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
//echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Oh, and the data is being sent with ajax:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
var like = $('.quote-wrap span iframe');
$('.inner').prepend('<div class="quote-wrap group">' + like + '<div class="quote"><p>' + quoteVal+ '</p></div></div>');
// console.log("success");
});
return false;
});
So how would I get the id for each quote and add it to the page after the form has been submitted?
In you php:
echo mysql_insert_id($result)
Then in your jquery ajax:
$.ajax({
type:'post',
url:'url.php',
data:querystring,
success:function(data){
var id = parseInt(data);
}
]);
this will return the inserted ID as an integer value that you can work with in javascript
Have the PHP print the ID as a response to the request:
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
// Print the id of last insert as a response
echo mysql_insert_id();
jQuery, test code to alert what was echoed by the PHP as a test
// add data as a param to the function to have access to the PHP response
$.post("add.php", $(this).serialize(), function(data) {
alert(data);
});
With this php-function. You can call after inserting.
int mysql_insert_id ([ resource $Verbindungs-Kennung ] )
mysql_insert_id

Changing url from JavaScript code and adding another value

I have following mysql query:
$colname_profile = "-1";
if (isset($_GET['user'])) {
$colname_profile = $_GET['user'];
}
mysql_select_db($database_conn, $conn);
$query_profile = sprintf("SELECT * FROM users WHERE user_id = %s", GetSQLValueString($colname_profile, "int"));
$profile = mysql_query($query_profile, $conn) or die(mysql_error());
$row_profile = mysql_fetch_assoc($profile);
$totalRows_profile = mysql_num_rows($profile);
and following JS part of code I need to change:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"),
now, how do I add another value inside JS code from above query which should be in format of
user='.$row_profile['user_id'].'
so I need to keep whats already inside that JS url and at the end add that user ID. In case you need complete JS here it is
<script type="text/javascript">
$(document).ready(function(){
$("#loadmorebutton").click(function (){
$('#loadmorebutton').html('<img src="../images/body/icons/ajax-loader.gif" />');
$.ajax({
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"),
success: function(html){
if(html){
$("#historywrapper").append(html);
$('#loadmorebutton').html('Load More');
}else{
$('#loadmorebutton').replaceWith('<center>No more posts to show.</center>');
}
}
});
});
});
</script>
Thanks for help.
maybe change url line to something like this:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "&user=<?php echo urlencode($row_profile['user_id']); ?>",
Given the way the question is asked, this will work:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "user=<?php echo $row_profile['user_id']; ?>",
However I don't know if that is what you are looking for. Is $row_profile['user_id'] only a single value on a page or is this like a list of users and for each row in the table is there a different $row_profile['user_id'] that might exist? If this is a single value, for example the user_id of the user visiting the page and you want to pass that along with every ajax request, you might be better off storing that value is sessions elsewhere as it is unlikely to change unless the user logs out and back in under another account.

ajax POST not working, can't figure why

I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.

Categories