Reload an AJAX loaded page after update - javascript

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.

Related

Ajax / Jquery refresh page after variables are passed

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();
}
});
}

How to pass form input field value to external page using jquery

I have a form where I would like to pass the value of an text input field to an external page without a form submit event. I would like to field value to become a php variable on the external page.
Here is what I have so far:
<script type="text/javascript">
jQuery(document).ready(function() {
$(function() {
cityField = $('#the_form input[id=city]');
$.ajax({
type: "POST",
url: "external.php",
data:{ city: cityfield },
success: function(data){
console.log(data);
}
});
});
});
</script>
Within the external.php page, I would like to declare the city form field value as a php variable as
$city = $_POST['city'];
To start with
jQuery(document).ready(function() {
and
$(function() {
are equivalent. The $(function() should be something like
$("input[type='button']").click(function() {
so that when you click the button, it runs the ajax request.
I cleaned up the code but the data is not being sent to external.php. It is being set but not posting. Here is my revised code
<script type="text/javascript">
$('#city').blur(function() {
var cityField = document.querySelector('#city').value;
$.ajax({
type: "post",
url: "external.php",
data: {'cityField': cityField },
dataType: "text",
success: function(data, status){
if(status=="success") {
alert("You typed: " + cityField);
}
}
});
});
I dont feel right posting an answer for a single change... But
EDIT: There are actually a few things...
<!-- For .click() -->
Click Me!
<script type="text/javascript">
// $(function() { // Trigger on page load
// $('#doStuff').click(function() { // Trigger on a click
$('#city').blur(function() { // Trigger when the focus on the field is lost (click away, tab to another field, ect)
// $('#city').change(function() { // Trigger when the fields value changes
var cityField = $('#city');
$.ajax({
type: "POST",
url: "external.php",
data:{ 'city': cityField.val() },
success: function(data){
console.log(data);
}
});
});
</script>
Changes:
You dont need jQuery(document).ready(function() {}) AND $(function(){ }). Its the same thing.
Its smart to put a var in front on your variables.
Case is important. cityField and cityfield are not the same thing
You were just sending the whole dom element to your external script. (which I assume you only wanted the contents of the input)
Also, you dont need to look for "an input, with an 'id' attribute , with a value of 'city'". Just look for #city
EDIT:
Your updated code (just putting it here so its easier to see):
<script type="text/javascript">
$('#city').blur(function() {
var cityField=$('#city').val();
$.ajax({
type:"post",
url:"autosuggest.php",
data:{'cityField':cityField },
dataType:"text",
complete:function(data, status) {
alert("You typed: "+cityField);
}
});
});
</script>
Your data will should be available in autosuggest.php as $_POST['cityField'];
Having a status check within the success function, is a little redundant, in my opinion.
It would be better to move the success:function(data,... to a complete:function(data,...

Unable to submit form with ajax without reloading parent

I am building a web application that will create a div on the page, use ajax to load a form into that div, and then have the form submitted without the parent page refreshing. I've read many examples on this site and others of how to do this, yet I'm puzzled why my proof-of-concept test is not working for me.
What successfully happens is that the parent page is creating the new div and is loading the form into the div. However, upon submitting the form, the parent page reloads. Using "Live HTTP Headers" in Opera, I can see that submitting the form is causing a GET rather than a POST, even though my Javascript is attempting to POST.
Can anyone help me understand why this is happening? Any help is very much appreciated.
Here is the code to the parent HTML page:
<html>
<head>
<script src=\"jquery-1.11.1.min.js\"></script>
<script src=\"jquery.min.js\"></script>
<script type=\"text/javascript\">
var num=1;
console.log('starting the code');
$(document).ready(function() {
console.log('document is ready');
$('#form1').submit(function(event) { // catch the form's submit event
console.log('form is going through submit');
$.ajax({ // create an AJAX call...
url: 'add_user.php', // the file to call
type: 'POST', // GET or POST
data: $('#form1').serialize(), // get the form data
success: function(data) { // on success..
$('#assign1').html(data); // update the DIV
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
event.preventDefault(); // cancel original event to prevent form submitting
});
});
function addToBox(divID) {
console.log('adding new assign to box');
var myNewDiv = document.createElement(\"div\");
myNewDivID = 'assign'+num;
myNewDiv.setAttribute('id', myNewDivID);
myNewDivID = '#'+myNewDivID;
var myBox = document.getElementById(divID);
myBox.appendChild(myNewDiv);
$.ajax({
type: 'GET',
url: 'add_user.php?id=1',
success: function(data) {
$(myNewDivID).html(data);
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
num+=1;
}
</script>
</head>
<body>
<div>
<div id=\"box1\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
<div>
<div id=\"box2\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
</body>
</html>
Here is the code to the PHP page (named add_user.php) with the form.
<?php
$n=0;
$id=$_GET['id'];
if ($_SERVER['REQUEST_METHOD']=="POST") {
echo "got the form!";
} else {
echo "<form id=\"form{$id}\"><select name=\"quantity\">\n";
for ($n=1;$n<=5;$n++) {
echo "<option value=\"answer{$n}\">option {$n}</option>\n";
}
echo "</select>\n<input type=\"submit\" /></form>";
}
?>
Thanks to the comment by A. Wolff, I replaced $('#form1').submit(function(event) { with $(document).on('submit','#form1', function(event){ and it worked.
Thanks A. Wolff!

showing velue from php file in div in html file

Basicly, In my html I have a form that consists of 2 selects and 2 text inputs. I would like to send values from that form into a php file called solve.php. This file will produce a variable called $cenaCelkom. I want to show the value of that variable in one of my divs.
I have to send tvalues from my form without redirecting to the solve.php. I have this for sending values to my php, but I cant find out if it works.
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "solve.php",
data: formdata
});
return false;
});
});
If this is ok, I would like to know how to get the value from my php after executing it. BTW: I am not an experienced js or jquery programmer, so please go easy on me :)
Thank you.
<div id="myresult"><div>
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function (e) {
e.preventDefault();
var formdata = $(this).serialize();
$.post('solve.php', $(this).serialize(), function(result){
$('#myresult').html(result);
});
});
});
You can grab the values of the inputs by using $_POST['inputnamehere'] from your solve.php page.
You can use $.load() method in jQuery
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
$( "#yourDivId" ).load(
'solve.php',
$('form').serialize(),
complete(responseText, textStatus, XMLHttpRequest){
//do whatever after ajax operation
}))
return false;
});
});
</script>
On solve.php simply get the values via $_GET and use print() for output:
<?php
print( $_GET['val1'] + $_GET['val2']) // Show a summation of two numbers
?>

CakePHP & JQuery, location.reload sometimes not working

Hi I am developing data deleting page with checkbox and button. After deletion, I'd like to display the message either the transaction is successful or not. Most of the time the message shows correctly, but sometimes the page reload doesn't happen and the message won't show until manually reloaded.
Now if it's not certain if the page is reloaded, is there any other way to show the message from the controller?
Here's the code:
(index.ctp)
<script type="text/javascript">
$(document).ready( function() {
$("#btn").click(function() {
var ids = '';
$('input[type="checkbox"]').each(function(){
if(this.checked){
ids = ids.concat(this.id).concat(',');
}else{
jAlert("Please choose items to delete");
}
});
if (ids != ''){
jConfirm('Delete?', 'Confirm',function(r){
if(r==true){
ht = $.ajax({
url: 'items/delete/'.concat(ids),
type: "POST",
contentType: "application/json; charset=utf-8",
});
location.reload(true);
}
});
}
});
});
</script>
(controller.php#function delete())
$this->Session->setFlash(__('Deleted!, true));
$this->redirect(array('action'=>'index'));
CakePHP's session flash is usually pretty reliable.
Perhaps your browser is not reliably doing a hard refresh with location.reload(true). Try window.location = window.location.href + "?nocache=" + new Date().getTime() to manually clear the cache and see if that helps at all.

Categories

Resources