Posting to a PHP script with Ajax (Jquery) - php

I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.

The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)

Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.

Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)

I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick

Related

Understanding AJAX php script for clue game practice

I'm trying to understand the relationship between a PHP script I'd like to run to keep track of progress and the front end work that has taken place. Its 2 clues in a game practice. Once the clue is inputted correctly everything occurs as below and I want to add a script that sends to MYSQL.
I'm working on the script now, but I'm trying to figure out at what point I'd introduce this. Is there anything I'd need within my PHP to distinguish it as AJAX. As in to run it in the background? Do I just "include" it as I would part of another larger PHP script?
The script in my mind will send a 1 if correct or 0 if still wrong. This way I can easily determine without having to deal with clues. The clues are irrelevant in my thinking, but what is your opinion on this?
// =====clue 1====================////////////////// clue 1 **************
//**********************************========================
$(document).on('click', '.btn-clue', function(){
if($i!=1){
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueTwo: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
});
} else {
$("#mySecondDiv").remove();
var mySecondDiv = $('<div id="mySecondDiv"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongOne').append(mySecondDiv);
}
}
});
// =====clue 2====================////////////////// clue 2*********=========
$(document).on('click', '.btn-clueTwo', function(){
if($i!=1){
//checking if textbox has desired value (1 in this case),
//in your application you would be passing the textbox value to
//ajax here and making the check at server side
var $two = $('#twoClueShow');
var x = $("#clueTwoInput").find('input[type=text]').val();
if(x == 'C' || x == 'CS') {
// if answer correct you should load data from ajax
// and append it to a container
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
} else {
$("#mySecondDivClueTwo").remove();
var mySecondDivClueTwo = $('<div id="mySecondDivClueTwo"><img src="images/check-x-mark.png" /></div>') .show('slow');
$('#clueWrongTwo').append(mySecondDivClueTwo);
}
}
});
Above is where I've been able to get. Now here is where I'm getting confused. I now want to send to the database that the answer has been answered correctly through AJAX, correct? Would I just include_once my php script in the commented area.
I was thinking of creating a script that filled a 1 if correct and 0 if not correct to make life easier. Let this do the work as I don't need to reintroduce the inputs or re use. This way once the page has reloaded I could simply not output the inputs again and use this info to determine what is displayed and where they are at in the clue game. Basically saving progress.
Is there something specific to use when building my normal PHP. I guess that and where to "include" it is where I'm confused.
MY button for reference
<div id="clueOneInput">
<input type="text" id="clue1" class="clue-text form-control" placeholder="Enter Clue 1 here and check"/>
</div>
<input type="button" id="clue1Input"class="btn btn-primary btn-clue" value="Check">
Update :
// =====clue 1====================////////////////// clue 1**********************************************************************========================
$(document).on('click', '.btn-clue', function(){
if($i!=1){
//checking if textbox has desired value (1 in this case),
//in your application you would be passing the textbox value to ajax here and making the check at server side
var $one = $('#oneClueShow');
var x = $("#clueOneInput").find('input[type=text]').val();
if(x == 'd' || x == 'dr')
{
//if answer correct you should load data from ajax and append it to a container
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueOne: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongOne").hide();
$("#mySecondDiv").remove();
$("#clueOne").remove();
$("#clue1Input").remove();
$one.show();
$("#clueOneInputCorrect").slideDown('slow').show();
$i++;
});
}
else
{
$("#mySecondDiv").remove();
var mySecondDiv = $('<div id="mySecondDiv"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongOne').append(mySecondDiv);
}
}
});
// =====clue 2====================////////////////// clue 2**********************************************************************========================
$(document).on('click', '.btn-clueTwo', function(){
if($i!=1){
var $two = $('#twoClueShow');
var x = $("#clueTwoInput").find('input[type=text]').val();
if(x == 'CS' || x == 'CSU')
{
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueTwo: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
});
}
else
{
$("#mySecondDivClueTwo").remove();
var mySecondDivClueTwo=$('<div id="mySecondDivClueTwo"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongTwo').append(mySecondDivClueTwo);
}
}
});
In your Jquery
$.ajax({
type: "POST",
url: "yourScriptToUpdateDB.php",
data: { clue: "Wrong", user: "JoeBob" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongOne").hide();
});

jQuery form validation taking too long on submit

There is fairly complex php POST form with great deal of data validation using jQuery like below. However, I'm running into some problems cause it seems like form is getting submitted before the validation gets completed.
Question : Is it possible that the validation is taking so long, that the form is submitted by default, before jQuery has even returned true or false? If so, what is the best way to deal with this?
jQuery('#order-form').submit(function(){
// Validate many different fields in various ways
if (valid)
return true;
else
return false;
});
Since we can't see your code and how it validates, maybe you can try your function another way.
Try and use the click function on your submit button to validate your items, then if all is good, submit.
e.g.
$('#btn1').click(function(e){
var valid
if($('#ex1').val() == ""){
valid = false;
}else{
valid = true;
}
if(valid){
$("#testform").submit();
}else{
alert("not validated");
}
e.preventDefault();
});
See fiddle as example.
http://jsfiddle.net/em62Z/1/
Also I use this plugin to validate my forms. It can validate any size form and even some complex fields.
https://github.com/posabsolute/jQuery-Validation-Engine
It works well and might save your trouble doing your own validation if you are doing your own.
Here is the code snippet as an example for contact form that can help you, i used jqueryvalidation.org plugin and posting form using ajax
$(function() {
var form = $("#contact_form").validate();
$('#progressbar').hide();
$('#success').hide();
$('#failure').hide();
$(document).ajaxStart(function() {
$( "#progressbar" ).show();
});
$(document).ajaxStop(function() {
$( "#progressbar" ).hide();
});
$("form#contact_form").submit(function() {
if(form.valid())
{
//any other validations here
var name = $("#txtName").val();
var email = $("#txtEmail").val();
var phone = $("#txtPhone").val();
var message = $("#txtMessage").val();
$.ajax({
url: "process_contact.php",
type: "POST",
data: {'name': name,
'email': email,
'phone': phone,
'message': message},
dataType: "json",
success: function(data) {
if(data.status == 'success')
{
$('#contact_form').hide();
$('#success').show();
}
else if(data.status == 'error')
{
$('#failure').show();
}
}
});
return false;
}
});
});
As far as I know, only two conditions that your case could happen :
there is an error in your validation's code, or
javascript is turned off.
In regard of client side validation, have you tried jQuery Validation? It validate every elements in form on two events :
everytime elements are changed, and
when form is submitted.
You could also add custom method to do a unique validation for each condition in each element.
For more info and examples (with and without ajax) regarding jQUery Validation : here.

Jquery POST to refresh a div

I want to use $.post function of jquery to do a div refresh, only if the content returned in the json data from the php script is modified. I know that ajax calls with $.post are never cached. Please help me with $.post, or $.ajax if it is not possible with $.postor any other method with which this is possible.
Thanks
Why don't you cache the response of the call?
var cacheData;
$.post({.....
success: function(data){
if (data !== cacheData){
//data has changed (or it's the first call), save new cache data and update div
cacheData = data;
$('#yourdiv').html(data);
}else{
//do nothing, data hasan't changed
This is just an example, you should adapt it to suit your needs (and the structure of data returned)
var result;
$.post({
url: 'post.php'
data: {new:'data'}
success: function(r){
if (result && result != r){
//changed
}
result = r;
}
});
Your question isn't exactly clear, but how about something like this...
<script type="text/javascript">
$(document).ready(function(){
$("#refresh").click(function(){
info = "";
$.getJSON('<URL TO JSON SOURCE>', function(data){
if(info!=data){
info = data;
$("#content").html(data);
}
});
});
});
</script>
<div id="content"></div>
<input id="refresh" type="submit" value="Refresh" />
I think you should use .getJSON() like I used it there, it's compact, and offers all the functionality you need.
var div = $('my_div_selector');
function refreshDiv(data){
// refresh the div and populate it with some data passed as arg
div.data('content',data);
// do whatever you want here
}
function shouldRefreshDiv(callback){
// determines if the data from the php script is modified
// and executes a callback function if it is changed
$.post('my_php_script',function(data){
if(data != div.data('content'))
callback(data);
});
}
then you can call shouldRefreshDiv(refreshDiv) on an interval or you can attach it to an event-handler

jquery ajax post - how to get data back?

I have a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:
delete.php
<?php
if (isset($_POST['id'])) {
if (unlink($_POST['id'])) {
echo "success";
}
else {
echo "failure";
}
}
?>
(There's already user authentication in place just to get them to the page that calls delete.php.)
Here's the html of one displayed image - there can be up to 5 of these chunks one after another:
<div class="box">
<img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" />
<h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5>
<a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
<div class="clear"></div>
</div>
My jQuery so far looks like this:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(data){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?
Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case
success: function(data){
/*The code you need*/
});
The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.
Hope this helps a bit.
Edit Note:
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.
This is the php that executes:
if ( !$db->isGlobal($id_css)){
$data['id_poll'] = $id_poll;
$data['id_css'] = $id_css;
$data['css'] = $css;
$db->applyCssChanges($data);
}
else{
echo 'invalid';
}
You've two obvious options I can think of:
Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:
Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.
From delete.php return whether the delete succeeded or not. In the success even check for that data and handle it appropriately.
HTH.

jQuery Ajax submission problems

Why doesn't the following pick up the form? All it does is just to do a normal PHP post without throwing any errors...
I'm using blockUi on this as well, hence block/unblock.
$(document).ready(function(){
$("input.update").click(function(){
var str = $(this).parent().serialize();
$(this).parent().parent().block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
$.ajax({
type: "POST",
url: "forms/update.php",
data: str,
success: function(){
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
}
});
return false;
});
});
This is my first attempt at using jQuery's Ajax functionality so please bear with me.
("input.update").click(function(){
should be
$("input.update").click(function(){
Since it seems you're only using the 'success' callback of post you could use the .post method, which is a bit easier on the eyes. Also you can put those block calls inside ajaxStart and ajaxStop. To me it's neater.
The $(this).parent().parent().block seemed wrong to me, I changed it to reference the same element that is used for unblocking. I'd also be checking the output of the PHP script, to make sure that whatever you are 'updating' actually is updated (just echo XML from PHP and you'll see it on your console log).
$(function() {
// Apply click handlers to anchors
$("input.update").click(function(e){
// Stop normal link click
e.preventDefault();
var str = $(this).parent().serialize();
// Send request
var action = "forms/update.php";
$.post(action, {data:str}, function(xml) {
console.log(xml);
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
})
});
// Adds a wait indicator to any Ajax requests
$(document.body).ajaxStart(function() {
$("div.edit_box").block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
}).ajaxStop(function() {
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
});
});

Categories