Refresh div content on form submit (ajax) - php

On my page I have a form that inserts a new record in to the database. On the same page there is a DIV that contains the current resultset.
What I am trying to do is refresh just that DIV (not the whole page) when the form is submitted. The DIV will then contain the latest records (including the one just added).
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
});
return false;
});
<div id="current-rows">
<?php while($variant=mysql_fetch_array($variants)) { ?>
<div class="row">
// resultset
</div>
<?php } ?>
</div>
I set $variants from within my controller (beforehand):
$variants=Catalog::getProductVariants($product['id']);
Ideally I don't want to be returning a whole load of HTML to be injected in to that DIV.

Set the new content in the success handler of ajax request. Try this
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(newContent){
$('#current-rows').html(newContent);
}
});
return false;
});

I think it is easier to use .load method, which injects the response from the server to the given div, something like:
$('#idOfYourDiv').load('/your/url', {params: params});
alternatively you can still use $.ajax, like:
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(data) {
$('#yourDiv').html(data); // html will insert response, response is stored in "data" variable
}
});
return false;
});
on php site just echo what you want to be displayed, for example
foreach($results as $result){
echo $result."<br />";
}
hope that helps

I have put the contents of the "current-rows" div into it's own seperate view file:
<div id="current-rows">
<?php include("_current-rows.php"); ?>
</div>
And in my controller 'addvariants' action I just do this:
$variants=Catalog::getProductVariants($_POST['product_id']);
include('application/view/admin/catalog/_current-rows.php');
That is the response that is passed back to my jQuery success function.

Related

I have three div's, how to load data in only a particular div without reloading the complete page in php-codeigniter?

I have three div tags, on click of a link I want to load data in only the second div without loading the complete page, I want to keep the first and third div as static and second div should be dynamic?
<div class="first">
<?php echo $data->hospital_name;?>
</div>
<div class ="second">
//content//
<div>
<div class ="third">
//content//
<div>
You can achieve these by ajax.
1) As you want to apply dynamic data loading on some click event of some anchor link then please don't apply anchor link as:
"<?php echo $data->hospital_name;?>" the anchor leads you to the href value link. alternatively you can do like (<a href="javascript:void(0);">);
Now in your case for CI;
In view:
<?php echo $data->hospital_name;?>
In Js File
function changeData(parentVisitId){
var urlCI = 'patientLogin/patientVisit_details/'+parentVisitId;
$.ajax({
type: "GET",
url: urlCI,
data:{
'parenIdIfReq':parentVisitId,
},
success: function(response) {
if(response!=''){
$('.second').html(response);
}
else{
return false;
}
}
});
}
In controller/action i.e patientLogin/patientVisit_details/parentVisitedId
function patientVisit_details($parentVisiteId){
echo "whatever data you want to return as response";
}
Just try to return the values that you need from the ajax function.Something like this might do.Soppose you have a insert.php file,you may echo or return the data at the end of the function that needs to be populated into the page
$('.first a').click(function(){
$.ajax({
type: "POST",
url: "insert.php",
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('.second').html(data); //now the data is populated in the input field
}
});
})
For more info check this link

accepted ways of submitting and retrieving data using jquery ajax

what is the most accepted way of retrieving data without reloading, ive seen tutorials use echo encode_json(array), the tutorial im following doesnt use it, instead.. i think he opts to get the HTML area of a specific PHP page.
my index.php
$("#button").click(function() {
... some code here ....
$.ajax
({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'html',
cache: false,
success: function(html)
{
$("#posts").prepend(html);
$("#posts").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('content').focus();
}
});
});
Upon success, I want to retrieve the data from my MYSQL and print it on my #posts DIV.
my update.php includes
inserting data into mysql
selects/retrieve data from mysql
echoes the data from mysql_query
<?php
include("connect.php");
if (isset($_POST['submit']))
{
$status = $_POST['status']; //get textarea value
mysql_query("insert into messages (msg) values ('$status')");
}
$sql = mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$row = mysql_fetch_array($sql);
$msg = $row['msg'];
$msg_id = $row['msg_id'];
?>
<!-- get this part -->
<li id="posts">
id:<?php echo $msg_id; ?>
text: <?php echo $msg; ?>
</li>
basically, i just want to submit a post, and displays all the posts without reloading.
You are definitely on the right track.
However you are trying to insert something with an id="posts" into an element which is already on the page with the same ID which is not correct.
Perhaps make a wrapper div with a class of posts-container and then you can return say this from PHP:
<li class="post">
id:<?php echo $msg_id; ?>
text: <?php echo $msg; ?>
</li>
and add it to your page like this:
$.ajax
({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'html',
cache: false,
success: function(html)
{
$(".post-container").prepend(html);
$(".post-container").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('content').focus();
},
//adding an error function
error: function(error){
//do whatever you need to handle you error here
console.log(error);
}
});

jQuery AJAX refresh page content after success

I'm updating my database with jQuery .click() and then calling my AJAX; my question is once the SQL has ran what is the best way to refresh the content on the page so I'll be able to do the previous action again, currently I'm using window.location.reload(true); but I don't like that method because I don't want to have the page reloading all I want is for the content on the element I used to update it with to be to match the database field after the AJAX was successful
Here's my jQuery:
$(document).ready(function(){
$("span[class*='star']").click(function(){
var data = $(this).data('object');
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success: function(data){
if(data == false) {
window.location.reload(true);
} else {
window.location.reload(true);
}
}
});
console.log(data.art_featured);
});
});
PHP:
<section class="row">
<?php
$sql_categories = "SELECT art_id, art_featured FROM app_articles"
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row">
<div class="column one">
<?php if($row['art_featured']==0){
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star"></span>
<?php
} else if($row['art_featured']==1) {
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star-color"></span>
<?php
}
?>
</div>
</div>
<?php
}
} else {
echo "FAIL";
}
?>
</section>
EDIT:
I need to update the class .star or .star-color with art_featured depending on what the value of a art_featured is at the time, basically where ever I'm echoing out art_featured I need that to reload once the Ajax is successful.
EDIT:
$("span[class*='star']").click(function(){
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success:function(art_featured){
//remember $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object')),{
art_featured: art_featured
});
}
});
console.log(data.art_featured);
});
If you can just return art_featured after the MySQL database success, it'll send it back to the ajax success function. here, we can manipulate data, however, first we should store reference to the element that was clicked on.
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
Now in our success function, instead of using data just use art_featured because that's all we are returning. Now we can update the existing data object on the target.
success:function(art_featured){
//remmeber $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object'),{
art_featured: art_featured
}));
}
The above will extend the existing data object, allowing key:value pairs to be redefined based on the object we are extending.
You should find this working as intended.
I don't fully understand your question so let's assume the content you want to change is a div with class div, and you want to replace the content with the content just sent i.e. the data. Then you would need to return the data (probably using JSON would be easiest), then your call would be
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
for(n in data){
$('.div').append('<p>'+data[n]+'</p>');
}
}
});
Note addition of dataType return as being json, then iterating over the json data by for n in data, then using n to call the data from the array. So if the third item was name then you could do something like
$('.div').append('<p>Name is '+data[3]+'</p>');
You will have to return the data from the PHP form by json encoding it which can be done with the json_encode php function. If it's cross domain you'll have to use jsonp
EDIT:
If you already know the data you want to replace before you send the form (i.e. don't need a response) then you can just put those variables into the success call back. This will wait for the ajax to return successfully, then update your div.
So you could have this
var updateText = yourDataFromForm
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
$('.div').append('<p>'+updateText+'</p>');
}
});

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

jQuery write element just after the Ajax call

Hello I have a jQuery function that will send to a php file some info. The PHP file will do the stuff it has supposed to do and will generate some HTML code. I am fine until here.
The problem is that I have then to take the HTML results generated by this PHP file and write them in the page where the Ajax call has been created, simply by appending it after a DIV or inside a DIV or whatever.
This is the jQuery function I have so far:
$(document).ready(function() {
var idGenre = $("#txtGenre option:selected").val();
var html = $.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: "id=" + idGenre,
async: false
}).responseText;
});
The DIV that must be updated with the HTML results taken from the PHP file GetSubGenreData.php is:
<div id ="divSubGenre"></div>
Now lets say the PHP file will return a select box, something like this:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
etc...
</select>
This select box must be appended just after the DIV <div id ="divSubGenre"></div> or by simply replacing this DIV with the returned Select Box. Nothing impossible for a good jQuery developer. But I am not.
I just need the function to write the HTML results from the PHP file in the right DIV.
Thanks!!
in your success callback
success:function(html){
$("#divSubGenre").append(html);
}
if you want to replace the container div with the ajax response
success:function(html){
$("#divSubGenre").replaceWith(html);
}
if the div to which you are appending the results is not empty then to insert after the div use after
success:function(html){
$("#divSubGenre").after(html);
}
so your final code may look like this
$(document).ready(function() {
var idGenre = $("#txtGenre option:selected").val();
var html = $.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: {id:idGenre},
async: false,
success:function(html){
$("#divSubGenre").append(html);
}
});
});
jquery ajax
jquery replaceWith
jquery append
jquery after
update
$("#txtGenre").change(function(){
//get the update value here
var idGenre = $("#txtGenre option:selected").val();
$.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: {id:idGenre},
async: false,
success:function(html){
$("#divSubGenre").html(html);
}
});
});
jquery change
yet another update
about the comment to show the result on page load, if i have understood the scenario well you can have two divs on the page like
<div id="divSubGenre"></div>
<div id="divonLoad"></div>
on the page load do the ajax call and append the result to #divonLoad and in the success callback of your ajax call that is inside the change event handler do this
success:function(html){
$("#divonLoad").fadeOut("slow").remove(); removes the div that was holding the result on page load
$("#divSubGenre").html(html);
}
Add an HTML dataType and a success method to your AJAX call:
// No need to return the responseText as a variable
updateSelectHtml = function() {
$.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: "id=" + idGenre,
async: false,
// Make sure the return is formatted as html
dataType: "html",
success: function(data) {
// The return HTML data is appended after the div.
$("#divSubGenre").html(data);
}
});
};
// Bind the function to #txtGenre onchange
$("#txtGenre").change(updateSelectHtml);

Categories