Below code works on localhost, but not on live server.
MAIN EDIT:
Only 1 thing remains which is not working:
On AJAX success this will being executed:
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
How ever, the label(for example) is not being updated. The label needs to be updated by the score which is given (data.score_result).
Ajax code:
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
+ <?php echo $query['monitor_id']; ?>
+ '&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
When I put alert('test'); above the $.ajax({ code it shows 'test'. When I put the alert INSIDE (just below) the $.ajax({ code, it does not show the alert.
saveScore function:
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
Results/info:
alert(post); gives me the correct data result.
saveScore is executed, but won't close afterwards (setTimeout).
#label and #monitoring_score are not being updated like it has to do.
using jquery-3.1.1.
I'm distraught on how to solve this. Anyone has an idea on how to fix?
Extra:
#Teemu:
Add an error handler to the AJAX call too, most likely it's the
server-side which passes an error instead of data. Or open Network tab
from the DevTools, and see if you're actually getting 200 OK message
and the data.
Edit 1: (Whole javascript code):
<script>
$(document).ready(function () {
$(".nav-tabs a").click(function () {
$(this).tab('show');
});
});
$(document).ready(function () {
$('.summernote').summernote({
height: 450, //set editable area's height
toolbar: [
['view', ['fullscreen']],
['help', ['help']]
],
codemirror: { // codemirror options
theme: 'monokai'
}
});
});
jQuery(document).ready(function () {
$('.nvt').on('click', function () {
// get the id:
var id = $(this).attr('id');
var res = id.split("_");
// Reset rating:
var rating_input = "item_score_" + res[1];
$('#' + rating_input).rating('update', 0);
var comment = $("#comments_" + res[1]).val();
var score = 0;
var post = 'controller=QualityMonitoring&task=setScore&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[1] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[1]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[1]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: 'json',
beforeSend: function (data) {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function(data) {
console.log("ERROR: ", data);
}
});
});
$('.savecomment').on('blur', function () {
var comment_id = $(this).attr('id');
var res = comment_id.split("_");
var commentraw = $("#comments_" + res[1]).val();
var comment = encodeURIComponent(commentraw);
var post = 'controller=QualityMonitoring&task=setComment&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[1] + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
success: function (data) {
if (data.result == 666) {
$("#comments_" + res[1]).css("background-color", "#ffcccc");
}
}
});
});
});
$(document).on('change', '.btn-file :file', function () {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready(function () {
$('.btn-file :file').on('fileselect', function (event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if (input.length) {
input.val(log);
} else {
if (log) alert(log);
}
});
});
function closediv() {
$(document).unbind("keyup");
$("#overlay").fadeOut("slow", function () {
$("#overlay").remove();
$(".FixedDiv").removeClass("panel-danger");
});
}
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
$(document).ready(function () {
var $sidebar = $(".FixedDiv"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 55;
$window.scroll(function () {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 24
});
}
});
});
</script>
Is your PHP code valid and not throwing extra code which is messing up your JSON object. When there is a notice the JSON object becomes a string instead of a JSON string and then javascript can't parse it anymore.
Please make a new clean controller without any other code, post the data again and then check what is happening. Never return data but echo data with an exit.
Javascript and Code looks valid but somewhere else in your MVC may throw HTML code in the exit statement or generating it before you enter the controller which is required to return the data.
after function saveScore() add:
var close = function() { $('#overlay').remove(); };
after success: function (data) {} remove last comma
I think a few of the other posters are on to something about the invalid JSON,
I would add however, this is something I like to do for JSON
<?php
ob_start(); //turn on output buffering
//...other code
$debug = ob_get_clean();
$response['debug'] = $debug; //comment this when live in production
header('Content-type: application/json');
echo json_encode($response);
What this does is turn on output buffering. Which traps any output and buffers it. This includes warnings, notices, echo, and print stuff. Then it stuffs it into the response as debug and forwards it to the client.
Obviously you would not want to do this on live production server, but you can easily comment it out. It can be a security issue to include some errors and stack trace information to the client. But for debugging purposes it works great.
The problem with JSON is if you are checking the value of something somewhere (printing it) or have any notices it will muck up your JSON. For example
printed content
{"foo":"bar"}
So this takes away that problem entirely (assuming you output buffer before printing anything) like so:
{"foo":"bar", "debug":"printed content"}
And now you have valid JSON, and as a side bonus you can print out your debug info by simply doing
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
if(data.debug) console.log(data.debug);
}
});
It's simple and effective.
Hope it helps.
Try adding an error handler to your Ajax function and see what it returns:
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function(data) {
console.log("ERROR: ", data);
}
});
Share the result with us so we can trouble shoot your issue and help you.
Are you wrapping your js code in $(document).ready() ?
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
Try enclosing everything in
$(function(){
//your code here
})
Like this:
$(function(){
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
+ <?php echo $query['monitor_id']; ?>
+ '&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
});
From the code you posted, the comments below and the discussion ( actually was very helpful to jump to this conclusion ) .. i can point a couple of things, but first :
adding error_reporting(0); in the begining of the controller right after <?php should solve your problem. ( if my guess is correct and it's just a notice, not an actual error)
i'm guessing that you already have this in your localhost 's php.ini and on the live server you have the default error_reporting = E_ALL, due to two different installations of php.
there's probably somewhere in the controller a notice of an undefined index or something, and php is trying to let you know by outputting this :
<br />
<b>Notice</b>: Undefined index: ...
{"calculated_score":10,"score_result":"1.75 pts"}
it starts with a < and that's where this comes from
SyntaxError: Unexpected token < in JSON at position 0
the $.ajax is unable to parse this because you have dataType="json" and this means that it is expecting a valid json back from the server, so you get the 200 status because the request was successful with no errors and console.log(data) will be empty because it was unable to parse it.
a simple way to reproduce this is creating a test php file and send the request to it instead of controller.php like :
<?php
error_reporting(0); // try with and without this line.
$data = [
'city' => 'Montreal',
'Country' => 'Canada'
];
echo $_GET['something']; // this will trigger a notice of undefined index something
echo json_encode($data);
?>
you can remove dataType:"json" and put console.log(data) in the success function and look in the console to see what the server is really telling you.
but here's something that bugs me ..
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
this looks like a query string you use for GET requests but you have type:"POST" in your ajax request ..
i don't know how you're handling this in the controller but it should be type:"GET" to send data like this, but if you want to send the data with POST then var post should be an object, ( this could be the problem as it defaults to GET when not set and in the controller there's a $_GET['task'] instead of $_POST['task'] or vise-versa ) so here's a snippet to convert the query string to a json :
function QueryStringToJSON(str) {
var pairs = str.split('&');
var result = {};
pairs.forEach(function (pair) {
pair = pair.split('=');
var name = pair[0]
var value = pair[1]
if (name.length)
if (result[name] !== undefined) {
if (!result[name].push) {
result[name] = [result[name]];
}
result[name].push(value || '');
} else {
result[name] = value || '';
}
});
return (result);
}
var string = 'controller=QualityMonitoring&task=setScore&monitor_id=5&q=blah&item_score=99&comment=hello';
var obj = QueryStringToJSON(string);
console.log(obj);
i hope this helps or at least gives you an idea, and Good Luck.
I use json.encode from php and pass it array in jquery ajax, although console.log(links); works , I don't see anything in the console for selecting an item (for example console.log(links[1]);
the commented codes are the ones that are not working
$(document).ready(function () {
var links = [];
$.ajax({
method: 'post',
dataType: 'json',
url: 'slider_pull_data.php',
success: function (data) {
$.each(data, function (i, j) {
links.push(j.photo);
});
}
});
// console.log(links[1]);
// $('#big_slider').css("background-image", "url(uploads/" + links[0] + ")");
console.log(links);
$(".numbers").hover(function(){
var imageNumber = Number($(this).text()) - 1;
$('#big_slider').css("background-image", "url(uploads/" + links[imageNumber] + ")");
});
});
You have to place the not-working parts in the success function otherwise they are executed before the query has returned and links is still [].
This would be similiar to this:
$(document).ready(function () {
var links = [];
$.ajax({
method: 'post',
dataType: 'json',
url: 'slider_pull_data.php',
success: function (data) {
$.each(data, function (i, j) {
links.push(j.photo);
});
console.log(links[1]);
$('#big_slider').css("background-image", "url(uploads/" + links[0] + ")");
}
});
console.log(links);
$(".numbers").hover(function(){
var imageNumber = Number($(this).text()) - 1;
$('#big_slider').css("background-image", "url(uploads/" + links[imageNumber] + ")");
});
});
jQuery for Updating Database table entry using PHP. after ajax code is not working for me please help.
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(this).parents(".success1").replaceWith(html);
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
You are trying to replace with parent, it must be child. Use below code
success: function (html) {
$("#dynamic-table .success1").replaceWith(html);
}
OR
success: function (html) {
$("#dynamic-table").find(".success1").replaceWith(html);
}
This code works great i have used similar.... try this one..
function FormSubmit() {
$.ajax(
type: "POST",
url: 'success1.php',
data: $("#attend_data").serialize(),
async: false
}).done(function( data ) {
$("#attend_response").html(data);
});
}
I have updated your code snippet below... tested offline and the code is working:
A few pointers:
Instead of this: request/allot_enrollmentNo_gov.php
Try this: /request/allot_enrollmentNo_gov.php
Notice the forward slash ( / ) This indicate that the Ajax path must start from the root directory depending on your server settings.
Use this: $(".success1").html(html); instead of $(this).parents(".success1").replaceWith(html);
Working code below:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "/request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(".success1").html(html);
alert('Response from the POST page = ' + html + ');
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
Now it is working Perfectly by setting parent:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var rowParent = $(this).parent('.success1');
var allottedValue = rowParent.find('input').val();
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
rowParent.replaceWith(html);
}
});
return false;
});
For some reason ajax is not sending data.
On the PHP I have this code:
if (isset($_POST['submit'])) {
echo "submit";
} else {
echo "not submit";
}
And I get not submit.
This is JS code:
$(function () {
$('#submit').click(function () {
var length = $('#number').val();
var small = $('#small').val();
var big = $('#big').val();
var number = $('#numero').val();
var special = $('#special').val();
var submit = 'submit';
var url = 'public/php/codegenerator.php';
var data = "length=" + length + "&small=" + small + "&big=" + big +
"&number=" + number + "&special=" + special + "&submit=" + submit;
$.ajax({
type: "POST",
url: url,
data: data,
success: function () {
$('#code').load(url, function () {
$(this).fadeIn(1000)
});
}
});
return false;
});
});
You can try this approach
$(function(){
$('#submit').click(function(){
//YOUR CODE
var param = {
length:length,
small:small,
big:big,
number:number,
special:special,
submit:submit
}
$.ajax({
type: "POST",
url: url,
data: param,
//EDITED LINE
success: function (data) {
$('#code').hide().html(data).fadeIn(1000);
}
});
return false;
});
});
// REVISED ANSWER
// IN YOUR PHP FILE
if (isset ($_POST['submit'])) {
echo json_encode(array('result'=>"submit"));
}
else {
echo json_encode(array('result'=>"not submit"));
}
//IN YOUR JQUERY CODE
$.ajax({
type: "post",
url: url,
data: param,
dataType:'json';
//EDITED LINE
success: function (data) {
// alert(data.result);
$('#code').hide().html(data.result).fadeIn(1000);
}
});
You are getting Not submit, because it comes from the .load() call and not from .ajax - and in the load call you just load the URL without passing any POST data. So why you are running .load inside the success callback of .ajax with the same url?
is it possible to pass the link value of a hyperlink to ajax?
I'm quite new in this branch so maybe I'm doing actually wrong
so I would like to achieve the following:
echo '<ul><li class="all">alle</li>';
foreach(range('a','z') as $i):{
echo '<li class = "searchAbc"><a class="button" href="#"/>'.$i.'</a></li> </ul>';
}
endforeach;
than the ajax
function ajax_abc() {
var url = 'index.php?option=com_glossary&task=abc';
var abc= $(this).attr('href');
// data = 'format=raw'+ '&'+'val=' + $("#search").val();
data = 'val=' + abc + '&' + 'format=raw';
$(document).ready(function(){
function showLoader(){
$('.search-background').fadeIn(200);
}
function hideLoader(){
$('#sub_cont').fadeIn(1500);
$('.search-background').fadeOut(200);
};
$(" li.edit a").click(function(){
ajax_redirect();
});
$(".searchBtn").click(function() {
ajax_search();
});
$('#search').keyup(function(e) {
if(e.keyCode === 13) {
ajax_search();
}
});
function ajax_search(search) {
var url = 'index.php?option=com_glossary&task=getvalues';
data = 'val=' + $("#search").val() + '&' + 'format=raw';
$('#sub_cont').fadeIn(1500);
showLoader();
$.ajax({
type: "GET",
url: url,
data: data,
success: function(data) {
hideLoader();
$('div.default_order').hide;
$('#sub_cont').html(data);
}
}); // ajax
}
function ajax_abc(abc) {
var url = 'index.php?option=com_glossary&task=abc';
data = 'val=' + abc + '&' + 'format=raw';
//... Add jQuery.load() codes here ...
$.ajax({
type: "GET",
url: url,
data: data,
success: function(data) {
hideLoader();
$('div.default_order').hide;
$('#sub_cont').html(data);
}
}); // ajax
}
$(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
$(".stripeMe tr:even").addClass("alt");
});
do you mean something like this?
$('a.button', 'li.searchAbc').click(function(){
var url = 'index.php?option=com_glossary&task=abc';
var abc = $(this).attr('href');
var ajaxParam = {
val: abc,
format: 'raw'
};
$.post(url, ajaxParam, function(result){
//process result
});
// or using GET
/*
$.get(url, ajaxParam, function(result){
//process result
});
// */
return false;
})
note: attribute href of your <a> tag is '#'.
Ok try something like the following
Change
echo '<li class = "searchAbc"><a class="button" href="#"/>'.$i.'</a></li> </ul>';
to
echo '<li class = "searchAbc"><a class="button" href="#" onClick="ajax_abc(\''.$i.'\')"/>'.$i.'</a></li> </ul>';
Then put in your javascript
function ajax_abc(abc) {
var url = 'index.php?option=com_glossary&task=abc';
data = 'val=' + abc + '&' + 'format=raw';
//... Add jQuery.load() codes here ...
}
In my case this worked form me !!
function deleteImage(data1,data2){
$.ajax({
type: "POST",
url: "remove_unwanted_files.php",
data: "nameImage="+data1+"&idImage="+data2,
success: function(msg){
alert( "Data Saved: " + data1 + " " + data2);
//Code for Anything you want
}
});