Curiosity killed the cat...
Here's a good one that I need some help with, long story short I am trying to update information on MySQL databases, I understand how to do this with a form on the website and a bit of PHP coding. However, what I am trying to do is create a link on my webpage, just a standard html link, which - once clicked will do the same thing as a form almost (without all the information) which would change a piece of info in the database. Example:
Click "here" to change set number from 0 to 1
Once the user clicks "here" the number in the database changes from 0 to 1.
I would use Ajax. Even though you need to use another PHP file, that won't refresh the HTML page.
1) The link should be something like:
Click here to set number from 0 to 1
2) The Javascript/JQuery code:
function changeValue(value) {
$.ajax({
type: "GET",
url: 'changeIt.php?value='+value,
success : function() {
//does nothing
}
});
}
3) And finally, the code in changeIt.php file should be something like:
$value = $_GET['value'];
//Use MySQL to change the value in the Database
Related
I have a div which contains comments for a post ... when user add a comment the div containing comments get updated immediately ( i have set a function which is called when user press enter )
Here Is my code for that :
$(document).on('keydown','.addComment',function(e){
var id = $(this).attr('id').match(/\d+/);
var p_id = Number(id);
var comment_box = '#comment_box_'+id;
var content = $(comment_box).text();
if (e.which === 13 && e.shiftKey !== true) {
content = content.replace(/\s\s+/g, ' ').replace(/\n/g, '<br>');
if (content.length > 0 ) {
$.ajax({
type : 'POST',
url : 'update.php',
data: ({
content: content,
id: p_id,
act: "add_cmnt"
}),
success : function()
{
update_ca("comment_area_"+id, true);
}
}); //End of Ajax
}
return false;
}
});
but a user logged in from another account must have to refresh the page to see new comments ... now what i want to do is that all users see the latest comments without refreshing the page i.e when ever a new comment is posted by any user the div containing comments should be updated ... now one way is to do this is that a function is called out after every 10 seconds which refreshes the div via ajax
Here is code :
setInterval(function(){update_comment_area();}, 10000);
this line of code refreshes the comment area after every 10 seconds but i want this function to be called only if a new row ( comment ) is inserted into a database
can anyone help me that how this can be done ??
Create a function that checks for a new row in the database i.e checkNew().
Then try:
if (checkNew()) {
refreshAjax();
}
Note: for the checkNew(), if a new record has been inputted, return true;
Else return false;
Here is a way to implement the checkNow():
Let it retrieve the value gotten from a PHP page that performs the SQL: SELECT lastupdated FROM commentTable ORDER BY id DESC LIMIT 1.
What that does is that it retrieves the last value in the commentTable which would obviously be the last inserted comment. Then update your page with intervals. The comment will continue to change as long as more comments are being added
Since it sounds like you already have an event for the submission of a comment, and assuming you're using javascript to push the comment to the server:
You can just use a callback and have it refresh then. Of course, that would only show up for the user that submitted the comment.
Example for that: JQuery Ajax calls with callbacks
Since you haven't mentioned your back-end coding language or database structure there are only a limited amount of suggestions I can give. However, one that would work would be to use AngularJS, or Socket.io to establish 2-way binding.
UPDATE:
Based on your code and how you're calling it I'm going to assume that update.php has the ability to know whether the record (comment) was added successfully. Once it's been added, have update.php set a global javascript variable to a new value (increment it, use a random number, doesn't matter as long as the value changes)
Then setup an object.watch() that will do your ajax call to update the comments when that variable changes. This is probably the simplest way to do it without using something like socket.io or angular.
How to use object.watch in javascript
I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.
I have asked this question before but I couldn't understand the answer maybe because it didn't work for me.
I have a developed a chat application. Once a user submits using keyup, it works well i.e inserted into database and also selected just fine and the message is even displayed. The page being refreshed by javascript is load.php which has php code doing the selection like this;
SELECT * FROM chat WHERE sender_id=$_SESSION['id']
This is working just fine. But when I change it to
SELECT * FROM chat WHERE sender_id=$_SESSION['id'] AND receipent_id=$_GET['id']
it is not working simply because the $_GET['id'] of a selected member in the home page is not being passed to the load.php which is being refreshed by javascript every .....milliseconds so that online messages of the session id and the selected member should show in the message display.
I refresh the load.php using this code on the home page;
function refresh(){
setTimeout (function(){
$('#message').load('load.php');
refresh();
}, 2000);
}
working just fine.
Now this load.php must select for me messages only for the member selected in the home page. So how can I have this members' id passed on to this load.php on selecting from database?
Will be so grateful for your help programmers.
If you want to pass $_GET['id'] value try to add in your function this value
function refresh(){ setTimeout (function(){
$('#message').load('load.php?id=<?php echo $_GET['id']; ?>');
refresh(); }, 2000);
}
Then load.php will have get value
You need to add get variable in your code:
function refresh(id){ //receive id
setTimeout (function(){
$('#message').load('load.php?id='+id); //add id variable to the url
refresh();
}, 2000);
}
Well, you need to pass the GET value on the query string. Currently you're requesting this:
load('load.php')
If you want an id value, add one:
load('load.php?id=' + someValue)
If you need to get that value from the current query string in JavaScript, there are a number of ways to do that. Though, when you initially load the page, if the value is available then it would be trivial to output it to the page from PHP code in the first place. Something like this:
var someValue = <?php echo $someValue; ?>;
Keep in mind a few things here:
If the value is a string then you need to specify quotes in the JavaScript, not in the PHP.
Don't blindly echo user-submitted values to the page, that's a security vulnerability.
Users can change this value in your load.() call. So your approach may make it trivial for users to "impersonate" other users in your application. Make sure you always validate authorization server-side.
Your example SQL queries look like glaring SQL injection vulnerabilities. You're probably going to want to read up on validating user input and using prepared statements.
I need to redirect users to a unique url when they visit a specific link which corresponds to a certain/row/column in the mysql database.
Here is what I mean:
The mysql database has a table table123 with a row id 123 and inside a column name "column123".
This row and column correspond to the webpage1.html
Normal javascript redirection is like this:
<script>location.replace('http://website.com/webpage2.html');</script>
What I need to do is extract the value from column123 of the webpage1.html and add it to the redirection url, so it would redirect specifically with that value.
For example:
<script>location.replace('http://website.com/webpage2.html/go/dbtable123row123column123value');</script>
This redirection script will be placed on top of the php page that will call the other php pages, so it has to be dynamic every time, thus the redirection script has to use dynamic placeholder, not static value, except the domain name.
Thanks
If the table really is mysql table and the javascript has no way to access that information, follow other suggestions and deal with it on the server-side. If somehow, the table data are printed on the html document where you want the redirect to take place then you can consider the following. (Though, it would really make more sense to manage this server-side).
Assuming you have given unique id to your column and assuming that the table is on the web page that you have your location.replace call on.
location.replace("http://website.com/webpage2.html/go/" + $('#column123').text())
Without jQuery, you could use
document.getElementById('#column123').innerHTML (or text?)
If it is not practical to assign an id to the column, you can possibly use some jQuery selector magic with :eq
location.replace("http://website.com/webpage2.html/go/" + $('#dbtable123 > tr:eq(1) > td:eq(3)').text())
(none tested)
Assuming you can't redirect in PHP for whatever reason, here's what I'd do. Grab the proper web page from your database using AJAX. I'd suggest using a library such as jQuery to help you do that. If you use jQuery it'll look something like this:
$(function() {
$.get(
'/script/that/queries/db.php',
'your=query_string&goes=here',
function(data) {
if(data.url.length > 0) {
location.href = data.url;
}
},
'json'
);
});
You didn't specify when you want this redirect to fire, so I just put it in the standard body onload. Anyway, after you write that $.get() function call, then in your /script/that/queries/db.php, you'll want to perform your database query based on the get variable(s), and print a JSON encoded array with the valid page you want to redirect to:
$json = array('url' => '/webpage2.html');
print json_encode($json);
Of course I've just written some pseudo code, but hopefully it'll help get the idea across. You'll want to make sure you validate/sanitize all info being querying the database, etc.
Do it simply.Make dynamic url with php script.
header('Location: http://website.com/'.$table123row123column123);
I have a sandbox where I am trying to create a form where a person can add data, and the flow I want is an ajax call that add things to the database, and without refreshing the page, another panel in the original page gets updated with the added information.
How can I pull this off? I currently don't see any such exact examples just by googling.
One simple example (jQ). Bind the JS functionName with some event, on click/submit or something else.
function functionName(val1, val2, and so on) {
$.get('/ServletOrPhpFileOrSomeOther?valueOne=' + val1+
'&valueTwo=' + val2 +
'×tamp=' + $.timestamp(),
function(data) {
//data is the return stuff from you ServletOrPhpFileOrSomeOther
//do something with it... example
$('#ElementToUpdate').html(data);
}
);
}
On the server side 'ServletOrPhpFileOrSomeOther' compute the values and return someting back. Instead of passing values val1, val2 and so on you can read the form values within the function if you prefer.
I used the timeStamp as a dummy because i had some issues with values not getting updated. You can try without.
You can try this url :http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
In join.php, after insert,you can use a select * from tablename and be listed. that you can display a ajax response in another panel of same page.
Have a look at agiletoolkit.org - it is a php framework that provides out of the box crud that does exactly what you are looking for - it opens a jquery dialog for edit and add and makes Ajax calls in the background to refresh a grid with the data.