Reload php include on button click - php

I am a beginner on using php mysql and basically what I am trying to do is in index.php on form submit it inserts the data in mysql and then I query and store 2-3 column values of same data in another php file lets say data.php. Now I have included data.php in index.php and on every submit want to reload data.php and display latest values from the same in a data table in index.php.
Long story short, reload a include php file containing variables on button click to display latest values everytime after form submit. Below is the code
<?php
include("data.php");
?>
<html>
<form id="signupform"></form>
<button onclick="postdata()"></button>
<table>
<tr>
<td>var1 in data.php:</td> <td>value of var1</td>
</tr>
<tr>
<td>var2 in data.php:</td> <td>value of var2</td>
</tr>
</table>
<script>
function postdata() {
var data = $("#signupform").serialize();
$.post('submit.php', data, function(data,status){
console.log("");
});
document.getElementById("var1").innerHTML = '<?php echo $var1; ?>' ;
document.getElementById("var2").innerHTML = '<?php echo $var2; ?>' ;
</script>
</html>

If its a form make the action="time.php" and on the time.php page after you insert the data use header("location: index.php");

PHP code is server-side code that finishes executing before the page is actually sent to the browser. What this effectively means is that you can't execute php code when the user does something like clicking a button.
There are effectively two solutions for 'reloading' the data from an included php file:
Reload the entire page after you've posted the form data:
$.post('submit.php', data, function(data,status){
console.log("");
window.location.reload();
});
Or fetch the output of the other PHP file (assuming data.php) with Jquery after your post to submit.php is done, and then insert the result into the DOM:
$.post('submit.php', data, function(data,status){
console.log("");
$.ajax({
url: "url/to/data.php",
method: "get",
success: function(output){
$("#html-element-id-here").html(output);
}
})
});

Related

Search and display result on next page using ajax in codeigniter

i am working on search in codeigniter using ajax. i am passing value for search to codeigniter controller and getting result data in ajax success function on same page but i want to print result data on another page .
my code of viewpage is below with ajax script.
<input type="text" autocomplete="off" onblur="abc()" name="searchs" >
<script>
function abc() {
var name = $("input[name=searchs]").val();
$.ajax({
type: "POST",
url: 'search',
data: "search="+name,
success:function(data){
alert(data);
$("#res").html(data);
window.location="star/prsearch";
}
}); }
</script>
window.location="star/prsearch" star/prsearch is path for next page now i am redirecting on another page but there are no printed result data .
Give the action to your form where you want to Submit and Submit The form using a button and perform the ajax on the new page instead on load of the document

Getting jQuery variable to PHP in the same file without refreshing the page

Thanks for reading. I have tried the answers in other similar questions but none have worked so far. I'm trying to UPDATE values inside a Table that is inside a form, so in the first part of the file is the isset "saveImport" which is the name of the a tag that I'm using to send the id thru the URL:
if (isset($_POST['saveImport'])) {
$id = $_POST['id'];
}
a tag:
<a name="saveImport" href="./?id=<?= $row['id']; ?>" class="saveImport btn btn-success col-xs">Save</a>
I do get the ID value in the URL but since is been updated in the same file I'm assuming it refreshes the page before the variable gets post thru AJAX:
<script type="text/javascript">
$(document).ready(function() {
$('.saveImport').click(function() {
var imp_id = id.id;
var imp_href = $(id).attr('href');
alert(imp_href);
$.ajax({
url: "./",
data: {id : imp_id},
type: "POST",
success: function(data){
alert(id);//send this ID to the PHP variable without
//refreshing the file
}
});
});
});
I'm getting the class .saveImport because it's inside a Table which is displaying values from a Database so it's inside a while loop and if I use an ID it will cause conflict as the ID will repeat itself.
I already created the PHP function to UPDATE the Values which executes if the ISSET is true, so my real problem will be to execute the ISSET and inside grab the ID that was posted with AJAX so I can use the ID in the UPDATE function. Right now, if I click on the a tag, it sends the ID thru URL, the page refreshes but the value of the ID is not getting in the $id = $_POST['id];
I appreciate your time.
This should work.
Change the ajax url to your php file name (mine was t.php).
Replace 99 with your data from php. (id is used. href is not used)
<?php
if (isset($_POST['saveImport'])) {
print_r( $_POST );
exit;
}
?>
<a name="saveImport" id='99' href="./?id=99" class="saveImport btn btn-success col-xs"'>Save</a>
<script type="text/javascript">
$('.saveImport').click(function(event) {
var imp_id = this.id;
$.ajax({
url: "t.php",
data: {id : imp_id, saveImport: 1},
type: "POST",
success: function(data){
alert( data );//send this ID to the PHP variable without
//refreshing the file
}
});
event.preventDefault();
});
</script>
.preventDefault() will prevent the link from loading the target page... And then, ajax will proceed.
$('.saveImport').click(function(event) {
event.preventDefault();

Passing Javascript (HTML Table Contents) array to php file

Im very confused, I have been looking for a solution to pass HTML table contents via a javascript array (if this is indeed the best way of capturing HTML Table data) to a php file so I can then do whatever I like with the data.
I have simplified the table shown in my example code in order to make it easier, the table i will be using live will have a lot of rows with more complicated data etc.
The current code in get_table_data_php is:-
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div id ="results_table">
<table id="stats_table">
<tr>
<td>Car</td><td>Engine</td><td>Color</td><td>Price</td>
</tr>
<tr>
<td>Ford</td><td>2 Litre</td><td>Blue</td><td>22,000</td>
</tr>
<tr>
<td>Audi</td><td>2.5 Litre</td><td>White</td><td>25,000</td>
</tr>
</table>
</div>
<script>
var myTableArray = [];
$("table#stats_table tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray); // alerts the entire array
alert(myTableArray[0][0]); // Alerts the first tabledata of the first tablerow
$.ajax({
type: "POST",
data: {myTableArray:myTableArray},
url: "stats.php",
success: function(msg){
$('.answer').html(msg);
}
});
</script>
The code in the stats.php file being called is as follows:-
<?php
var_dump($_POST);
?>
The code in the calling php file runs as expected and shows (via the alert(s) which are there for my sanity) the table data as expected.
The file called (stats.php) however does not do anything and as such I do not know if its working and what the issue is as to why it isn't.
I am pretty new to the Javascript and Ajax side of things so any help would be appreciated.
Regards
Alan

How can i pass a variable from js file to another using ajax jquery?

I have 2 js files and i want to pass 2 variables from file1.js to file2.js. What i have done until now is to send these 2 variables from file1.js in a 3rd file file3.php with ajax using this:
$('#replace').click(function(){
var replacement = cur;
var replacement2 = cur2;
$.ajax({
url: DOMAIN_NAME+"file3.php",
type: "post",
data: {replacement: replacement, replacement2 : replacement2},
success:function(data){
console.log(data);
},
error:function(){
alert('Something Went Wrong');
},
});
});
In my file3.php:
if(isset($_POST['replacement']) && isset($_POST['replacement2']){
$a = $_POST['replacement'];
$b = $_POST['replacement2'];
}
<input type="hidden" id="af" value="<?=$a;?>">
<input type="hidden" id="bf" value="<?=$b;?>">
In my File2.js:
var a = $('#af').val();
var b = $('#bf').val();
i can see that in the network the ajax passes the variable with a status 200 OK but in the php file my variables doesn't pass. So the file2.js can't get the values. What i am doing wrong??
Let's say you have this simple form:
<form id="my_form">
<input type="text" name="a_field" id="a_field">
<input type="text" name="b_field" id="b_field">
<button id="submit_form">Submit</button>
</form>
The jquery script file (#1) for this form can be named "script1.js" and can look like that:
$(document).ready(function(){
$('#submit_form').on('click').function(e){
e.preventDefault();
var formData = $('#my_form').serialize();
$.ajax({
type: 'POST',
url: 'my_ajax.php',
data: formData
});
});
});
Notice that I serialized the form to be quicker... (If you want you can specify which variables you want to pass to ajax)
Here is an example of my_ajax.php:
<?php
session_start();
if(isset($_SESSION["a_var"])){unset($_SESSION["a_var"]);}
if(isset($_SESSION["b_var"])){unset($_SESSION["b_var"]);}
if(isset($_POST["a_field"])){$a_field=htmlspecialchars($_POST["a_field"]);}else{$a_field=""; exit();}
if(isset($_POST["b_field"])){$b_field=htmlspecialchars($_POST["b_field"]);}else{$b_field=""; exit();}
$_SESSION["a_var"] = $a_field;
$_SESSION["b_var"] = $b_field;
?>
With the above file, we created two php sessions based to the input-field values that we acquired from our html form.
Now the "tricky" part:
Your SECOND js file (#2) must be given an extension .php and NOT .js
It will however execute any javascript code if of course that code is enclosed in "script" tags
Let's name that file "script2.js.php" -which can be like that:
<?php
session_start();
if(isset($_SESSION["a_var"])){$value_a = $_SESSION["a_var"];}else{$value_a="";}
if(isset($_SESSION["b_var"])){$value_b = $_SESSION["b_var"];}else{$value_b="";}
?>
<script>/*...include jquery here (if necessary)...*/</script>
<script>
$(document).ready(function(){
//jquery is NOT necessary for my example
//I just included it in case you need to do other tasks...
var valueA = '<?php echo $value_a; ?>';
var valueB = '<?php echo $value_b; ?>';
//Now you can do anything with these values... For example, you could alert them:
alert('Value A: '+valueA+' - Value B: '+valueB);
});
</script>
One last thing:
While to include a js file to your html page you do:
<script src="http://www.example.com/scripts/yourscript.js"></script>
To include the "js.php" file you must do it by using the php "include" function:
This is how I would suggest to pass variables from one js file to another by using php sessions!
My example is quite "basic" and could take a lot of "polishing" work regarding functionality and security... But should give you an idea as of how to start...
Hope that helps you and/or others...

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.

Categories