How to refresh div without refreshing whole page? - javascript

I have a PHP file particular.php which have menu to serve sub pages. Once I click on a menu it loads page which I asked for without refreshing the main page i.e particular.php. Once the sub-page is loaded I create a SESSION which will store current page.
Following are codes I tried and seems no refreshing menu div.
echo '<footer id="ajaxmenu">';
echo '<ul>'
if ( $_SESSION["ajax_show"] == 'result') {
echo "<li style='text-decoration: underline;'>";
} else {
echo '<li>';
}
echo "Academic</li>";
echo '</ul>';
echo '</footer>';
}
JQuery ajax.
function result(year) {
var year = year.value;
$.ajax ({
type: "POST",
url: "result.php",
data: { year: year},
success: function(data),
$("#result").html(data);
}
});
$("#ajaxmenu").load("#ajaxmenu");
return false;
}
In Nutsheell, When I click on menu, I want #ajaxmenu to be refresh without loading whole page.

In your AJAX success replace $("#result").html(data); with $("#ajaxmenu").html(data). As for now it seems like you are loading your data response in the wrong container - nothing of id="response" in your code.
Also, it might lead to nesting <footer> tags inside each other, so you should bear that in mind as you prepare the HTML.

Related

Modifying AJAX from insert to update if modal is clicked again

I've built a CMS that uses bootstrap Modals within div areas so that when the user clicks on the div where they want to insert content, a modal comes up with a tinyMCE text editor area where they can put images or text. Once they have, they hit the save button in the modal which closes the modal and shows the preview of what they just did.
Also, when they hit the save button, I perform an AJAX request that calls an addPanel.php script in order to insert a record for that panel, panel type and content.
THis works perfectly except for the fact that if they click on the modal again and do this all over to edit their content, it just saves another panel.
I need to slightly modify what I"m doing now to either:
Get the ID of the panel that was created on the last ajax request and now perform a mysql update on the record for the content (as the panel ID and panel type will remain the same)
Keep the current process but set the last panel's 'active' column in mysql to '0' (not as big a fan of this approach but will accept it).
Basically, what I have works but if the user clicks on the modal anymore after the first time, I would be updating instead of inserting.
Here is the mysql being performed in addPanel.php:
$content = $_POST['page_content'];
$addContent = "
INSERT INTO content(content)
VALUES('$content');
";
if ($mysqlConn->query($addContent) === TRUE) {
$cont_id = $mysqlConn->insert_id;
$data['last_insert_id'] = $cont_id;
echo json_encode($data);
} else {
echo "Error: " . $addContent . "<br>" . $mysqlConn->error;
}
$panelID = $_POST['panel_type'];
$pageID = $_POST['page_id'];
$addPanel = "
INSERT INTO panels(panel_type_id, page_id, cont_id)
VALUES ('$panelID', '$pageID', '$cont_id');
";
if ($mysqlConn->query($addPanel) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $addPanel . "<br>" . $mysqlConn->error;
}
And the script/AJAX to show an example of what I'm doing currently for a panel:
<script type="text/javascript">
$("#leftHalfForm").submit(function(e){
var leftContentVar = tinymce.get("leftHalfTextArea").getContent();
$(".leftContent").html(leftContentVar);
$("#leftHalfPageContent").val(leftContentVar);
// jQuery.noConflict();
var string = $('#leftHalfForm').serialize() + '&page_id=' + page_id;
console.log(string);
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "addPanel.php",
data: string,
cache: false,
success: function(response){
console.log(JSON.stringify(response));
console.log(string);
$('#leftFiftyModal').modal('hide');
$('.modal-backdrop').remove();
}
});
return false;
});

Passing Javascript variable to PHP and then reloading page without refresh

How do you reload a page without re-fresh after sending a javascript variable to PHP via Ajax.
Below is an image of a webpage I'm creating which analyses asset performance.
What I'm trying to do is the following.
When a user selects a test block with in the graph, the selcection box is updated with all subtests within that specific test block. However, I do not want to refresh the page. I have managed to send the the selected tested block to the PHP code via ajax, but can not get ajax to reload the page without a refresh.
Currently, when a test block is selected, the label is return to PHP and is stored in the $_SESSION['label'] variable. This is then used in the panel header #subtest-chart-select. However the label will not update without a page refresh which is what I want to avoid.
Ajax:
$("#test_block_chart").click(
function(evt){
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
//alert(label);
$.ajax(
{
url:'test_performance.php',
type: 'POST',
datatype: 'json',
data: {'label':label}, // post to location.php
success: function(label) {
// success
},
error: function(label) {
alert("There may an error on uploading. Try again later");
}
});
}
});
});`
PHP:
session_start();
if(isset($_POST['label']))
{
$_SESSION['label'] = $_POST['label'];
}
PHP echo HTML
<?php
echo '<div class="row">
<div class="col-lg-12 subtest-select">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i>' . $_SESSION['label'] . ' Subtest Select </h3>
</div>
<select class="form-control">
<option>1</option>
</select>
</div>
</div>
</div>'
?>
I'm still to write the PHP code to update the options of subtests within the selected test block.
Any help will be greatly appreciated as I've been trying to get this working for what seems like forever.
In $.ajax() set
dataType: 'text',
In your $.ajax() success function say:
success: function(data) {
$('.inside_whereever_you_want_to_show_this').html(data);
}
Edit:
To update only one value on page you can:
a) in PHP print out only this value (so that whole page would be only this value).
<?php echo $_SESSION['label']
and in HTML put a span around the bit you want to update (avoid constructing longer strings in javascript, all constant parts should be in HTML)
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i><span class="subtest-updateable">' . $_SESSION['label'] . '</span> Subtest Select </h3>
then you can update only your needed bit with whole response
success: function(data) {
$('.subtest-updateable').html(data);
}
b) better (in systematic approach means) would be use json response, where you can return more isolated variables as well:
Set dataType to json.
Success function would use $('.subtest-updateable').html(data.label)
In PHP print json_encode(array('label' => $_SESSION['label'], 'someelse' => $someother_variable ))
You still should put span (or some other html element) around updateable bits of your page (to avoid writing constants into your javascript)
In your success function you need to update the part of the DOM that you want to change. On the PHP side just return your blade partial or whatever HTML you want to display.
$(document).on('submit', 'form#form-grad', function (e) {
e.preventDefault();
var context = $(this);
var thisForm = context.closest('form');
$.ajax({
url: thisForm.attr('action'),
method: 'PUT',
data: thisForm.serialize(),
success: function (response) {
$('#updatearea').html(response.pt_html);
// Close grading form
}
});
return false;
});

Store Ajax div content in a PHP variable

I have a problem with variables. I have a website using only Jquery which means that that I use #p1, #p02, ..., to navigate from one page to another.
I made an Ajax call which prints an id that I need in order to view my content. This id is printed in a div. The problem is that when I store the div in a variable like this:
$variable="<div class='something'></div>";
I can echo the variable but CAN'T use it in order to make queries. I know this is but programming but if I use sessions instead the identity didn't updated at all from page to page because of the using of #p01 instead of p1.php.
I also added the ajax.js file if this help you in order to advise me. The ajax.js file sends an identity to Ajax_page.php then I store this $_POST variable in a SESSION and then I echo this varible in Ajax_page.php. When i echo this variable it also printed in the div which is in the Show_content_page.php. I want the contents of that div. I want to use this div contents(identity) in order to make my php queries. Thats all.
Is there any way to make the $variable useful?
Here are the to sample files
Ajax_page.php
<?php
session_start();
if(!empty($_POST['show_an_anetoix']) ){
$_SESSION['anetoix_id']=$_POST['show_an_anetoix'];
}
echo $_SESSION['anetoix_id'];
?>
Show_content_page.php
<div id="p1" >
<?php
$variable="<div class='something'></div>";
echo $variable; //no problem
function_test($variable); //problem
?>
</div>
The ajax.js
/* Pass data with changePage */
$(document).on("pageinit", "#p1", function () {
$(document).on('click', '.anetoix_class', function(){
$.mobile.pageContainer.pagecontainer("change", "#p02", {
stuff: this.id,
transition: "flip"
});
});
});
/* retrieve data and run function to add elements */
$(document).on("pagebeforechange", function (e, data) {
if (data.toPage[0].id == "p02") {
var stuff = data.options.stuff;
var data = {"show_an_anetoix": stuff,};
$.ajax({
type: "POST",
url: "../show_an_anetoix.php",
data: data,
success: function(response)
{$(".show_an_anetoix").html(response);}
});
}
});
Not 100% sure what you mean. Are you asking, can you use a PHP variable in ajax? If so, I would do something like this:
<script>
$ajax_variable = "<?php echo $php_variable; ?>";
</script>

jQuery UI tabs refresh content after submitting form

I'm using jQuery UI tabs loading an external form in the tabs. The form is set to submit when the checkbox in the form is clicked on. The form is submitted using ajax. What I'm searching an answer for, is to refresh the tab content after submitting the form, but I haven't had any luck finding the answer.
$(function() {
$("#tabs").tabs({
cache: true,
beforeLoad: function( event, ui ) {
ui.jqXHR.error(function() {
ui.panel.html("Can't load content. Please call support.");
});
if(!($.data(ui.tab[0], "cache.tabs"))) {
return $(ui.panel).html("<div align='center'><img src='images/loader.gif'><p><strong>Loading...</strong></p></div>");
}
}
}); });
The tabs are generated using PHP loading variables from a DB:
<div id="tabs">
<ul>
<?php
$sql = mysql_query("SELECT username, name FROM members ORDER BY username") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
echo "<li><a href='tasks.php?user=" . $row['username'] . "'>" . $row['name'] . "</a></li>\n";
}
?>
</ul>
</div>
The form is in the file tasks.php and the submit script is:
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "update-task.php",
data: $("#form1").serialize()
}); });
It works perfect. When clicking on checkboxes with the class ".checkbox", the form is submitted and the database is updated. But I would like to have the text in the tab to have a different color and the list resorted so that the checked items are moved to the bottom when the form is submitted (I planned to do this on the serverside using PHP). For this I need the content in the tab to be refreshed, but I don't know how. Best guess is to add this in the ajax form submit:
success: function() {
// Something that refreshes tab content
}
But I have no clue to what to do. Any ideas?
/Carl
Try this:
success: function() {
var tabId = $("#tabs").tabs("option", "active");
$("#tabs").tabs("option", "active", tabId);
}
Can't use the refresh method?
$( "#tabs" ).tabs( "refresh" );
http://api.jqueryui.com/tabs/#method-refresh
That said, I'm not sure why you need to refresh in order to change font colors. Seems like you'd just do that directly in your success function:
success: function() {
$('.my-selector').css('color', 'orange');
}

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

Categories

Resources