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)}
});
Related
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
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.
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
..........
Hard to explain in the title...
So i have a form which is validated via javascript and an ajax request is sent to a php page which if succesful inputs the data and sets the database response.
However, on the ajax call getting the correct repsonse it doesnt carry out what i wish it to...
I What i want to happen is when the php returns a success JSON return, the .commentsdiv is reloaded.
This doesnt work however. But the comments are added into the database.
here is the code
part of commentsbox div and form:
<div class="commentsbox">
<form class="addcomment" action="process/addcomment.php" method="post">
<input type="hidden" class="postid" name="postid" value="'.$postID.'">
<input type="hidden" class="usernameuser" name="usernameuser" value="'.$usernameuser.'">
<input type="hidden" class="userid" name="userid" value="'.$userid.'">
<input type="text" name="addpostcomment" class="addpostcomment" placeholder="Add Comment..." />
<input type="submit" id="addcommentbutton" value="Post" />
<br />
<br />
</form>
</div>
Here is the javascript:
The viewbuild.php url is dynamic depending on what post is viewed. Do i need it to be like viewbuild.php?id=1 etc? Because that doesnt work niether.
// JavaScript - Edit Post
$(document).ready(function(){
$(".addcomment").submit(function(){
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $comment = $targetForm.find('.addpostcomment'),
newcomment = $comment.val();
// Validation
if (newcomment == '') {
check = false;
$comment.after('<br><br><br><div class="error">Text Is Required</div>');
}
// ... goes after Validation
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess) {
$('.commentsbox').load('viewbuild.php');
}
else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
Here is part end of php:
$return['databaseSuccess'] = $dbSuccess;
echo json_encode($return);
Any help is most appreciated! :)
Make sure your php response is setting the proper headers. You need to set the content type as "application/json" for JQuery to call the success function. Try adding debugging to the error or complete callbacks when you call the jquery ajax function.
well , why am i thinking that you should check what value the obj returns ..
i mean ..
if(response.databaseSuccess == ??! ) { ... }
Or why don't you just check for the length of the retruned string.
if(response.databaseSuccess.length > 3){ alert('ok');}
One advise bro, if you are returning JUST one parameter .. use e string .. not JSON .. ;)
so, in php you would have :
echo $databaseSuccess;
And in JS .. the IF wil be more simple :
if(response == "ok"){ alert('ok');}
Get it ?
Hope i've helped.
Thats the best description I could think of. I normally do not post, but I honestly cannot figure this out.
Still in jquery learning mode, and basically what I want to accomplish is that depending on the type of button that is submitted, the script assigns variables to div's on the page. What I am making is a admin side of a user script to allow them to update that particular div that appears on the page.
When I put in the actual selectors, the script works.
When the page loads, it will take the field of the database that corresponds with the and load it. Once they push the update button, a new div will appear. The admin inputs his new data (the new information he wants to display) and it updates the mysql table, then pulls it back in through jquery's ajax.
Sorry for the long explanation. Like I said, I've never really posted, just always liked figuring it out on my own.
php page
<?php //
if(isLoggedIn())
{
echo '<button id="adultClassButton">Edit Class Information</button>';
}
?>
<div class="class" id="adultClass"><?php
$row = checkPost('adult');
echo $row['info'];
?>
</div>
<?php
echo '<div id="adultClassInput">
<textarea rows="2" cols="80" id="adultClassUpdate"></textarea>
<input type="hidden" id="className" name="adult"/>
<button id="adult">Save the Updated Class Info</button></div>';
?>
javascript (jquery) file
$(".button").click(function(){
var button = $(this).attr('id');
if (button == 'adult'){
var classDiv = $("#adultClass");
var className = $("#className");
var classDesc = $("#adultClassUpdate").val();
var classUpdateDiv = $("#adultClassInput");
postData(classDiv, className, classDesc, classUpdateDiv);
}
});
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: "name="+ className+ "& info="+ classDesc,
success:function(data){
$("#" + classDiv).html(data);
}
})
$("#" + classDesc).val('');
$("#" + classUpdateDiv).hide();
}
Like I said, if I have normal selectors in the function, it works as intended. But as of right now, I'm just stumped as to whats wrong.
Thanks a bunch!
classDiv is a jquery object not the ID of the element. So when you use this
$("#" + classDiv).html(data);
That's not working as expected.
Try
classDiv.html(data);
Your function should be like this:
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: {"name": className.val(), "info": classDesc}
success:function(data){
classDiv.html(data);
}
})
$("#"+classDesc).val('');
classUpdateDiv.hide();
}
because you already passed jquery objects (not strings) to your function, except for classDesc.
Hope this helps. Cheers