display data via ajax when using $_GET - php

How do I display data based on `$_GET', which is to say without refreshing the page ?
I have this for example, and it shows the correct result whenever I click add (increments by 1), but of course it always first refreshes the page.
How do I make it do the same thing without visible page refresh, using ajax?
php and html
if (isset($_GET['add'])) {
$_SESSION['numbers']++;
}
echo $_SESSION['numbers'];
?>
<br>
add
<div id="response"></div>
And if for example I wanted to pull something from the database via post and print it, I would do something like this:
$.post('print_something.php', function(response) {
$('#response').html(response);
});
But how do I change that for get, since there is stuff in the URL plus sessions?
EDIT:
I tried this, I removed all php from the current script, added it to get.php which is now like this:
session_start();
if (isset($_GET['add'])) {
$_SESSION['numbers']++;
}
echo $_SESSION['numbers'];
And inside my main index script I have this:
$('a.add').click(function() {
$.get('get.php', function(response) {
$('#response').html(response);
});
return false;
});
Now it does not increment each time i click add, it just shows 1 the first time and doesn't change afterwards.

You are not passing the add parameter to your $.get, so isset($_GET['add']) is false. Add add to your ajax call
$.get('get.php', {add:true}, function(response) {
$('#response').html(response);
});
I put {add:true}, but true could be anything, as you are only checking if it is set, not the value
alternatively, you could also just add it to your url
$.get('get.php?add=true', function(response) {
$('#response').html(response);
});

Please find the example code below:
$('a.add').click(function(e) {
e.preventDefault();
var request = $.ajax({
url:"get.php", //Please provide the absolute URL to avoid errors.
type:"GET",
data:""
});
request.done(function(response){
$("#response").empty().html(response);
});
});

Related

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

How to run php Delete query in jquery without refreshing page

I want to delete value from database using PHP.
Using a table row and placed a button like "Delete" and I create a function like onClick='window.location='page.php?action=del&id=1' and in PHP for delete.
if($_REQUEST['action'] == 'del'){
$req_id = $_REQUEST['id'];
$del_query = mysql_query("DELETE FROM table WHERE id='$req_id'");
}
It's working well but, I don't want to refresh the page. Please tell me how can I do it without page refresh?
<button id='delete'>Click Me To Delete</button>
$('#delete').on('click',function(){
$.ajax({
type:'POST',
url:'page.php',
data:'action=del&id=1',
success:function(result){
//Deleted
}
});
});
Try this:
delete
<script type="text/javascript">
function delData(control,id){
$.ajax({type:'POST', url:'page.php?action=del&id='+id, success:function(result){
//alert('deleted');
$(control).parents('table').eq(0).remove();
}
});
}
<script>
NOTE:
You will need to add jQuery file for this.
This process is called ajax. Google it.
Then try to pass the data in post parameter rather than in query string.
Update: Note that now the 'this' is passed as a reference of this control to the method delData.

Run PHP code when user clicks link and pass variables

I need to run a PHP code from external server when user clicks a link. Link can't lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?
Something like this?
<a href="runcode.html?id=' + ID + '"> and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?
use something like this in you page with link
Some text
in the same page put this somewhere on top
<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";
$.ajax({
url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
alert('success');//do something
}
});
return false;
});
});
</script>
on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple
<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>
hope that helps
You can do this with an ajax request too. The basic idea is:
Send ajax request to runcode.html
Configure another AJAX to trigger from that page
Considering, this as the markup
<a id="link" href="runcode.html'">Test</a>
JS
$("#link").on("click", function() {
$.get("runcode.html", { "id" : ID }, function(data) {
//on success
});
return false; //stop the navigation
});

Refresh value from MySQL db on php page after clicking a submit button

So all i need to do is refresh a variable displayed on a php page which is stored in a MySQL db. This value is an int which is subtracted by 1 everytime the submit button from a form is clicked. As i've opted to use AJAX to post the form the page isn't being refreshed, therefore the value isn't being updated along with the form submission.
$qry = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
while($row = mysql_fetch_array($qry)) {
if ($row['codes_remaining'] ==1 )
{
echo "You have ".$row['codes_remaining'].' code remaining';
}
else {
echo "You have ".$row['codes_remaining'].' codes remaining';
}
}
So this code just displays how many "codes" a person has left. I need this value to be refreshed once the submit button has been clicked from the form on the same page.
I'm using the following JavaScript to not refresh the page.
$("#form-submit").click(function(e) {
e.preventDefault();
$.ajax({
cache: true,
type: 'POST',
url: 'process-register.php',
data: $("#form-register").serialize(),
success: function(response) {
$("#output-div").html(response);
}
});
});
Thanks,
LS
If you'd like to update the value, do it like this (jQuery is easiest):
$(".submit").click(function(event) {
event.preventDefault();
$(this).load('file.php',function(val){
$('#output').text(val);
});
});
And in file.php:
<?php
connect_to_db();
$returned = get_info_from_db();
echo $returned;
?>
The jQuery will grab the info on file.php and put it into #output.
Maybe It's just me, but why not use jQuery .load function?
$("#form-submit").click(function(e) {
e.preventDefault();
$(this).load('process-register.php');
});
Maybe not ethical nor the correct way of doing this but everytime you click on #form-submit, it loads that file and therefore processes it everytime. Also note that if you load a file that uses MySQL connection yes has no mysql_connect or mysql_select_db configured, it obviously won't work. I've had that for quite some times.
In your 'success', you could possibly just throw in
$("#WhereYouWantTheOutput").load("process-register.php");
That way whenever your submit succeeds, it'll also load the output for you. Just replace #WhereYouWantTheOutput with the name of where you want the output placed.

PHP + Jquery - pass value through ajax to php and check against variable

I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.
This is the code I've written:
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}else{
//Do nothing
}
echo $score;
?>
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
var value = "145";
alert(value);
$.ajax({
url: 'processing.php', //This is the current doc
type: "POST",
data: ({name: value}),
success: function(){
location.reload();
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.
First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.
I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.
// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}
echo $score;
?>
// test.html
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
// Why were you reloading the page? This is probably your bug
// location.reload();
// Replace the content of the clicked paragraph
// with the result from the ajax call
$("#raaagh").html(data);
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
You use POST in your jQuery, but you try and get a GET in you php.
BTW it is good practice to check if a GET/POST variable is set before reading it.
using the isset() function.
Replace $_GET with $_POST and there you are.
Basically POST and GET are two different way to pass variables to a script. The get method in php can also be attached at the end of a url : script.php?variable=value and it is really easy to hack. While the post method can be submitted with forms or ajax calls and it is pretty safe, at least more than the get.
Also i'd suggest you to check whatever a GET or POST variable is set before calling it, so that you can prevent stupid notice errors.
Just use the following code:
if (isset($_POST['var']) and !empty($_POST['var'])) { // do something }
You can also delete the
}else{
// do nothing
}
part of the script, since the else clause it is not necessary always.
You're submitting the data with an Ajax POST, but trying to read it out of a GET. Either use type: "GET" in your Ajax call or $_POST['name'] in your PHP.
The problem is you are using jQuery to POST your value, yet you are reading it with GET.
You should be able to fix your problem by changing your $_GET['name'] to $_POST['name']

Categories