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 have a code snippet for a Queue Management System here that dynamically fetch data from the database based from the number of window allowed to be shown on the screen.
var elementArray;
function fetchPayment() {
elementArray = new Array();
$('.win_id').each(function() {
// here's the moneyshot
elementArray.push(this);
});
doAjax(0);
}
function doAjax(param) {
if (typeof elementArray[param] === 'undefined') {
var win_id = 0;
} else {
var win_id = elementArray[param].value;
}
$.ajax({
type: "GET",
dataType: 'json',
// async: false,
url: "<?php echo base_url();?>queue/getCurrentTransaction/" + win_id,
success: function(data) {
param++;
if (param <= elementArray.length) {
$('.names-' + win_id).empty();
$('.names-' + win_id).append("<div class='pname'>" + data.customer_name + '<li>' + data.ref_code + '</li></div>');
doAjax(param);
} else {
console.log("!");
}
},
error: function(data) {
param++;
$('.names-' + win_id).empty();
$('.names-' + win_id).append("<div class='pname'><li></li></div>");
doAjax(param);
}
});
}
This works, however, it's too CPU intensive and it is admittedly a bad approach, I refactored my other functions to make them something like this:
(function fetchNewServiceConnection() {
setTimeout(function() {
$.ajax({
type: "GET",
dataType: 'json',
url: "<?php echo base_url();?>queue/getCurrentTransaction/" + 100,
success: function(data) {
$('.c_name').empty();
$('.c_name').append(data.customer_name + '<li>' + data.ref_code + '</li>');
fetchNewServiceConnection()
},
error: function(data) {
$('.c_name').empty();
$('.c_name').append('<li></li>');
fetchNewServiceConnection()
}
});
}, 500);
})();
This works much much faster. The problem is the code above, how do I convert it to be like the code snippet below?
Inside your
function doAjax(param) {
if (typeof elementArray[param] === 'undefined') {
var win_id = 0;
} else {
var win_id = elementArray[param].value;
}
$.ajax({
type: "GET",
// etc....
}
you have doAjax(param); in two places, one for success: and one for error:
replace doAjax(param); in both places with:
setTimeout(doAjax.bind(null, param), 500);
Note:
I'm not sure, but it looks like you're trying to do "real time data", so my suggestion is to look at WebSockets (https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API), host your own, or, eventually, providers like Pusher.com (https://pusher.com/)
Don't know what is wrong, I've tried everything. The code should take simple info from PHP file and for each should fade in delay and out. I was successful with getting all the data at once but it is not good.
<script type="text/javascript">
$('button').fadeOut('slow')
var progressBar = $('.progress-bar');
var percentVal = 0;
window.setInterval(function(){
percentVal += 10;
progressBar.css("width", percentVal+ '%').attr("aria-valuenow", percentVal+ '%').text(percentVal+ '%');
if (percentVal == 100)
{
percentVal = 0;
}
}, 500);
$(document).ready(function() {
$("button").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "submit.php",
data: 'html', //expect html to be returned
success: function(data){
for(var i=0;i<6;i++){
$('.input-group').html(data).fadeIn(500).delay(1000).fadeOut(500);
}
}
});
});
});
</script>
PHP CODE:
$array= ['apple','orange','grapes','avocado','banana'];
$indexedOnly = array();
foreach ($array as $row) {
$indexedOnly[] = array_values($row);
}
echo json_encode($indexedOnly);
I think you need to abandon the loops, they wont allow you to pause to wait for the animation to finish. You can try something like this where you handle each element in data then using the callback functions of .fadeIn and .fadeOut to call the next one
function disp_next() {
$('.input-group').text(data.shift()).hide();
$('.input-group').fadeIn()
.delay(1000)
.fadeOut(function(){
if(data.length !== 0) {
disp_next();
}
})
}
disp_next();
You also need to change your dataType to json as you are expecting json from the server. Here is your jquery updated
$(document).ready(function() {
$("button").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "submit.php",
datatype: 'json', //expect html to be returned
success: function(data){
data = Object.values(data);
function disp_next() {
$('.input-group').text(data.shift()).hide();
$('.input-group').fadeIn()
.delay(1000)
.fadeOut(function(){
if(data.length !== 0) {
disp_next();
}
})
}
disp_next();
}
});
});
});
Try something like this, but if you want the animation of each element to wait for the previous one to finish you need to change the approach.
$.each(data, function(i, value) {
$('.input-group').html(data).fadeIn(500).delay(1000).fadeOut(500);
});
I'm trying to upload files through Ajax call and jQuery. Each input[type="file"] is handled dynamically as you will see on the code below and are created on the change event for the Select2 element.
var tipoRecaudo = $('#tipoRecaudo'),
tipo_recaudo = tipoRecaudo.val(),
selectedIdsTipoRecaudo = [];
tipoRecaudo.select2({
ajax: {
dataType: 'json',
url: function () {
return Routing.generate('obtenerRecaudosTramite');
},
data: function (tipo_recaudo) {
return {
filtro: tipo_recaudo
}
},
results: function (data) {
var myResults = [];
$.each(data.entities, function (index, item) {
if (selectedIdsTipoRecaudo.indexOf(item.id.toString()) === -1) {
myResults.push({
'id': item.id,
'text': item.nombre
});
}
});
return {
results: myResults
};
}
},
formatAjaxError: function () {
return Translator.trans('mensajes.msgNoConexionServidor', {}, 'AppBundle');
}
}).change(function () {
var id = $(this).val(),
selectedData = tipoRecaudo.select2("data"),
htmlTpl = '<table class="table"><caption>'+ selectedData.text + '</caption><tbody><tr><td>';
htmlTpl += '<input type="hidden" name="tipoRecaudos[]" id="tipoRecaudo ' + id + '" value="' + selectedData.id + '" /><div class="row"><div class="col-xs-6"><div class="form-group"><input type="file" id="recaudosNombreArchivo' + id + '" name="recaudos[nombre_archivo][]" multiple="multiple" class="form-control" /></div></div></div></div>';
htmlTpl += '</td></tr></tbody></table>';
selectedIdsTipoRecaudo.push(id);
$('#recaudoContainer').append(htmlTpl);
});
$('#recaudoContainer').on('change', 'input[type=file]', function (event) {
$("input:file").filestyle({
buttonText: "Seleccionar archivo",
iconName: "fa fa-upload",
buttonName: "btn-primary"
});
});
$('#btnGuardarPasoSieteAgregarProducto').on("click", function (event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// Create a formdata object and add the files
var formData = $('#formRecaudosTramites').serialize();
$.each($('#formRecaudosTramites')[0].files, function (key, value) {
formData = formData + '&recaudos[]=' + value;
});
$.ajax({
url: Routing.generate('rpniSubirRecaudos'),
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
contentType: 'multipart/form-data',
processData: false, // Don't process the files
//contentType: false // Set content type to false as jQuery will tell the server its a query string request
}).done(function (data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
console.log('SUCCESS: ' + data.success);
} else {
// do something with error
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// do something with fail callback
// STOP LOADING SPINNER
});
});
What is happening is: no filenames exists on query string, no files are upload or send through the Ajax call, instead it's sending a [object Object], what I'm doing wrong? Can any give me some working code for this stuff?
EDIT:
After reads the post referenced by user I change my code as the one before and now the error turns on:
TypeError: a is undefined
...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e...
What is wrong there?
Note: Yes, I know there are tons of plugins for handle this like jQuery File Upload from Blueimp, Dropzone and some others but I leave them out since I start using jQuery File Uploader from inside OneupUploaderBundle on my Symfony2 project and spent 4 days without success so I move to the other side: made things by myself so I can learn something else and improve my knowledge
i think this will help you,
var fd = new FormData();
//name is the key on the page of php to access the file
fd.append('name', $('#aob_file')[0].files[0]);
pass this fd object to your data field in ajax,
I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});
Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.
Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault
I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??