jQuery UI tabs refresh content after submitting form - javascript

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

Related

"Like" system PHP, using AJAX

i want to make like/unlike system with PHP and jQuery/AJAX..
Here is my form in PHP foreach... Here i have own id's for every form;
<?php foreach ($vid as $var) { ?>
<form class="classform" action="functions/videolike.php" method="post">
<input type="text" name="id" value="<?php echo $var['video_id'];?>">
<button class="submitbuttonclass"type="submit">Like</button>
</form>
<?php } ?>
Here is my Ajax script;
<script>
// this is the id of the submit button
$(".submitbuttonclass").click(function() {
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: $(".classform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
the codes are working but not correctly;
When i click "like" button is working good, i cheked the database, caunting, inserting, deleting , working good...
But I want to make this with AJAX becouse, refreshing page is stopping the video when user watching video if he click the like button. Video is preloading becouse page refresh...
After i add my ajax script its working. But when i am clicking the like button, AJAX is posting to PHP, only the last id in the foreach loop,
THE Question?
How to make AJAX to get all of the id's in PHP foreach loop ??
And this is my videolike.php if you want to check;
<?php
session_start();
if($_POST['id'] && #$_SESSION["userid"]){
require_once "connectdb.php";
$id = $_POST["id"];
$VLcheck = "SELECT count(*) FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
$VLrow = $reslike->fetchColumn();
echo $VLrow;
if ($VLrow > 0){
$VLcheck = "DELETE FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
} else {
$curentsess= $_SESSION["userid"];
$INSlike = $conn->prepare("INSERT INTO videolikes(user_id, liked_vid_id)
VALUES('$curentsess','$id')");
$INSlike->execute();
}} else {die;}
?>
As you have a lot forms with class .classform, so how do you think your script should select the proper one?
The asnwer is - script can't, you should help it). Use .closest function to find closest <form> for a clicked button:
$(".submitbuttonclass").click(function() {
var form = $(this).closest("form");
// or find closest element with class `classform`
//var form = $(this).closest(".classform");
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

AJAX call not working - PHP, MySQL, jQuery/Ajax

I have the following problem:
What i'm trying to accomplish is:
User clicks on a submit/image type button
Ajax call handles the submit, calls another PHP script to update a record in a MySQL table, all without reloading the page ( obviously )
My PHP code is working fine without the AJAX, as it will reload and update the record. but somehow the ajax call is not working and/or returning any error.
My code:
$(function() {
$('#like_form').submit(function(event) {
event.preventDefault(); // Preventing default submit button
var formEl = $('#like_form');
var submitButton = $('input[type=submit]', formEl);
$.ajax({
async: true,
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
$("#like").fadeOut();
$("#like").fadeIn();
});
});
});
<!-- LIKE een gebruiker -->
<form action="" id="like_form" method='POST' enctype="multipart/form-data">
<input onmouseover="this.src='img/heart2.png'" onmouseout="this.src='img/heart.png'" name='like' id="like" src='img/heart.png' type="image" />
</form>
my PHP (just in case):
<?php
include_once "dbconnection.php";
//if like button (submit button) clicked
if ($_POST){
$conn = DatabaseConnection::getConnection();
$sql = "UPDATE dating_members
SET likes = likes + 1
WHERE member_id = 3";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
I figured out what the problem is, Kind of silly I didn't notice but better late than never.
I had to 'include' the JS script at the end of my PHP page in order to catch my onsubmit function and therefore disable the default event a.k.a submit button submitting my form and page reload / POSTs to the other PHP file.
Everything is working fine now

How to refresh div without refreshing whole page?

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.

How to use Ajax to update a second selectbox in jquery using the first selectbox's value?

First off, I'm using wordpress, and the goal is to choose a dropdown selectmenu item, structured in jquery, to choose a parent category. This choice then updates the second select menu with the sub-categories of the parent.
So far, I have this ajax:
<script>
$(function(){
$( "#categories" )
.selectmenu({
select: function getval() {
var parent = $("#categories").val();
$.ajax({
url: "ajax.php",
data: { parent : parent },
type: "POST",
success: success: function(response){
$(".sub_cat").html(response);
},
error: function() {
alert("Error, possible missing file.");
}
}); //End of ajax
alert(parent);
} //End of getval
}) //End selectMenu
.selectmenu( "menuWidget" )
.addClass( "overflow" );
$( "#sub_cats" )
.selectmenu()
.selectmenu( "menuWidget" )
.addClass( "overflow" );
var categories = $('#categories');
var subcats = $('#sub_cats');
});
</script>
This is the HTML that will be populated:
<fieldset>
<div class=sub_cat>
</div>
</fieldset>
And This is ajax.php:
<?php
$parent = $_POST['parent'];
$subcats = get_categories("child_of=$parent");
$parent = "<label for="sub_cats">Select a Sub-category</label>
<select name="sub_cats" id="sub_cats">
<option selected="selected">Pick a Sub-Category</option>" .
foreach($subcats as $subcat) {
"<option value=" echo $subcat->name ">" . echo $subcat->name . "</option>"
} .
"</select>"
?>
The menus come in as they should, the alerts come in and the parent category is always sent to the ajax when the choice is made. But the success alert is never touched and I have no idea what I'm supposed to put in the ajax.php file. My guess would be to use that file to get the sub-cats in php, and then send it in json format, but I don't know how.
Absolutely any help is appreciated, I've been struggling with this for a while.
I've tried the solutions from below but I never get any code or value back from ajax.php with any of their answers. Thats where it stops. I also don't know how to populate the next selectbox with the new item. Pretend Im a super ignorant programmer who doesn't know a thing about these structures and explain from that standpoint, that might help I hope.
In the ajax.php file ... do this ...
$parent = $_POST['parent'];
// Query the subcategories using parent ..
// then loop and create select box ...
Then the change the ajax success like below ... and fill the data to subcatogory div
success: function(response){
$(".subcat-div").html(response);
}
The simple way is in change event in your #categories
this must send a request to server and response in html format refreshes #sub_cats
Let us see:
//in your js
$(document).ready(function(){
$("#categories").change(function(){
//here we get corrent selected id
//form categories in corrent selected option
var id = $(this).val();
//simple ajax request $.post
$.post("ajax.php",{
id:id
},function(data){
$("#sub_cats").empty()
$("#sub_cats").append(data)
},"html")
});
}
//
On ajax.php your return must be in Html
... your query above end fetching result:
while($sub = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<option value='".$sub['id']."'>".$sub['name']."</option>";
}
Check it out.

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