Ajax / Jquery refresh page after variables are passed - javascript

Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
<a href='#' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
and
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
});
}
So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:
http://website.com/index.php#
and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.

e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
$('.dbchange').click (function (e) {
e.preventDefault();
var id = this.id;
$.ajax({
type: "POST",
url: 'page2.php',
data: {NewID: id},
success: function(data) {
window.location.reload();
}
});
});
});

Remove # then replace with javascript:void(0):
<a href='javascript:void(0)' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
JS:
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
success: function() {
window.location.reload();
}
});
}

Related

How to make redirection with variable URL

I have a form on my page an there is a problem with PHP/JS redirect.
I have 3 conditions:
I can't use PHP "header location" to redirect because I need the page not to be refreshed on form submit, so I defined button type='button', NOT type='submit' and I'm using AJAX.
I can't define redirection URL in AJAX's "success", because the URL should be variable, depending on previous user's actions. So I need to define the URL in PHP.
I have to define URL only after user has clicked on the button on my page, not before.
The problem is, that JS doesn't see the URL defined in PHP, so redirection doesn't work (If I define the URL in AJAX's "success", then it works fine).
$(document).ready(function () {
$("#my_button").click(function () {
$.ajax({
type: 'POST',
url: 'file.php',
data: {check_button: '1', email: 'user#email.com'},
success: function(data){
//var url = "https://.................."; // THIS WORKS FINE!
var url = document.getElementById("my_url").value; // THIS DOESN'T WORK!
window.location.href=url;
}
});
});
});
// echo "<input type='hidden' id='my_url' value='https://................'/>"; // THIS WORKS FINE!
if (isset($_POST['check_button'])) {
echo "<input type='hidden' id='my_url' value='https://................'/>"; // THIS DOESN'T WORK!
// Do something
}
And I need to define the URL exactly in this statement. How can I do that?
Thanks for your help in advance.
Make the following change in PHP code :
if (isset($_POST['check_button']))
{
echo "https://................"; // URL you want
}
Then make the following change in Ajax code :
$.ajax({
type: 'POST',
url: 'file.php',
data: {check_button: '1', email: 'user#email.com'},
success: function(data)
{
window.location.href=data;
}
});

Reload an AJAX loaded page after update

I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.

Ajax link to run codeigniter controller then update html

Sorry for the most simplest of questions but I can't seem to get anything to work. It's the first time I've really played around with AJAX.
I'm developing in codeigniter and I have a link that when clicked runs the controller: photo function: like and allows the logged in user to like the photo then redirects the user back to the photo and displays a slightly different version of the button showing that the user likes the photo.
<?php if ( $like_count > '0' ) { echo $like_count; } ?>
It works fine but I thought it would be cool to replace it with an ajax function so it's more of a fluid motion instead of navigating off the page and then back again.
Any help would be greatly appreciated.
$(".uk-button").click(function(e) {
e.preventDefault();
//Here you can add your ajax
$.ajax({
url: site_url + 'photo/like',
data: {
liked : 1
},
type: 'POST',
dataType: 'json',
async : false,
success: function(success_record) {
console.log(success_record,":success_record");
//You might receive your like count from PHP here
}
});
});
In your success record you would get your PHP record values. Based on that you can increment or decrement count in success function
You can do something like this:
$(document).ready(function()
{
$('.likeLink').on('click', funciton()
{
var obj = $(this);
var id = obj.attr('id'); //anything you want to pass to update your like somewhere
$.ajax(
{
type: 'POST',
url: 'YourFilePathWhereYouWillDoTheLike',
data:
{
id: id,
},
cache: false,
success: function(response)
{
obj.html("You have liked this!");
}
});
return false;
})
})

How to send a JQuery Variable to another PHP page via dblclick()?

So guys, I made a listbox and if I dblclick to an item the value of it gets saved into "val", but I can't send it to the next PHP File. I also alerted "val" - the value is really saved in it. I also get the function succes displayed in the browser console. what to do?
thanks
My Function:
$(document).ready(function () {
$("option").dblclick(function () {
var lb = document.getElementById("liste");
var val = lb[lb.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'about.php',
dataType: 'HTML',
data: {
aufid: val
},
success: function (data) {}
});
});
});
PHP Code in about.php:
$id = $_POST['aufid'];
Can you try to see what variables are in the $_POST superglobal?
print_r($_POST);
try to set the url your full adrees
url: 'http://myadress.com/about.php',
java script is running on your local computer so it might send the request to you own pc where no about.php exist

My function only works with an alert after my ajax call

I'm populating a table with values from my database. I have included a delete icon in rows which can be deleted. The image has an onclick='deleteCat(id);' property, the id is taken from a json array trough a loop like so:
string = "<td align='center'><a href=''><img border='0' src='../images/Bullet-Delete.png' alt='delete' onclick='deleteCat("+json[i]['id']+");'/></a></td>";
This is my deleteCat function:
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
//$("#allecat").find("tr:gt(0)").remove();
//update_table();
}
});
//alert(id);
}
My function works when I put an alert after the ajax. The table refreshes and the row is removed from my db. However when I remove the alert my function does not work, the table is refreshed and the row is still present in the table and db.
Thanks in advance.
You need to prevent the default event for the click - ie the page is being reloaded each time you click on the image
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
$("#allecat").find("tr:gt(0)").remove();
update_table();
}
});
return false; // prevent the browser following the href
}
You will also need to change your html :
onclick='return deleteCat("+json[i]['id']+");
The alert() helps because that delays the processing of the remaining javascript in that function. The ajax send data asynchronously. async key is Default: true and should change it to false in your call till the client wait for end of ajax call.
e.g.:
$.ajax({
async:false,
url: "test.html",
.
.
});

Categories

Resources