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 need to show multiple wfs features into map. The requested url is http://localhost/pdan/map.php?id=150 This is what I have done:
var id = <?php echo $_REQUEST['id']; ?>;
function getVector(obj) {
var url = "";
var geojsonFormat = new ol.format.GeoJSON();
var vectorSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url = 'http:192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
$.ajax({url: url, dataType: 'jsonp', jsonp: false, cache:false});
},
strategy: ol.loadingstrategy.bbox
});
window.loadFeatures = function(response) {
vectorSource.addFeatures(geojsonFormat.readFeatures(response));
};
return new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
}
function getObject(id) {
var result;
$.ajax({
url: "dbQueries.php",
async: false,
cache: false,
dataType: "JSON",
data: {'query': 110, 'id': id},
success: function (data) {
result = data;
}
});
return result;
}
var vector = [];
var rowObject = getObject(id);
var size = Object.size(rowObject);
//Prepare vector Layer
if (size != 0) {
for (var i = 0; i < size; i++) {
vector[i] = getVector(rowObject[i]);
}
}
//Now Initialise map
var map = createMap();
var graticule = getGraticule();
graticule.setMap(map);
//Add vector to the map
if (size != 0) {
for (var i=0; i<size; i++) {
map.addLayer(vector[i]);
}
}
Everything seems okey to me but the url is changed and in the console I get error as:
GET
http://localhost/pdan/192.168.0.101:8082/geoserver/pdan/ows [HTTP/1.1 403 Forbidden 3ms]
What am I missing here?
The problem was with the url I requested. It should be
var url = 'http://192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
instead of
var url = 'http:192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
I have the following code which (amount other things) gets an image URL from the server:
$.ajax({ url: 'Script.php',
data: {action: 'Random'},
type: 'POST',
dataType: "html",
success: function(data) {
var results = data.slice(0,-1).split('|');
var workers = [];
for(i=0; i<results.length; i++)
{
workers[i] = workers[i].split(',');
}
for(i=0; i<workers.length; i++)
{
var j = i+1
$('#random-worker' + j + '-pic').attr("src", workers[i][3]);
$('#random-worker' + j + '-name').html(workers[i][0]);
$('#random-worker' + j + '-pro').html(workers[i][1]);
$('#random-worker' + j + '-city').html(workers[i][2]);
}
}
});
Also, I have this code to display a loading gif while the ajax requests process
var $loading = $('.div-loading').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
What happens is that the Ajax is completed and the $loading div is hidden and only then the elements gets their values and the Image gets the new source. Is there a way to completely end the loading process and only then hide the $loading div?
Thanks.
I'm having a problem - my jQuery change blur event is only working for the first element in a dynamically created list. How can I resolve this?
The element I've created (well a watered down version) can be found here: http://jsfiddle.net/kfm5b/2/
jQuery
$('.roomFac').on("change blur", function () {
var park = $("#park2").val();
var lecturestyle = $("#lecture_style2").val();
var roomstructure = $("#room_structure2").val();
var groupsize = $("#groupSize2").val();
var facilities = "";
$('select[name*=roomFac]').each(function () {
facilities += $(this).val();
facilities += ",";
});
var dataString = 'park=' + park + '&' + 'lecturestyle=' + lecturestyle + '&' +
'roomstructure=' + roomstructure + '&' + 'groupsize=' + groupsize + '&' +
'facilities=' + facilities;
$.ajax({
type: "POST",
url: "process_timetableMon2.php",
data: dataString,
cache: false,
success: function (html) {
$('#mon').html(html);
}
});
});
process_timetableMon2.php
$array = explode(",", $_POST["facilities"]);
for($i = 0; $i < count($array); $i++){
echo $array[$i].'<br>';
}
Since the select dropdowns are added dynamically, you need a delegated event handler:
$(document).on('change blur', '.roomFac', function () {
//Your function here
});
I'm struggling around for a while now with a jQuery Ajax-Request. I'm building a Step-by-Step rating form. There is actually only one form which will be submitted on each step (the current step will is transmitted to PHP, only data that is important for that step will be validated).
The Problem:
The Ajax call is being submitted a lot of times without reloading the page. Although the ajax call (logged into Firebug console) is returning the right value (e.g. error if PHP validation fails) jQuery still picks up the old return values first (e.g. an old error or a success) and goes through the code again..
Code
Here is my jQuery function..
$(ajax_cont).find(':submit').live('mouseup keyup',function(){
submitButton = $(this);
});
$(ajax_cont).live("submit", function(d) {
var index = submitButton.attr("id").substring(9);
d.preventDefault();
var str = $(this).serialize() + "&step=" + index;
var uri = ajax_default;
$.ajax({
type: "POST",
cache: false,
asynch: false,
url: uri,
data: str,
success: function(data) {
$(".step_slider_container").ajaxComplete(function(event, request, settings) {
if(data.success) {
alert("jaa");
var next_step = "";
$(ajax_cont).parent().find(".error").html("").hide();
$(ajax_cont).find(".error_input").removeClass("error_input");
next_step = data.next;
console.log(data.next);
step_check = $(ajax_cont).find(".step_check").val();
if(step_check.indexOf(next_step) == -1) {
step_check = step_check + "," + next_step;
}
$(ajax_cont).find(".step_check").val(step_check);
var enabled_array = step_check.split(',');
$.each(enabled_array, function(enabled_index, enabled_value) {
if(enabled_array[enabled_index].length > 0) {
tmp_div = enabled_array[enabled_index];
$("body").find(".step_" + tmp_div).removeClass("disabled");
}
});
// Show - Hide Container
var id = "#step_" + next_step;
fadeDiv(id);
if(next_step == 3) {
preview_rating();
setHeight(ajax_cont.height());
}
// Navigation
$("body").find(".step").removeClass("step_active");
$("body").find(".step_" + next_step).addClass("step_active");
}
if(data.error) {
next_step = "";
$(ajax_cont).find(".error_input").removeClass("error_input");
error = data.error;
error_ids = data.error_id;
$.each(error_ids, function(index, value) {
id = "#" + error_ids[index];
$(id).addClass("error_input");
});
$(ajax_cont).parent().find(".error").html("<p>" + error + "</p>").show();
setHeight(ajax_cont.height());
}
});
},
dataType: "json"
});
return false;
});
I hope someone can find an answer to the problem.. Seems to make me crazy :(
I can see a few problems with your code:
a) You are setting the ajaxSuccess event within the success event of an ajax call...
b) You are using data.success to determine whether it is successful, which won't change because of an PHP error.
Instead, you should do:
$(ajax_cont).find(':submit').live('mouseup keyup',function(){
submitButton = $(this);
});
$(ajax_cont).live("submit", function(d) {
var index = submitButton.attr("id").substring(9);
d.preventDefault();
var str = $(this).serialize() + "&step=" + index;
var uri = ajax_default;
$.ajax({
type: "POST",
cache: false,
asynch: false,
url: uri,
data: str,
success: function(data) {
if(data.success) {
alert("jaa");
var next_step = "";
$(ajax_cont).parent().find(".error").html("").hide();
$(ajax_cont).find(".error_input").removeClass("error_input");
next_step = data.next;
console.log(data.next);
step_check = $(ajax_cont).find(".step_check").val();
if(step_check.indexOf(next_step) == -1) {
step_check = step_check + "," + next_step;
}
$(ajax_cont).find(".step_check").val(step_check);
var enabled_array = step_check.split(',');
$.each(enabled_array, function(enabled_index, enabled_value) {
if(enabled_array[enabled_index].length > 0) {
tmp_div = enabled_array[enabled_index];
$("body").find(".step_" + tmp_div).removeClass("disabled");
}
});
// Show - Hide Container
var id = "#step_" + next_step;
fadeDiv(id);
if(next_step == 3) {
preview_rating();
setHeight(ajax_cont.height());
}
// Navigation
$("body").find(".step").removeClass("step_active");
$("body").find(".step_" + next_step).addClass("step_active");
}
if(data.error) {
next_step = "";
$(ajax_cont).find(".error_input").removeClass("error_input");
error = data.error;
error_ids = data.error_id;
$.each(error_ids, function(index, value) {
id = "#" + error_ids[index];
$(id).addClass("error_input");
});
$(ajax_cont).parent().find(".error").html("<p>" + error + "</p>").show();
setHeight(ajax_cont.height());
}
},
error : function()
{
alert('there was an error parsing the json, or processing your request');
},
dataType: "json"
});
return false;
});
Note, I have removed the ajaxSuccess event and implemented an error event to your ajax request.
I agree with #thecodeparadox - wall of code. Too much code is just as bad as too little code :-)
Going purely by what you have said it sounds like you have multiple AJAX submits and you are using the response from an older request. Try using something like Ajax Manager http://www.protofunc.com/scripts/jquery/ajaxManager/ which lets you queue and cancel requests.