how to make a request several times without hard refresh with ajax - javascript

I send a request via ajax to delete a file. The first time , ajax handles the request, but the second time not anymorte. i got a "hard refresh"
This is my code:
<?php
if(isset($_POST['deletefile'])) {
// if is directory -> remove dir
if(is_dir($_POST['deletefile'])){
removeDirectory($_POST['deletefile']);
exit;
}
// else (must be a file) -> unlink file
else {
unlink($_POST['deletefile']);
exit;
}
}
?>
<div class="myFiles">
<form class="sfmform" method="post" action="">
<input type="hidden" name="deletefile" value="<?php echo $dir.'/'.$file; ?>" />
<input type="submit" class="sfmdelete" name="delete" value=" " />
</form>
<script>
$(".sfmform").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(response)
{
$('.myFiles').load(document.URL + ' .myFiles');
},
});
}));
</script>
</div> <!-- END myFiles -->
To see immediately when i file has been deleted, i use this line
$('.myFiles').load(document.URL + ' .myFiles');
The first delete request goes fine, but the second: he makes a hard refresh and dies in the php loop. I was hoping that after the exit in the php the line $('.myFiles').load(document.URL + ' .myFiles'); was executing but the second time it loads not the <div class="myFiles> anymore.
How can i make this work properly?
Even when i put the js in the ready handler, it does not work!
The reason why i use an exit in the php: otherwise the <div class="myFiles"> appears 2 times under each other

You changed the html of .myFiles so everything in it in the second time is dynamically generated . so you need Event binding on dynamically created elements? .. change
$(".sfmform").on('submit',(function(e) {
to
$(document).on('submit' , ".sfmform" , (function(e) {
Note: for me its not a good practice to use $.ajax with the same file url: better for me to make a separate file

Related

Javascript & PHP ajax error: "Undefined array key"

for several days I have been facing the problem that PHP cannot find my index.
What I've tried:
Change the data name in ajax
I added the code from PHP Create.php to create.php (at the beginning and at the end of the code)
Various ajax possibilities
The goal
I want to save an image which I have cropped with (cropper.js), using PHP on a SQL server.
My code:
OnSetData.js
canvas = cropper.getCroppedCanvas({
width:700,
height:700
});
canvas.toBlob((blob) => {
url_img = URL.createObjectURL(blob);
//url_img = blob:https://localhost/a37a7cd8-ad48...
$.ajax(
{
url:'assets/php/PHPCreate.php',
type: 'POST',
data: {'image':url_img},
success:function(output) {
console.log('Upload success: ' + output);
//Upload sucess: <output is empty>
},
error() {
console.log('Upload error');
},
});
}, 'image/png');
PHPCreate.php
if (isset($_POST['save_submit']))
{
$data = $_POST["image"];
//Warning: Undefined array key "image" in ..\assets\php\PHPCreate.php on line ..
echo($data);
}
create.php
<link href="assets/assets/cropperjs-main/dist/cropper.css" rel="stylesheet">
<script src="assets/assets/cropperjs-main/dist/cropper.js"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/OnSetData.js"></script>
<?php
include './assets/php/PHPCreate.php';
?>
.
.
.
.
<form id="formUpload" action="" method="post" class="form-inline" enctype="multipart/form-data">
<button class="btn btn-primary text-uppercase" role="button" name="save_submit" type="submit">Save</button>
</form>
i think you will open create.php in browser
create.php has a form that sends "save_submit" to izself as a new request
so create.php will be opened again but this time with "save_submit", nothing else, so yes, there is no image, that is correct
now lets look at OnSetData.js:
it makes a separate request to PHPCreate.php with "image", but no "save_submit" so PHPCreate.php will do nothing
to clearify:
the button in the form will make a site navigation
OnSetData.js will make a request on its own
both request are handled in separate

Trying to send js variables to a php file

I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null.
My goal is to send the data to finalmap.php and redirect to it.
To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work.
<button type="button" id="submit-button">FINISH</button>
Note, no <form> is needed; you're submitting through AJAX.
Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
You use your web console to see the console.log message.
Now, try out the ajax command with a simple post:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
finalmap.php
<?php echo 'This is finalmap.php';
If you see This is finalmap.php in the web console after pressing the button, then you can try sending data.
finalmap.php
<?php
echo 'You sent the following data: ';
print_r($_POST);
See where we're going with this? The way to eat an elephant is one bite at a time.
./finalmap.php is not a thing.
Instead the code must look like this:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
Try using this instead.
EDIT: OOPS SORRY, I JUST CPED AND PASTED.

Having problems figuring out AJAX POST functions

I am trying to post using AJAX because I don't want to use a submit button and reload the page everytime I click it.
I am using this code for ajax:
<script language="JavaScript"><!--
function postit()
{
var frm = $('#pmconfirm');
$.ajax({
type: "POST",
url: "bitcin",
data: frm.serialize(),
success: function(msg){
$("#main").hide();
$("#main").html(msg).show();
},
error: function(msg){
$("#main").html("<font color='#ff0000'>Ajax loading error, please try again.</font>").show();
}
});
}
setTimeout("postit()",2000);
//--></script>
Next, I am using this form:
<form action="" name="fcaptcha" method="post">
<input type="hidden" id="bitcoin" name="bitcoin">
<input type="hidden" id="pmconfirm" name="pmconfirm" src="http://www.mvixusa.com/newsletter/2010/11/newsletter-membership-confirmation/images/confirm-button.png" alt="Submit Form" onclick=\"document.getElementById("fcaptcha").submit()\"/>
</form>
<div id="main">
</div>
This works it posts but I doesn't give me results ?
if (isset($_POST['bitcoin']))
{
// My code here works, because it works when i dont use ajax
// And I have some things to check like if it wasnt what i wanted
// it returns some message which is shown with php.
}
<div id="messaget">
<?php
if($failed == 1) echo $messages;
?>
</div>
This is the part where the messages should be displayed, I tried using a tag #messaget to display the HTML after post but it didn't work, I tried displaying the entire page in this page it still didn't work.
And the url: "bitcin", is entirely ok, i used htaccess.
Can somebody spot where the problem is ?
Add an id to the form :
<form id="pmform" action="" name="fcaptcha" method="post">
And change Js to:
var frm = $('#pmform');
When performing:
............
data: frm.serialize(), //this will take the form and make an array based on the names of the form elements thus having them accessible in the PHP script
..........

image button - no page change

I'm trying to call a php file without refreshing the page. The code executes the php file, but the value toid is not being passed along. If i manually query the page then it works fine. The other issue im having is the button needs to be an image with the path src="{ROOT_PATH}mchat/quote.gif"
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo {mchatrow.MCHAT_USERNAME}; ?>">
<div id="button_block">
<input type="submit" id="button" value="Enter">
</div>
</form>
<script>
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
$.ajax({
type: "POST",
url: "randomquote.php",
data: "toid=" + toid,
});
});
});
</script>
Any ideas?
When you say "if i manually query the page then it works fine", does that mean hitting the endpoint directly like
http://yoursite.com/randomquote.php?toid=239439
Have you tried sending the data as an object (like this):
$.ajax({
type: "POST",
url: "randomquote.php",
data: { toid: toid }
});
That may do the trick.

PHP Ajax button press conundrum

I have been trying to have a button execute a PHP script on a page and refresh just a div tag without any success. When I remove the $ajax part of the script my buttons change state but when I add the ajax part again nothing happens.
I need to load some content from a PHP file and then change the button's and div tags state. Some help will be very much appreciated as I can't seem to find the problem.
<div id="noah-content">
<script>
$(document).ready(function() {
$("#ON'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = true;
document.getElementById("OFF'.$id.'").disabled = false;
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src");
}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
$("#OFF'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = false;
document.getElementById("OFF'.$id.'").disabled = true;
});
});
</script>
<img src="images/about.png" alt="image" id="myimg" />
<input type="submit" class="ON" id = "ON'.$id.'" value=" ON " name="submit"/>
<input type="submit" class="OFF" id = "OFF'.$id.'" value=" OFF " name="submit" disabled="disable"/>
</div>
Lets start with evaluating your php:
In order to run your php you have to open php tags:
$("#ON<?php echo $id ?>")...
Replace it everywhere you want your id to appear. For debugging, open your page source in the browser and see what is being generated:
Example:
<input type="submit" class="ON" id="ON<?php echo $id ?>" value="ON" name="submit"/>
Firstly, your ids for your html tags, and the way you reference them in js, seem odd (though still perhaps valid when dropped into js or html as strings). Looks like your trying to reference a php value in an improper way in html and js.
Second, are you getting any errors on your javascript console? Does the ajax query complete (i.e. do you get the alert message)? Check your JS console because that will tell you something more than 'nothing happens'
Also
I usually use the success option for ajax rather than the done method. Personal choice.
You also have a syntax error after $(this).attr("src");. The semicolon indicates the end of a line of code usually, and you put it after an element in your array/object declaration for your data.
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src") //Removed the semicolon that was here
},
success: function(data){alert(msg)}
});

Categories