If I add caption to image it's working, if I add one more caption without refreshing the page the 1st value is posting to the second one...
$(document).ready(function () {
$(".cap_btn").click(function(){
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
$.ajax({
type: "POST",
url: "addcap.php",
data: { id: li.data("imageId"), "cap": cap},
success: function(data){
alert("Caption Added");
},
error: function(){
alert("failure");
}
});
});
});
php code:
if(isset($_POST['id'])){
$ids = $_POST['id'];
$cap = $_POST['cap'];
try
{
$query = "UPDATE image SET caption='$cap' WHERE id='$ids'";
$sql=$con->prepare($query);
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
You can do it like this
$(document).ready(function () {
$(".cap_btn").click(
function()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
alert("Caption Added");
}
else
{
alert("failure");
}
};
xmlhttp.open("POST", "addcap.php", true);
var formdata = new FormData();
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
formdata.append("id",li.data("imageId"));
formdata.append("cap",li.data("cap"));
xmlhttp.send(formdata);
});
});
Hope it helps :)
Related
I want to call a jQuery function that acts upon a form in AJAX response.
How do I do it???
jQuery Function
$(document).ready(function (e) {
$("#load_timetable").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "load_timetable.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#time_table").html(data);
},
error: function() {}
});
});
});
Another AJAX Function
$(document).on("click", ".open-viewFacultyDialog", function () {
var uid = $(this).data('id');
$('#update').click(function() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) {
**//I would like to call JQUERY here**
document.getElementById("update_action_response").innerHTML = "";
var ajaxDisplay = document.getElementById('update_action_response');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var dept_slot = document.getElementById('dept_slot').value;
var subject = document.getElementById('subject').value;
var faculty1 = document.getElementById('faculty1').value;
var faculty2 = document.getElementById('faculty2').value;
var faculty3 = document.getElementById('faculty3').value;
var queryString="?id="+uid+"&dept_slot="+dept_slot+"&subject="+subject+"&faculty1="+faculty1+"&faculty2="+faculty2+"&faculty3="+faculty3;
ajaxRequest.open("GET", "update_timetable.php"+queryString, true);
ajaxRequest.send(null);
});
});
In simple I would like to reload the contents after updation without page reload by submitting the same parameters that are used to load the contents before update.
Use Promise method which is already defined in jquery.you can use it if data transfer successfully. such that if promise returns true then perform this task.else other task.
I'm hoping someone can help me...
Basically, neither if (data.status=='error') { or } else if (data.status=='success') { appear to be getting called yet the data is being inserted into the database fine.
add_alarm_code.php;
<?php
require_once('../inc/config.php');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// define and escape each POST as a variable
foreach ($_POST as $key => $value) {
if (!empty($value)) {
${$key} = mysqli_real_escape_string($con, $value);
}
}
// insert data into database
$sql="INSERT INTO alarm_code (
alarm_code_property,
alarm_code_code,
alarm_code_notes,
alarm_code_date_added
)
VALUES (
'$alarm_code_property',
'$alarm_code_code',
'$alarm_code_notes',
'" . date('Y-m-d') . "'
)";
if (!mysqli_query($con,$sql)) {
echo '{ "status": "error", "message": "Error Inserting Alarm Code Data into Database: ' . mysqli_error($con) . '" }';
} else {
echo '{ "status": "success", "message": "The alarm code has successfully been added to the system. The page will now refresh." }';
}
mysqli_close($con);
?>
jQuery on view_property.php;
// add alarm code submit form
$('#add_alarm_code').ajaxForm({
dataType: 'json',
success: processJson,
error: function (xmlRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
function processJson(data) {
if (data.status=='error') {
alert('Error 1');
$('#ajax_form_status_alarm_code').removeClass('green_background')
$('#ajax_form_status_alarm_code').addClass('red_background')
$('#ajax_form_status_alarm_code').html(data.message);
alert('Error 2');
} else if (data.status=='success') {
$('#add_alarm_code').clearForm();
$('#ajax_form_status_alarm_code').removeClass('red_background')
$('#ajax_form_status_alarm_code').addClass('green_background')
$('#ajax_form_status_alarm_code').html(data.message);
setTimeout(function() {
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#keys";
location.reload(true);
}
}, 3000);
}
}
form on view_property.php (the form is in a hidden div as it loads in a fancybox/lightbox)
echo '<div style="display:none">';
echo '<form id="add_alarm_code" action="' . SITE_AJAX . 'add_alarm_code.php" method="post">';
echo '<input type="hidden" id="alarm_code_property" name="alarm_code_property" value="' . $property_id . '">';
echo '<fieldset><legend>Add an Alarm Code</legend>
<table class="nobord">';
echo '<tr><td><label for="alarm_code_code">Alarm Code:</label></td>
<td><input type="text" id="alarm_code_code" name="alarm_code_code" maxlength="10" required></td></tr>';
echo '<tr><td><label for="alarm_code_notes">Notes:</label></td>
<td><textarea id="alarm_code_notes" name="alarm_code_notes" rows="6" cols="35"></textarea></td></tr>';
echo '<tr><td colspan="2"><input type="submit" value="Save"></td></tr>';
echo '</table>';
echo '<div id="ajax_form_status_alarm_code" class="ajax_form_status"></div>';
echo '</fieldset></form>';
echo '</div>';
entire jQuery on view_property.php (in case it helps find a bug!);
<script>
$(document).ready(function() {
// tab functionality on load
$(function(e) {
// define variables
var currentAttrValue = window.location.hash;
if (currentAttrValue!='') {
// show/hide tabs
jQuery('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();
// change/remove current tab to active
jQuery(currentAttrValue).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
}
});
// tab functionality on click
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// show/hide tabs
jQuery('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();
// change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
// fancybox
$(".fancybox").fancybox({
closeBtn : true,
modal : false
});
// apply validation
$( "#add_certificate" ).validate({
errorClass: "error-class",
});
$( "#add_keys" ).validate({
errorClass: "error-class",
});
$( "#add_alarm_code" ).validate({
errorClass: "error-class",
});
// add certificate submit form
$('#add_certificate').ajaxForm({
dataType: 'json',
success: processJson,
});
function processJson(data) {
if (data.status=='error') {
$('#ajax_form_status_certificate').removeClass('green_background')
$('#ajax_form_status_certificate').addClass('red_background')
$('#ajax_form_status_certificate').html(data.message);
} else if (data.status=='success') {
$('#add_certificate').clearForm();
$('#ajax_form_status_certificate').removeClass('red_background')
$('#ajax_form_status_certificate').addClass('green_background')
$('#ajax_form_status_certificate').html(data.message);
setTimeout(function(){
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#certificates";
location.reload(true);
}
}, 3000);
}
}
$( "#add_1_year" ).click(function() {
if ($('#certificate_start_date').val()!='') {
var expiry_date = moment($('#certificate_start_date').val()).add(1, 'year').format("YYYY-MM-DD");
$('#certificate_expiry_date').val(expiry_date);
} else {
alert('Please enter the certificate start date.');
}
});
// add alarm code submit form
$('#add_alarm_code').ajaxForm({
dataType: 'json',
success: processJson,
error: function (xmlRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
function processJson(data) {
if (data.status=='error') {
alert('Error 1');
$('#ajax_form_status_alarm_code').removeClass('green_background')
$('#ajax_form_status_alarm_code').addClass('red_background')
$('#ajax_form_status_alarm_code').html(data.message);
alert('Error 2');
} else if (data.status=='success') {
$('#add_alarm_code').clearForm();
$('#ajax_form_status_alarm_code').removeClass('red_background')
$('#ajax_form_status_alarm_code').addClass('green_background')
$('#ajax_form_status_alarm_code').html(data.message);
setTimeout(function() {
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#keys";
location.reload(true);
}
}, 3000);
}
}
// add keys submit form
$('#add_keys').ajaxForm({
dataType: 'json',
success: processJson,
});
function processJson(data) {
if (data.status=='error') {
$('#ajax_form_status_keys').removeClass('green_background')
$('#ajax_form_status_keys').addClass('red_background')
$('#ajax_form_status_keys').html(data.message);
} else if (data.status=='success') {
$('#add_keys').clearForm();
$('#ajax_form_status_keys').removeClass('red_background')
$('#ajax_form_status_keys').addClass('green_background')
$('#ajax_form_status_keys').html(data.message);
setTimeout(function(){
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#keys";
location.reload(true);
}
}, 3000);
}
}
});
</script>
ajax function
<script type="text/javascript">
var timeOutID =0;
var checkScores = function () {
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/countScoreCh',
success: function(response) {
if(response == false){
timeOutID = setTimeout(checkScores, 3000);
} else {
jsn = JSON.parse(response);
score= jsn.scoreCH;
$('#progressbar').progressbar({
value: score
});
clearTimeout(timeOutID);
}
}
});
}
timeOutID = setTimeout(checkScores,1000);
</script>
Controller
public function countScoreCh(){
$id = $this->session->userdata('userID');
$data['getScore'] = $this->lawmodel->battleUserID($id);
foreach($data['getScore'] as $row){
$scoreCH = $row->challengerScore;
echo json_encode(array('scoreCH' => $scoreCH));
}
}
Im having a problem..im using a progress bar..my idea is making the progress bar like a Hit Point/Health bar..but it seems that when i put the $('#progressbar').progressbar it will not get the value from jsn.scoreCH..jst disregards the response == false it still working i tried using console log..But when i put this code..it will not be read and display the output..
$('#progressbar').progressbar({
value: score
});
You can omit JSON.parse(response). Just use dataType: 'json'
$.ajax({
url: "http://127.0.0.1/ProgVsProg/main/countScoreCh",
dataType: 'json'
success: function(response) {
if(response.scoreCH == undefined){
timeOutID = setTimeout(checkScores, 3000);
} else {
$('#progressbar').progressbar({
value: response.scoreCH
});
clearTimeout(timeOutID);
}
}
});
I can't get the content from a div (width a specific ID) from single.php into index.php with ajax.
Now I have this code and returns nothing - "0".
function loadcontent(type,id,slug, action) {
jQuery.ajax({
type:'POST',
url:srvars.ajaxurl,
data: {
action:'sr_get_content',
id:id,
type:type
},
success: function(response) {
if ($(window).width() > 768) {
$('#content .content-inner').hide();
$('#content .content-inner').html(response);
initialise('#content');
}
var checkwidth = $('.maincontent').width();
$('#loading').delay(1000).fadeOut(fadeInOutSpeed, function(){
if ($(window).width() > 768) {
if (checkwidth > 0) {
reorganizeIsotope('.masonry');
$('#content .content-inner').fadeIn(fadeInOutSpeed, function() { resize_jplayer(); reorganizeIsotope('.masonry'); });
} else {
$('.mainside').animate({'width':srvars.asidewidth+'%'}, animationSpeed, $easingType);
$('.mainside-bg').animate({'width':srvars.asidewidth+'%'}, animationSpeed, $easingType);
$('.maincontent').animate({'width':srvars.contentwidth+'%'}, animationSpeed, $easingType, function() {
reorganizeIsotope('.masonry');
$('#content .content-inner').fadeIn(fadeInOutSpeed, function() { resize_jplayer(); reorganizeIsotope('.masonry'); });
});
}
} else {
$('#content .content-inner').hide();
$('#content .content-inner').html(response);
initialise('#content');
if ($(window).width() <= 480) { var topscroll = jQuery('header').height(); } else { var topscroll = 0; }
$('html, body').animate({scrollTop: topscroll+'px'}, animationSpeed, $easingType);
reorganizeIsotope('.masonry');
$('#content .content-inner').slideDown(fadeInOutSpeed, $easingType, function() {
resize_jplayer();
reorganizeIsotope('.masonry');
});
}
});
}
});
}
$("body").on("click", 'a.loadcontent', function() {
var href = $(this).attr('href');
var type = $(this).data('type');
var id = $(this).data('id');
var slug = $(this).data('slug');
if(window.location.hash.substr(1) == slug) {
$('html, body').animate({scrollTop: 0}, animationSpeed, $easingType);
} else {
window.location.hash = slug; // set the hash
//history.pushState({page:href}, href, href);
loadcontent(type,id,slug,false);
}
return(false);
});
and from functions.php
add_action('wp_ajax_nopriv_sr_get_content', 'loadAjaxPosts');
add_action('wp_ajax_sr_get_content', 'loadAjaxPosts');
function loadAjaxPosts() {
switch($_REQUEST['type']) {
case 'portfolio':
$output = sf_portfolio_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
case 'blog':
$output = sf_blog_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
default:
$output = 'Incorrect type specified, please contact support.';
break;
}
$output=json_encode($output);
if(is_array($output)) {
print_r($output);
} else {
echo $output;
}
die;
}
How to transfer the content? Thanks
Your loadContent() function's success handler does absolutely NOTHING. Hence whatever your php script sends back is simply thrown away.
You'd need something like:
success: function(response) {
$('#whatever').html(response);
}
Also note that your isarray($output) will NEVER work. json_encode() returns a STRING... never an array.
I can't get the content from a div (width a specific ID) from single.php into index.php with ajax.
Now I have this code and returns "0".
$("body").on("click", 'a.loadcontent', function() {
var href = $(this).attr('href');
var type = $(this).data('type');
var id = $(this).data('id');
var slug = $(this).data('slug');
});
function loadcontent(type,id,slug, action) {
jQuery.ajax({
type:'POST',
url:srvars.ajaxurl,
data: {
action:'sr_get_content',
id:id,
type:type
},
success: function(response) {}
});
}
and from functions.php
add_action('wp_ajax_nopriv_sr_get_content', 'loadAjaxPosts');
add_action('wp_ajax_sr_get_content', 'loadAjaxPosts');
function loadAjaxPosts() {
switch($_REQUEST['type']) {
case 'portfolio':
$output = sf_portfolio_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
case 'blog':
$output = sf_blog_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
default:
$output = 'Incorrect type specified, please contact support.';
break;
}
$output=json_encode($output);
if(is_array($output)) {
print_r($output);
} else {
echo $output;
}
die;
}
How to transfer the content?
Thanks
I have that part too..
$("body").on("click", 'a.loadcontent', function() {
var href = $(this).attr('href');
var type = $(this).data('type');
var id = $(this).data('id');
var slug = $(this).data('slug');
if(window.location.hash.substr(1) == slug) {
$('html, body').animate({scrollTop: 0}, animationSpeed, $easingType);
} else {
window.location.hash = slug; // set the hash
//history.pushState({page:href}, href, href);
loadcontent(type,id,slug,false);
}
return(false);
});