I have this following code that works at the moment. What I want is to remove the url and process the ajax request on the same page. Since I am not sending any data, how can I have php check when my ajax function is ready to send a request to the database?
I'm using jquery mousedown to hold on to a button, then after 1 second the user receives a prompt to delete. If the user holds button 5 on the list, it will delete row 5 in mysql table, button 10 will delete row 10 etc.
$("#outter_div_5").mousedown('#button_5', function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user== "d")
{
$.ajax({
url: './ajax/5/delete.php', // <-- I want to remove this line and process this ajax request on the same page
type:'POST',
data: {},
success:function(result){
$("outter_div_5").fadeOut(125);
},
complete:function(data){
$.ajax({
url:'reload_table.php',
method:'POST',
success:function(data){
// reload javascript variables and html table
$("#my_table").html(data);
}
});
}
});
}
}, 1000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});
And my delete.php page is a simple mysql query, I'm not using a php isset since I am not passing any data.
include_once './includes/db.inc.php';
$sql = "UPDATE my_table SET row = '' WHERE id = '5' ";
mysqli_query($conn,$sql);
I need to create a php isset so that I can process this ajax request on the same page. How can I do this?
<?php
if( isset($_POST['']) ){
$sql = "UPDATE my_table SET row = '' WHERE id = '5' ";
mysqli_query($conn,$sql);
}
?>
<script>
$("#outter_div_5").mousedown('#button_5', function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user== "d")
{
$.ajax({
url: './ajax/5/delete.php', // <-- I want to remove this line and process this ajax request on the same page
type:'POST',
data: {},
success:function(result){
$("outter_div_5").fadeOut(125);
},
complete:function(data){
$.ajax({
url:'reload_table.php',
method:'POST',
success:function(data){
// reload javascript variables and html table
$("#my_table").html(data);
}
});
}
});
}
}, 1000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});
</script>
The main advantage of an HTTP (with AJAX in your case) request is that you don't have to reload the page or redirect the user to pass information the server. Some other advantages and more info can be found here. Note that php code is run before any of your javascript is run.
If you don't want to use an HTTP request, you have multiple solutions. Here's mine:
Rather than such HTTP request, you can use a form with method="POST" (read all about that) that uses a prompt before submitting:
$("#delete_button").click(function( event ){
event.preventDefault();
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user == "d") {
console.log("submitted");
//$("#myForm").submit();
}else if( prompt_user == "e" ) {
console.log("editing");
// Add your actions for editing the thing you want to edit.
}else {
console.log("aborted");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form id="myForm" action="" method="POST">
<!-- You can add inputs here to add to your POST
This data can be read when the form is submitted and the page is consequently reloaded. -->
<input id="delete_button" type="submit" value="delete">
</form>
However, if I'm being honest, I would stick with the HTTP request as this can provide a more slick user experience.
I understand you are a beginner so please feel free to ask questions if you don't understand something, we have all been there (and maybe I am still there :p).
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'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();
});
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
here is the problem.
i have HTML Form and it has a button submit with an onclick=validationFunction(). When i click this button, values from form goes to this function.
Now, in this function, the values of the form are cheenter code herecked ifenter code here they are correct or not. In addition, it has 1 input Field who has to be checked for validation, and also checked again from database to see it that value exists there. This part is done via ajax. Below the ajax call, there is a return value(boolen) for the function validationFucntion().
Now, what i want. i want either of the two things.
1) ajax should return true or false within its success
2) or ajax should send the value just below where the ajax call ends. By now, i m failing big times to do either of the things.
Here is a sample pseudo code.
function validationFunction()
{
validations checks in progress
$.ajax({
url:'checkIfNumberExists.php',
data : {
'number : num //this num is coming from above
},
method:'GET',
success: function(data)
{
console.log("Return Value = "+this.toReturn);
if( (this.toReturn) > 0 )
{
either return validationFunction from here or set a flag.
}
else
{
either return validationFunction from here or set a flag.
}
});
}
checkIfNumberExists.php
<?php
$num = $_GET['number'];
$toReturn = 0 ;
$queryCheckNo = mysql_query('SELECT * FROM `TABLE` WHERE `number_from_table`="'.$num.'" ');
while($row = mysql_fetch_assoc($queryCheckNo)){
$toReturn++;
}
echo ($toReturn);
?>
try this plug in
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and keep this inside your form
<form id="tempForm" enctype="multipart/form-data">
<input type="file" name="" id="" />
</form>
and you can find the plug in here
I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.