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>
Related
I have a chat application which works absolutely fine for sending and receiving texts only but I want to send images/videos/ files through it.
This is the main home page which display the chats.
<script>
$ = jQuery;
var currentID = null;
var chatTimer = null;
var oldhtml="";
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#chatbox").show();
$('#messages').html(data);
$("div.area").show();
if(oldhtml!==data) {
$('#messages').scrollTop($('#messages')[0].scrollHeight);
}
oldhtml=data;
}
});
}
$(document).ready(function() {
fetch_data();
setInterval(function() {
fetch_chat();
}, 500);
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
fetch_chat();
});
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
});
});
</script>
and below is the fetch_chat.php which fetches the chat from databases.
<?php
require("config.php");
$user_to = $_POST['id'];
$res1=$db->query("select * from chats where user_from='$_SESSION[id]' AND
user_to='$user_to' OR user_to='$_SESSION[id]' AND user_from='$user_to' order
by id");
if($res1->num_rows){
while($row=$res1->fetch_object()){
if($row->user_from === $_SESSION["id"] ) {
echo "<div class='chat self'>
<div class='user-photo'><img src='img/user1.jpg'></div>
<p class='chat-message'> $row->msg</p>
</div>";
} else {
echo "<div class='chat friend'>
<div class='user-photo'><img src='img/user2.jpg'></div>
<p class='chat-message'>$row->msg</p>
</div>";
}
}
} else
echo "No msgs <br />";
?>
Now I want to save the info of the uploaded file in the database and the files into a folder/directory. The sender and receiver should be able to send and view the files respectively.
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 :)
i have read all the stackoverflow solutions but it didnt work.
i have some divs and when i click on them it should change and load different data from server via ajax.
but whenever i click on it the page scroll to top.
i have tried "return false" and preventDefault .
here is my code:
$('.part').click(function(e) {
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('banners/bannerjs.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
}
return false;
});
and here is my html code:
<div class="part type<?php echo $w['TypeID']?>" style="" data-price="<?php echo $w['Price']?>" data-id="<?php echo $w['id']?>"
data-selected="<?php echo $selected?>" data-banner-selected="<?php echo $w['Display_Banner_Selected']?>"
data-banner="<?php echo $w['Display_Banner']?>">
<script type="text/javascript">
//jQuery.ajaxSetup({async:false});
if($('[data-id="<?php echo $w['id']?>"]').attr('data-selected') == "selected"){
var id = <?php echo $w['Display_Banner_Selected']?>;
}else{
var id = <?php echo $w['Display_Banner']?>;
}
$.post('banners/bannerjs.php', {'id': id}, function(result) {
$('[data-id="<?php echo $w['id']?>"]').append(result);
});
$('.<?php echo $banner['name'].$banner['id']?>').append('<div class="partPrice"><?php echo $w["Price"]?></div>');
</script>
<br>
</div>
Try returning false after your post:
$('.part').click(function(e) {
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('banners/bannerjs.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
return false; //added this
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
return false; //added this
}
return false;
});
Updated code:
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$(".part").click(function(e) {
e.preventDefault(); //this disables the default behavior of the element
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('testy.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
}
return false;
});
})
</script>
<a class="part" data-selected="">Foo</a>
I am using setInterval and then unable to clearInterval in my code. Please see the code
I am getting the value of complete and it is true and also entering the if statement but clearInterval still not working. I am tired and trying for last 10 hours but not find the bug. I checking the console.log and it is not stopping the interval.
jQuery(document).ready(function() {
var complete = false;
var Interval;
jQuery( "#form" ).submit(function() {
Interval = setInterval(get, 100);
post();
return false;
});
function post(){
var url = "my/url/here";
var data = {
'action': 'action/here',
'name': 'value'
};
jQuery.post(url, data, function(response) {
jQuery("#emails").html(response);
}).done(function() {
//alert( "second success" );
})
.fail(function() {
//alert( "error" );
})
.always(function() {
complete = true;
//alert( "finished" );
});
} // End post()
function get(){
var url = "url/goes/here";
if(complete == true){
clearInterval(Interval);
}
var data = {
'action': 'action/here',
};
jQuery.get(url, data, function(response) {
console.log(response);
jQuery("#progress").html(response);
});
} // End get()
});
here is the original code below. ajax call is working fine but clearInterval() not working
<script type="text/javascript" >
jQuery(document).ready(function() {
jQuery(".juee_emails_row").hide();
var juee_complete = false;
var juee_Interval;
jQuery( "#juee_form" ).submit(function() {
jQuery(".juee_emails_row").show();
juee_Interval = setInterval(juee_get, 100);
juee_post();
return false;
});
function juee_post(){
var data = {
'action': 'juee_get_emails',
'juee_data_option': jQuery('input[name=juee_data_option]:checked', '#juee_form').val()
};
jQuery.post(ajaxurl, data, function(response) {
jQuery("#juee_emails_td").html(response);
}).done(function() {
//alert( "second success" );
})
.fail(function() {
//alert( "error" );
})
.always(function() {
juee_complete = true;
//alert( "finished" );
});
} // End juee_post()
function juee_get(){
if(juee_complete == true){
clearInterval(juee_Interval);
}
var data = {
'action': 'juee_progress',
};
jQuery.get(ajaxurl, data, function(response) {
console.log(response + " email found");
jQuery("#juee_progress_td").html("");
jQuery("#juee_progress_td").html(response);
});
} // End juee_get()
});
</script>
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.