i am developing a site with html and php ...
what i have done so far for like button on my page is as follow(concept is same only name is different on facebook it is like and on my site it is Points Up )
<form method="post">
<input type="hidden" value="<?php echo $posts[postid]; ?>" name="postid">
<input type="submit" name="pointsup" value="Points Up" />
</form>
the above will create the button with name Points Up.
if(isset($_POST['pointsup']))
{ in this if block i have written all queries to update database and user interface and all
}
what i want is instead of that button there should be some link witch will run my sql code.
i also tried JavaScript but it doesn't help anything
Thanks in advance for your answers!
When you are working with a single anchor tag (hyperlink), you should send your parameters by GET method. in case, /your/address/rate.php?id= and check $_GET['id'] in PHP (validate/sanitize/...)
also, you can send your requests as POST by using AJAX.
this is a sample for jQuery:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
take a look here
but if you want to use pure JavaScript, you should work with XMLHttpRequest object. take a look here.
You should do something like:
Find where you should point your link to and what parameters are needed, i will call it $url. It can involve such things like creating additional files, refactoring your code, etc...
Write js method which will send request to $url. I will call this method sendPointsUp;
Create link which will react to onClick event and call sendPointsUp with desired parameters from there.
What you can do is just add a link with an id so you can reach it easily with jquery.
Create a php-page where you do the query and other stuff (security check, cookie, whatever you want to do), and finally attach an ajax event to the link to call your php-page.
Print the link in your page:
Vote up
Create php
<?php
// do the query and other stuff, return the result in json format
// if you want to do something with the result (for example display the votes)
Javascript
$('#voteup').click(function(e){
$.ajax({
url: "your/url/to/phpfile",
}).done(function(data) {
// rewrite link to undo vote or whatever you want
// do something with the returned data
});
});
Related
I'd like to update a form, more exactly I wish to display an extra scroll menu, depending on the user's choice in a first scroll menu.
I have a page, mypage.php page on which there is a form. Here it is :
<form method="post" action="wedontcare.php" enctype="multipart/form-data">
<label for="base">3 - Select a DB </label><br />
<?php
include 'functions.php';
offers_choice_DB();
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
I have a separated file "functions.php" where are declared all the functions I use here. offers_choice_DB() displays a scroll menu where I can select a database (actually, this function performs a MySQL query and echoes the result in a scroll menu). If the user selects a database, then $_POST['base_name_choice'] exists. And it does, because when i only work with PHP/HTML, all is doing fine.
My purpose is to allow the user to select a database, then for this database I'd like to display a second scroll menu that displays some tables from this DB. This scroll menu will only be displayed if a POST value has been set. The offers_choice_table($_POST['base_name_choice']) function takes this value as an argument, then echoes the HTML for the scroll menu, containing the tables. Here we are !
Oh, and the submit button is not important here, because I want to have my second scroll menu displayed before the user clicks on the submit button, so we just disregard the target page, ok ?
Before, everything was OK : I used tests, conditions (isset...) but it was not dynamic, I had to call other pages, ...etc. And now I want, as you guessed, to use jQuery to refresh mypage.php as soon as the user selects a database so that an extra menu appears.
I started to listen to a change in my scroll menu, but then I don't know what to do to refresh my page with a POST parameter containing the selected database. Anyway, here is my code :
<script type="text/javascript">
$( '#base_name_choice' ).change(function() {
var val = $(this).val(); //here I retrieve the DB name
alert( val ); //I notify myself to check the value : it works
$.ajax({
type: 'POST', //I could have chosen $.post...
data: 'base_name_choice='+val, //I try to set the value properly
datatype: 'html', //we handle HTML, isn't it ?
success: function(){
alert( "call ok" ); //displays if the call is made
//and here...???? I don't know whatto do
}
})
});
</script>
Here it is...any help will be appreciated ! Thanks :)
Regards
The issue here is that your page is rendered first (html + php preprocessing). That means that once your page is rendered, you won't be able to make direct php method calls such as offers_choice_table or change the $_POST parameters.
How you normally do this, is by making an AJAX call from your javascript to a PHP script/method which than generates the second menu based on the parameter that the user chose.
So, you don't need this part:
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
because you will call "offers_choice_table" method with an ajax call.
You make the ajax call to a url which will return the second menu
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data){
alert( "call ok" ); //displays if the call is made
// here you can append the data that is returned from your php script which generates the second menu
$('form').append(data);
}
})
You should use GET instead of POST, in your new PHP file:
if (isset($_GET['base_name_choice'])) {
offers_choice_table($_GET['base_name_choice']);
}
You SHOULD check if the variable has a value set, especially if your function is expecting one. You can use whatever functions you want in this file, it is like any other PHP file you would write. Include any files that you want.
You should make sure to avoid SQL injection when using a GET or POST value in a query: How can I prevent SQL injection in PHP?
In the .ajax() call, there is a callback function success, this runs if the server response is good (i.e. not a 404 or 500). There first parameter in that function is what the server returned. In your case, it would be the HTML you echoed out. You can use jQuery to append the response to an element:
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data) {
// it looks like you're only returning the options of the select, so we'll build out the select and add them
var $newSelect = $('<select></select>');
$newSelect.append(data);
// and then add the select to the form (you may want to make this selector for specific)
$('form').append($newSelect);
}
});
I am trying to create a button on my chat that will allow someone to print the conversation. So I made the button that runs a PHP script that creates a new file, writes the conversation to file, and also writes the following jQuery.
jQuery AJAX Call
function OnBeforeUnLoad () {
$.ajax({
type: 'GET',
url: 'deleteFile.php',
data: {
pageName: ".$pageName."
},
dataType: 'text',
success: function(data){alert('Good bye 1!');}
});
return;
}
HTML Put into page
<br/><br/><form method="get" action="deleteFile.php"> <input type="submit" value="Close this Window"/>
<input type="text" value="'.$pageName.'" name="pageName" style="visibility:hidden"/></form>
deleteFile.php
<?php
$pageName = $_GET['pageName'];
$fullURL = 'PrintPage'.$pageName.'.php';
unlink($fullURL);
echo '<script>window.close();</script>';
?>
When the page shows up and I click the "Close this Window" button it does exactly what I want. It deletes the file and closes the window. But I do not get the same results when I close the window (aka OnBeforeUnLoad()). I even tried triggering submit by giving the form an id of deleteFiles and then doing $('#deleteFiles').submit() and it still didn't work.
How do I get the AJAX to work within the OnBeforeUnLoad function?
The form calls the data pageName but the ajax calls it url.
You probably don't want to prefix and suffix the value with . characters either.
Feel like a dummy.... After making all those changes... I found out all I needed to do was add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
to the header.
Because I was dynamically creating the page in php, I forgot I needed to readd the jQuery.
Always the small things.. Thanks everyone for the help.
I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.
I'm developing a website/database solution which gives the administrator the option to sign into the webpage and perform actions on the database.
Currently they can add/delete/run pre-defined queries, however to 'edit' records in a table, I would like them to specify the primary key (ID) and then have ajax read in the values associated with that record and allow them to be changed.
What's the best way to go about this?
as stratton suggested you have to use jquery/html on frontend and php/mysql on backend that will have the logic to handle the data you send and retrieve result that will be sent back to the user.
ex.
have a form that will send the id to search:
<form>
<input type="text" id="data" name="data"/>
<--send button-->
</form>
I suggest then to use jquery to send the form via ajax like this:
$(sendbutton).click(function(e){
e.preventDefault();
s.ajax({
url: 'urlofyouphppage',
type: 'post',
data : {data: $("#data").val(), action: 'search_thing'}
success: function(data){
//the response from the php page to insert somewhere.
//beware that if you use json you will have to decode via parseJSON.
}
});
});
On you php side you will have to parse the post and then perform the action
<?php
if($_POST['action'] == 'search_thing'){
$id = $_POST['data'];
//query for searching
//format the result data
echo $result; //or json_encode($result); if you want to use json
}
?>
This way you can create multiple logic step by setting each time a different action, and the anwer can be full html code that contains the "next step" to perform.
make an ajax request (use jQuery) to a php script that reads from the database and outputs the return value in whatever format you prefer (html, json) then display it in the front end with javascript
EDIT:
I will try to explain what I want to do a bit better. I am displaying a table with all the fields retrieved from a database using an ajax call to a php file (eg. other.php) in my main.php. What I am trying to figure out is once the table is displayed to screen and the call is in the other.php file, can I implement an update query within other.php to update a field in the database with a user input? Does that make sense?
Thanks.
Yes, it's possible. Assuming that you have a form that the user fills before clicking in the menu, you can add this values in your ajax call.
For example, assuming that you have a search button
<input type='text' name='search' id='search' />
You can pass this to your php with get or post (type of request)
$.ajax({
url: "somefile.php",
type: "POST",
data: "search=" + $('#search').val(),
success: function(data){
//do something...
}
});
And in your somefile.php you can access the value with $_POST['search'] or $_GET['search'] (depending of the type of the request).
I think with this you can adapt to your reality. More samples you can get in the JQuery docs.