jQuery AJAX refresh page content after success - php

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

Related

codeigniter update database using ajax then show

I would like this function:
After I select an option I want to update right away the database and then show it right away also inside a certain div. How can I achieve this?
Here's my HTML:
<select id="category1" name="cat1">
<option>Hardware</option>
<option>Software</option>
<option>Network</option>
</select>
AJAX code:
$('#category1').on('change',function(){
var data = $("cat1").val();
var ticket = '<?php echo $ticket_details[0]["cTicketNo"];?>';
if(data){
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo base_url();?>User/TicketView/update_cate",
data: {data: data,ticket: ticket},
success:function(response){
alert('successful');
},
error: function(response){
alert('tangina!');
}
});
}
});
Controller:
function update_cate(){
$this->TicketView_m->update_cat1();
redirect($_SERVER['HTTP_REFERER']);
}
Model:
function update_cat1(){
$ticket_id = $_POST['ticket'];
var_dump($cat = $_POST['data']);
$this->db->set('vCategory',$cat);
$this->db->where('cTicketNo',$ticket_id);
$this->db->update('tconcerns');
}
THanks for all the help!
Drop that redirect($_SERVER['HTTP_REFERER']);, You don't need that.
First of all, AJAX will allow you to send data to server without redirecting to another page.
Based on your AJAX dataType. It is JSON. So for you to get the result, You have to encode it to JSON like json_encode(['result' => 'things you want to show']).
Then you can access it in your response like this:
success:function(response){
alert('successful');
var res = response.result; //Access the JSON
$("#certainDiv").html( res ); //Print to the div you want
}
And it is also better to get the post request in your controller then pass it to your model:
function update_cate(){
$ticket_id = $this->input->post('ticket');
$cat1 = $this->input->post('cat1');
$this->TicketView_m->update_cat1($ticket_id, $cat1);
echo json_encode(['result' => 'things you want to show']);
}

Ajax call json undefined Object : object

the json value keeps returning unidentified or it doesnt display at all
PHP CODE
$index=0;
while($row = $result->fetch_array()){
$index++;
$data=array(
array(
$index=>$row['menuName']
)
);
}
echo json_encode($data);
}
JQUERY AJAX
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
$('.navbar ul').append('<li>'+data[0]+'</li>');
}
}); //ajax request
});
</script>
The json is fine it displays in the right format. When i change my jquery to data[0] it displays object Object and if i do data[1 or higher] it gives me undefined. I dont know what im doing wrong i even tried it do this: data[0].1 and it displays nothing.
Any help will be appreciated.
First thing to do is to fix the PHP script part which responds to the request.
Create a valid JSON string response. The simpliest way is first to create a container (an array).
Then second is the to continually push fetched rows in there. Then finally use json_encode in the end.
Don't encode while inside the loop:
Simple example:
// initialize container
$data = array();
// the pushing of rows
while($row = $result->fetch_array()) {
$data[] = $row; // push the whole row
}
// finally, echo it to into a JSON string
echo json_encode($data);
// don't put me inside the WHILE
PHP Note: If this is mysqli, I'd suggest use the ->fetch_assoc() instead or just simply ->fetch_array(MYSQLI_ASSOC) flag.
In your AJAX script, just handle the response as you normally would:
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
// every each row, create an LI element with an anchor
$.each(data, function(index, element){
$('.navbar ul').append('<li>'+element.menuName+'</li>');
// just use the column names as the properties in your data response that came from PHP
});
}
});
});
</script>
If this runs, this should yield something into a markup like this:
<li>
Table1
</li>
<li>
Table2
</li>
<li>
Table4
</li>

How to pass JS object to PHP function

$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'<?php echo site_url($this->config->item('admin_folder').'/catalog/get_all_option');?>',
type:'POST',
data:{category_id:1},
dataType: 'json',
success:function(data){
$('#attribute_form').html('<?php add_attribute_form("'+data+'");?>');
}
});
}
});
on callback function success return the data and pass it to add_attribute_form(data) php function but nothing response.
what is the correct way to pass js object to php function
What you will need to do here is, use Ajax to send data to a separate php page passing it some information, then, based on that information, the php page should return data to the Ajax callback function which will add the returned data to the original page.
Here's a simple example (and a working demo here):
In index.html do this:
<script>
$(document).ready(function(){
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'somepage.php',
type:'POST',
data:{category_id:1},
dataType: 'json', // this setting means you expect the server to return json formatted data
// this is important because if the data you get back is not valid json,
// the success callback below will not be called,
// the error callback will be called instead
success:function(response){
$('#attribute_form').html(response.html);
// if not using json, this would just be $('#attribute_form').html(response);
},
error:function(xhr, status, error){
// handel error
}
});
}
});
});
</script>
<input type="checkbox" class="select_category"> Check this box
<div id="attribute_form"></div>
Then in somepage.php do the following:
<?php
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
if($category_id == '1'){
echo json_encode(array('html'=>'<h1>This text came from the php page</h1>'));
exit;
// if you are not using dataType:json in your ajax, you can just do:
// echo '<h1>This text came from the php page</h1>';
// exit;
}
?>

Show/hide div with jQuery and AJAX not working properly

I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)

How can I add the content of a page in a div with Ajax?

I have a list in my site, and when I click each of the list items, I want the div next to them to reload with ajax, so as not to reload the whole page.
Here is my javascript
parameters = "category_id="+categoryId;
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
The ajaxFunction() function is the regular $.ajax() jQuery function, with "POST". In the "changeCategory.php" I call with include another php file.
The problem is that the whole page is reloaded instead of only the div. I want to use this ajax function I have, cause I want to send data to my php file.
Does anyone know what should I do to reload only the div?
Thanks in advance
Try this
$(document).ready(function(){
var parameters = {category_id:categoryId};
$.ajax({
url:'changeCategory.php',
type:'post',
data:parameters,
dataType:'html',
success:function(result){
$("#mydiv").html(result);
},
error:function(){
alert('Error in loading [itemid]...');
}
});
});
Also verify that when in your click event this line is written or not return false; This is required.
Try using load to load the div with the url contents -
$("#mydiv").load("changeCategory.php", {category_id: "category_id_value"} );
You can pass data to the url.
The POST method is used if data is provided as an object; otherwise, GET is assumed.
you could send a query to that PHP so it "understands" that it needs to output only the div, like this:
in your javascript:
//add the query here
parameters = "category_id="+categoryId + "&type=divonly";
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
in your "changeCategory.php":
//add a query check:
$type = "";
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
//then, depending on the type, output only the div:
if($type === "divonly"){
//output the div only;
} else {
//your normal page
}
$(document).ready(function() {
$.ajax({
url: "right.php",
type: "POST",
data: {},
cache: false,
success: function (response) {
$('#right_description').html(response);
}
});
});
The whole page is reloaded that means there may be an error in your javascript code
check it again
or try this one
function name_of_your_function(id)
{
var html = $.ajax({
type: "GET",
url: "ajax_main_sectors.php",
data: "sec="+id,
async: false
}).responseText;
document.getElementById("your div id").innerHTML=html;
}
you can use get method or post method....

Categories