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've got a bit of code to divide a string of words in parts and do a request (foreach part) to php to get results and place them in element. All works fine when I use async : false BUT I would like it to be be async : true. The problem I have with async : true is that the results are "random" because request doesn't goes sequential... I've read and searched how to solve this but couldn't find it...
Here's my code:
$(function() {
$("#check").on( "click", function() {
$("#results").empty();
var text = $("#original").val();
var totalWords = text.split(' ').length;
var start = 0;
var numberResults = 10;
var divide = totalWords / numberResults;
var numberOfTimes = Math.floor(divide) + 1;
var test = 0;
for(var index = 0; test < totalWords; index+=10){
var part = text.split(/\s+/).slice((test),(test + 10)).join(" ");
$.ajax({
url: "requests.php",
async : true,
cache: false,
type: "POST",
data: {words : part},
success: function(html){
$("#results").append(html);
$("#check").hide();
}
});
console.log(test);
test = test + 10;
$(".progress-bar").attr("aria-valuenow", test);
$(".progress-bar").css({"min-width" : test + "em"});
$(".progress-bar").css({"width" : test + "%"});
$(".progress-bar").text(test + "%");
console.log(part);
}
});
});
Asynchronous Execution cannot guaranty order of execution. Hence the name. If you want synchronous as you mentioned use async: false.
jQuery docs
Alternatively, use a solution to rearrange the data or use some additional parameter to position the data in your required order if you want to reap the advantages of async execution such as speed.
Example of one such implementation logic is:
$(function() {
$("#check").on("click", function() {
$("#results").empty();
var text = $("#original").val();
var totalWords = text.split(' ').length;
var start = 0;
var numberResults = 10;
var divide = totalWords / numberResults;
var numberOfTimes = Math.floor(divide) + 1;
var test = 0;
function action_task(index, data) {
$.ajax({
url: "requests.php",
async: true,
cache: false,
type: "POST",
data: data,
success: function(html) {
//add data at reserved spot
$("#id_" + index).html(html);
$("#check").hide();
}
});
}
for (var index = 0; test < totalWords; index += 10) {
var part = text.split(/\s+/).slice((test), (test + 10)).join(" ");
//reserving a spot
$("#results").append("<span id='id_" + index + "'></span>");
action_task(index, {
words: part
});
console.log(test);
test = test + 10;
$(".progress-bar").attr("aria-valuenow", test);
$(".progress-bar").css({
"min-width": test + "em"
});
$(".progress-bar").css({
"width": test + "%"
});
$(".progress-bar").text(test + "%");
console.log(part);
}
});
});
I am working with this piece of code. Here I am using jQuery, Jquery form.js, and jQueryUI. The task is to upload an image in the upload folder and store the path of the image along with its position which is set by users (jQueryUI draggable is used for this). It works just fine. But I don't know exactly how it works.
Can anyone explain to me how we are grabbing the dragged position set by users and how the whole thing is working all together. If you need to see the PHP script I can share thattoo. Thanks
$(document).ready(function () {
/* Uploading Profile BackGround Image */
$('body').on('change', '#bgphotoimg', function () {
$("#bgimageform").ajaxForm({
target: '#timelineBackground',
beforeSubmit: function () {},
success: function () {
$("#timelineShade").hide();
$("#bgimageform").hide();
},
error: function () {
}
}).submit();
});
/* Banner position drag */
$("body").on('mouseover', '.headerimage', function () {
var y1 = $('#timelineBackground').height();
var y2 = $('.headerimage').height();
$(this).draggable({
scroll: false,
axis: "y",
drag: function (event, ui) {
if (ui.position.top >= 0) {
ui.position.top = 0;
} else if (ui.position.top <= y1 - y2) {
ui.position.top = y1 - y2;
}
},
stop: function (event, ui) {}
});
});
/* Bannert Position Save*/
$("body").on('click', '.bgSave', function () {
var id = $(this).attr("id");
var p = $("#timelineBGload").attr("style");
var Y = p.split("top:");
var Z = Y[1].split(";");
var dataString = 'position=' + Z[0];
$.ajax({
type: "POST",
url: "image_saveBG_ajax_bg.php",
data: dataString,
cache: false,
beforeSend: function () {},
success: function (html) {
if (html) {
$(".bgImage").fadeOut('slow');
$(".bgSave").fadeOut('slow');
$("#timelineShade").fadeIn("slow");
$("#timelineBGload").removeClass("headerimage");
$("#timelineBGload").css({
'margin-top': html
});
return false;
}
}
});
return false;
});
});
$("body").on('click', '.bgSave', function () {
var id = $(this).attr("id");
var p = $("#timelineBGload").attr("style");
var Y = p.split("top:");
var Z = Y[1].split(";");
var dataString = 'position=' + `Z`[0];
You are getting the position here just before the ajax post to the PHP script, it is crudely getting the 'top' CSS attribute from the inline style on #timelineBGload element.
If you inspect the DOM when dragging #timelineBGload UIDraggable updates the top (and left) as you move it around
tag a is to $.each(). see my js code:
$('.auto_complete').keyup(function () {
var id = '#' + this.id;
var alt = $(id).attr('alt'); var id = $(this).attr('id'); var name = $(this).attr('name');
var url = alt + id + '/' + name;
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
$.each(data.name, function(a,b){
$(".list_name").append('<p>' + b + '</p>');
////////////////////here/////////////////////
$('.list_name p a').live('click', function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo('.auto_box span');
$(this).remove();
return false;
});
/////////////////////////////////////////////
});
if($('.auto_complete').val()==''){
$(".list_name p").hide().remove()
}
$('body').click(function(){
$(".list_name p").hide().remove();
$('.auto_complete').val('');
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
php:(i use of codeigniter)
function search_hotel(){
$search_term = $this->input->post('search_hotel');
$query = $this->db->order_by("id", "desc")->like('name', $search_term)->get('hotel_submits');
$data = array();
foreach ($query->result() as $row)
{
$data[] = $row->name;
}
echo json_encode(array('name' => $data));
// echo: {"name":["333333","\u0633\u0644","\u0633\u0644\u0627\u0633\u06cc","\u0633\u0644\u0627\u0633\u0633","\u0633\u0644\u0627\u0645"]}
}
How you approach the solution might depend on whatever else you have attached to your link in terms of events. I would try it like this instead:
$('.list_name p a').live('click', function() {
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" />').appendTo('.auto_box span');
$('.list_name p a').remove();
return false;
});
I created a jsFiddle for an example, which seems to be working just fine. If you're still getting a form submission then there might be other syntax errors in your code or other events tied to your elements that are interfering or preventing the desired behavior from occurring.
Because the event was not attached. Why? You must debug it... do you have errors in your browser Javascript console? Maybe stopped parsing due of some error.
Maybe you are not selecting the right a element (list_name or list-name)... etc.
UPDATE
What version of jQuery are you using?
You can place the binding of the event outside of the AJAX call to test. It should work that way too.
You can try also to attach it to the parent .list_name , the events bubble up, so it's more efficient doing it like this.
Are you having any errors in the console log?
Try this
$('.list_name p a').live('click', function(e) {
e.preventDefault();
var b = "defineIt";
$('' + b + '، ').appendTo('.auto_box span');
$(this).remove();
return false;
});
below is a code that gets the value of the selected option and shows the php file in the div. How can I add another file and another div (secondfile) to be displayed ?
$('#firstresult').empty().addClass("loading")
.load(val + '.php', { value: val }, function(){
$("#firstresult").removeClass("loading");
}));
$('#secondresult').empty().addClass("loading")
.load(val + 'b.php', { value: val }, function(){
$("#secondresult").removeClass("loading");
To show a loading image, you could add a class before load() and remove upon load() complete.
JS
Changes to the lines that begin $('#firstresult') and $('#secondresult').
$('#firstresult').empty().addClass("loading")
.load(val + '.php', { value: val }, function(){
$("#firstresult").removeClass("loading");
}));
$('#secondresult').empty().addClass("loading")
.load(val + '.php', { value: val }, function(){
$("#secondresult").removeClass("loading");
}));
CSS
.loading { height:24px; background:#fff url('loading.gif') 50% 50% no-repeat; }
Create / Append div in results div as child and load content from php script to it:
$(document).ready(function() {
$('#termid').change(function() {
var val = $(this).val();
$('results').append('<div id="result' + val '"></div>');
$('#result' + val).load(val + '.php',
{
value: val
});
});
});
not tested