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.
function DoAjax( args )
{
var formData = "?" + $("form[name=" + args.formName + "]").serialize();
$.ajax({
type: "POST",
url: args.url + formData,
data: {
request: args.request
},
success: function (data) {
alert(data);
args.callback.html(data);
},
error: function (a, b, c) {
alert("error: " + a + ", " + b + ", " + c + ".");
}
});
return false;
}
I need to pass in a custom bit of data to my php script called "request" which will denote which process to run on the php page... but I also want to serialize any other form fields on my form. Is this the correct way of doing it (add the serialize to the end of the URL) because I just cannot seem to get anything from my PHP $_POST["whatever"]
EDIT:::///
<?php
$request = $_POST[ "request" ];
if( isset( $request ) )
{
require_once( "includes.php" );
function LogInWithClientCred()
{
$username = CheckIsset( "username" );
$password = CheckIsset( "password" );
echo $_REQUEST["username"];
echo $_GET["username"]; // echos correctly the username.. but I want it to be post data instead!
Please ignore the security awesomeness, it is pseudo for your purpose.
Combine formData and your additional data into one string.
var formData = $("form[name=" + args.formName + "]").serialize() + "&request=" + args.request;
$.ajax({
url: args.url,
data: formData,
type: "POST",
...
})
I am not too sure If i got ur question well, But I think you are appending the form data to URL and using POST in ajax.
Can you try
$_REQUEST["whatever"] to see what you are getting
EDIT
After seeing the commnets I think I now got it
function DoAjax( args )
{
var formData = $("form[name=" + args.formName + "]").serialize();
$.ajax({
type: "POST",
url: args.url,
data: {
request: args.request,
formData:formData
},
success: function (data) {
alert(data);
args.callback.html(data);
},
error: function (a, b, c) {
alert("error: " + a + ", " + b + ", " + c + ".");
}
});
return false;
}
Now $_POST[formData] should work
Edit
see this as well
github.com/maxatwork/form2js
I'm trying to add ajax form submission to a PHP web app I'm working on using jquery. The form is being submitted and writing to a database, but it'll still doing it all with a refresh.
Here's my code:
$("form#form_customer").submit(function() {
var customer123first_name = $('input[name=customer123first_name.]');
var customer123last_name = $('input[name=customer123last_name.]');
var customer123date_of_birth = $('input[name=customer123date_of_birth.]');
var customer123email_address = $('input[name=customer123email_address.]');
var customer123telephone_number = $('input[name=customer123telephone_number.]');
var customer123picture = $('input[name=customer123picture.]');
var customer123id_picture = $('input[name=customer123id_picture.]');
var customer123id_expiration = $('input[name=customer123id_expiration.]');
var data = 'customer123first_name=' + customer123first_name.val() + '&customer123last_name=' + customer123last_name.val() + '&customer123date_of_birth=' + customer123date_of_birth.val() + '&customer123email_address=' + customer123email_address.val() + '&customer123telephone_number=' + customer123telephone_number.val() + '&customer123picture=' + customer123picture.val() + '&customer123id_picture=' + customer123id_picture.val() + '&customer123id_expiration=' + customer123id_expiration.val();
$.ajax({
url: "inc/createObject.php",
type: "POST",
data: data,
cache: false,
success: function(data){
$('form_success').fadeIn();
}
});
return false;
});
Everything I've read online for this specific issue has found the return false; call to be in the wrong place or not there at all. I've checked mine is in the right place, I just can't find a reason why it's refreshing.
I know jquery is working because I use it to do popups windows which are working fine.
If you want to see the code in context, go to www.sfyfe.com/studioadmin
The problem is caused by the dot at the end of the selector on your $('input[name=customer123... lines. The dot isn't doing anything, and it's making the selector invalid. Removing the dots should fix the problem. Hope this helps!
Maybe
$("form#form_customer").submit(function(e) {
e.preventDefault();
});
You should send the data in JSON format , using : " data : data " is not valid ,
try:
$.ajax({
url: "inc/createObject.php",
type: "POST",
data:{dataField : data },
Your code should be like this.
$("form#form_customer").submit(function() {
var customer123first_name = $('input[name=customer123first_name]');
var customer123last_name = $('input[name=customer123last_name]');
var customer123date_of_birth = $('input[name=customer123date_of_birth]');
var customer123email_address = $('input[name=customer123email_address]');
var customer123telephone_number = $('input[name=customer123telephone_number]');
var customer123picture = $('input[name=customer123picture]');
var customer123id_picture = $('input[name=customer123id_picture]');
var customer123id_expiration = $('input[name=customer123id_expiration]');
var data = 'customer123first_name=' + customer123first_name.val() + '&customer123last_name=' + customer123last_name.val() + '&customer123date_of_birth=' + customer123date_of_birth.val() + '&customer123email_address=' + customer123email_address.val() + '&customer123telephone_number=' + customer123telephone_number.val() + '&customer123picture=' + customer123picture.val() + '&customer123id_picture=' + customer123id_picture.val() + '&customer123id_expiration=' + customer123id_expiration.val();
$.ajax({
url: "inc/createObject.php",
type: "POST",
data: data,
cache: false,
success: function(data){
$('form_success').fadeIn();
}
});
return false;
});
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.
I'm working on an existing script at the moment which uses Ajax, something I've never worked with before. I have a variable set in my javascript file which gets its value from an input field on my page. I need to use Ajax to post this to my PHP page only I've no idea where to start,
Im not sure what code you would need to see, but My javascript/AJAX code is, the variable I need to pass is 'var credoff'
$(".getPoint").click(function () {
var theid = $(this).attr("id");
var onlyID = theid.split("_");
var onlyID = onlyID[1];
var credoff = parseInt($(this).children('input.credoff:hidden').val());
$.ajax({
url: 'do.php',
type: 'POST',
data: "userID=" + onlyID,
success: function (data) {
if (data != "success1" && data != "success5") {
$("#" + theid).text(data);
} else {
$("#thediv_" + onlyID).fadeOut("slow");
$('#creditsBalance').fadeOut("slow");
newbalance = parseInt($('#creditsBalance').text());
Wouldit have to be in this format?
data: "userID=" + onlyID,
"credoff=" + credoff
...
data: {
userId: onlyID,
credoff: credoff
},
...
Or you can do this:
data: "userID=" + onlyID + "&credoff=" + credoff
don't forget the ampersand! &