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();
});
Related
So I have been working on this for hours now, I have read a bunch of StackOverflow posts and I am still having no luck.
I have a page that has 2 sections to it, depending on the int in the database will depend on which section is being displayed at which time.
My goal is to have the page look to see if the database status has changed from the current one and if it has then refresh the page, if not then do nothing but re-run every 10 seconds.
I run PHP at the top of my page that gets the int from the database
$online_status = Online_status::find_by_id(1);
I then use HTML to load the status into something that jquery can access
<input type="hidden" id="statusID" value="<?php echo $online_status->status; ?>">
<span id="result"></span>
So at the bottom of my page, I added some jquery and ajax
$(document).ready(function(){
$(function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$newResult = $('#result').html(data);
window.setInterval(function(){
liveCheck();
}, 10000);
}
}
});
});
liveCheck();
});
this then goes to another PHP page that runs the following code
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
echo "<script>location.reload();</script>";
}else{
}
}
the jquery then loads into the HTML section with the id of "result" as shown earlier. I know this is a very bad way to do this, and as a result, it will work at the beginning but the longer you leave it on the page the slower the page gets, till it just freezes.
If anyone is able to point me towards a proper method I would be very grateful.
Thank you!!
js:
(function(){
function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(data.trim() == ''){
location.reload();
}else{
$('#result').html(data);
window.setTimeout(function(){
liveCheck();
}, 10000);
}
}
});
}
$(function(){
liveCheck();
});
})(jQuery)
php:
<?php
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
$data = '';
}else{
$data = 'some html';
}
echo $data;
}
Your page is slowing down because you are creating a new interval every time you call the liveCheck function. Over time, you have many intervals running and sending requests to your PHP file concurrently. You can verify this behavior by opening the developer console in your browser and monitoring the Network tab.
What you should do instead is set the interval once, and perform the $.ajax call inside that interval. Additionally, it's good practice to not send a new request if a current request is pending, by implementing a boolean state variable that is true while an request is pending and false when that request completes.
It looks like the intended behavior of your function is to just reload the page when the $online_status->status changes, is that correct? If so, change your PHP to just echo true or 1 (anything really) and rewrite your JS as:
function liveCheck() {
if (liveCheckPending == true)
return;
liveCheckPending = true;
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST'
}).done(function(data){
if (!data.error)
location.reload();
}).always(function(data){
liveCheckPending = false;
});
}
var liveCheckPending = false;
setInterval(liveCheck, 10000);
I have created one application in that there is one text box for searching information from table. Although i have written the code when we enter the character in search text box, after accepting one character control goes out of textbox.
this is my code for searching`
<script type="text/javascript">
$(document).ready(function()
{
var minlength = 1;
$("#searchTerm").keyup(function () {
value = $(this).val();
if (value.length > minlength )
{
searchTable(value);
}
else if(value.length < minlength)
{
searchTable("");
}
});
});
function searchTable(value)
{
$.ajax({
type: "GET",
url: "dispatient.php",
data:({search_keyword: value}),
success: function(success)
{
window.location.href = "dispatient.php?search_keyword="+value;
$("#searchTerm").focus();
},
error: function()
{
alert("Error occured.please try again");
},
complete: function(complete)
{
$("#searchTerm").focus();
},
});
}
<input id="searchTerm" Type="text" class="search_box" placeholder="Search"
value = <?php echo $_GET['search_keyword'] ?> >
`
Please suggest to me..
thanks in advance..
value is default attribute of javascript try to change the variable name of value into something like searchData
In your success callback, you are redirecting the page to dispatient.php. I believe, this is the same page that has the search functionality. Once you redirect, the page is reloaded again and there is no point in writing:
$("#searchTerm").focus();
Since, you are already using AJAX, try loading the data from success on to your page through JavaScript/jQuery without reloading the page.
create one div and load your data in that instead of reloading entire page.
try something like this instead of ajax Call
<div id="searchResult"></div>
$("#searchResult").load("search.php?search_keyword=value",function(){
//your callback
});
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
I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.
I have this
"fsField" is the class of all elements in the form. So whenever the user blurs to another field it submits the form using the function autosave() - given below. It saves data when the user blurs but when the user clicks the button with class "save_secL" to go to next page it does not save.
$('.fsField').bind('blur', function()
{
autosave();
}
});
but when i use this code
$('.save_secL').click(function()
{
var buttonid = this.id;
{
var answer = confirm("You have left some questions unanswered. Click OK if you are sure to leave this section? \\n Click CANCEL if you want stay in this section. ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="unanswered" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="answered all" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
});
**autosave_secL.php is the php source thats saving the data in the database. I ran it independently and it does save data okay. **
function autosave()
{
var secL_partA_ques_1_select = $('[name="secL_partA_ques_1_select"]').val();
var secL_partA_ques_1 = $('[name="secL_partA_ques_1"]:checked').val();
var secL_partA_ques_2_select = $('[name="secL_partA_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partA_ques_1_select=" + secL_partA_ques_1_select + "&secL_partA_ques_1=" + secL_partA_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
}
});
}
**
valid() is a validation function that checks if any field is empty and returns a value if there is an empty field.**
function valid()
{
var items = '';
$('.fsField').each(function()
{
var thisname = $(this).attr('name')
if($(this).is('select'))
{
if($(this).val()=='')
{
var thisid = $(this).attr('id')
items += "#\"+thisid+\",";
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '#B5EAAA');
}
}
else
{
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '');
}
});
return items;
}
Can anyone please help? i am stuck for a day now. Can't understand why it saves when the user goes field to field but does not save when button is clicked with validation.
Tested with Firefox. this line appears in red with a Cross sign beside when the button(save_secL class) is clicked. I am using a ssl connection.
POST https://example.com/files/autosave_secL.php x
Here is the modified code trying to implement the solution
$('#submit_survey_secL').click(function()
{
if(valid() !='')
{
var answer = confirm("You have left some questions unanswered. Are you sure you want to Submit and go to Section B? ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=4"
});
}
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=6"
});
}
});
function autosave(callback)
{
var secL_partL_ques_1_select = $('[name="secL_partL_ques_1_select"]').val();
var secL_partL_ques_1 = $('[name="secL_partL_ques_1"]:checked').val();
var secL_partL_ques_2_select = $('[name="secL_partL_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partL_ques_1_select=" + secL_partL_ques_1_select + "&secL_partL_ques_1=" + secL_partL_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
{
callback();
}
}
});
}
I don't understand why this doesn't work as callback should totally work. Firebug does not show POST https://example.com/files/autosave_secL.php in red any more but it shows that it has posted but I think the callback is not triggering for some reason
$('.save_secL').click(function() {
//...
//start autosave. Note: Async, returns immediately
autosave();
//and now, before the POST request has been completed, we change location...
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
//....and the POST request gets aborted :(
Solution:
function autosave(callback)
{
//...
$.ajax(
{
//...
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
callback();
}
});
}
//and
autosave(function(){
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
});
By the way, your autosave function is pretty hard for your server. Did you consider using localStorage + a final POST request containing all data?
I got the solution.
It might be one of the several. scr4ve's solution definitely helped. So here are the points for which I think its working now.
Moved "cache: false, " and removed "async:false" before url: in the ajax autosave function. Before I was putting it after "data: "
Added a random variable after autosave_secL.php/?"+Match.random()
Added scr4ve's solution so that POST is completed before redirect