So i have a form like so:
<form>
<input type="submit" value="X" id="deleteButton" onclick="ConfirmChoice(<?php echo $id; ?>)" />
</form>
and a function like this:
<script type='text/javascript'>
function ConfirmChoice(theid)
{
var dataString = 'id=' + theid;
answer = confirm("Are you sure you want to delete this song?");
if (answer !=0) {
$.ajax
({
type: "POST",
url: "deleteSong.php",
data: dataString,
});
}
}
</script>
So basically I want it to delete whatever they click on from my database which deleteSong will take care of.
It gives the id of the song and as far as I know should confirm deletion then delete it right?
Any help would be appreciated.
Thanks
change it from
input type="submit" to
input type="button"
Also because your are not setting it, the request to the server is in json which in your case is badly formed.
Try something like this:
var dataString = "{'id'= '"+ theid + "'}";
this should make it work :)
It's hard to answer this without knowing where exactly the problem is. Is deleteSong.php working correctly?
Like others have said you should change the input type to button or return false from your function, otherwise the browser will try and submit the form in the normal manner but as you haven't specified an action within the <form> tag it won't work properly.
Personally, I would do things quite differently:
HTML:
<input type="button" value="<?php echo $id ?>" id="deleteButton">
Javascript:
$(document).ready(function () {
$('#deleteButton').click(function () {
var answer = confirm("Are you sure you want to delete this song?");
if (!answer) {
return false;
}
var data = 'id=' + $(this).val();
$.ajax({
type: 'POST',
url: 'deleteSong.php',
data: dataString,
success: function (response) {
// response will contain the output from your php script.
// Do something with it here. If you just want to see what it
// says, do something like:
console.log(response);
// then look in the console (view > javascript console in chrome)
}
});
});
});
Just to explain what I'm doing here (sorry if I'm telling you things you already know, I want to be as explicit as possible for anyone who might be reading this in the future:)
I enclose the whole thing in $(document).ready(function() { ... } ); so it only gets run when the page is finished loading, other wise you might end up trying to bind functions to the click action on a button that doesn't exist yet.
if (answer !=0) is redundant, you can just write if (!answer) as any positive integer will evaluate to true
I included a success callback above which might help you in debugging.
Is there only going to be one 'delete' button on the entire page? Or is there going to be a delete button next to every song? If it's the latter, you'll have to give each button a different ID, not just deleteButton because all IDs must be unique.
If the above doesn't work, are you sure that jQuery has loaded correctly? To check, type jQuery in the console, if you don't get an error then you're fine. The other possibility is that something's wrong with your deleteSong.php script but I can't help you there without seeing it.
Related
I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.
Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.
Now I want to pass that JS array to PHP, so I can create tables with it.
Here's what I have done.
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
elements: enc
},
success: function(data) {
console.log(enc);
}
});
});
And in my calc.php I got this to get the values to PHP.
<?php
$data = json_decode($_POST['elements'],true);
echo $data;
?>
Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:
Undefined index: elements
I am sure I am looking at this the wrong way, interpreting it wrong.
Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.
With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.
You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.
So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?
In JavaScript:
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
"elements="+enc;
},
success: function(data) {
console.log(data);// You can use the value of data to anywhere.
}
});
});
In PHP:
<?php
if(isSet($_POST[elements]))
{
$data = json_decode($_POST['elements'],true);
echo $data;
}
else
{
echo "Elements not set";
}
?>
I have php function that checks if an entry exists in my database that I call with class::checkThis($my_entry);
In my script javascript is used to determined the name of the folder I am selecting, so $my_entry is supposed to look like this :
(in normal is determined by php and the part in bold is what is determined by javascript)
C:/library/user/apatik/folder1
As you guess I can't find a working way to mix up thoses languages, and I don't really have any experience in javascript yet to figure out this.
The php code that returns the first part of the path is simply $_SESSION['cwd'].'/' and the javascript variable that returns the selected folder's name is data_name and is determined by var data_name = $(this).attr('data-name');
Is there a way to get something like if (class::checkThis($_SESSION['cwd'].'/'.data_name) == true) ?
None of what I tried so far worked and I'm having troubles finding an alternative.
Thanks for the help
You'll need to make an AJAX request to accomplish this. You'll load the page as normal, except for the dynamic part. Then you can populate the dynamic part (I've illustrated it as #content here) based on the result of the AJAX call:
var data_name = $(this).attr('data-name');
...
$.ajax('http://example.com/my_php_script.php?data_name=' + data_name)
.done(function(data){
// "data" is the resulting output of the PHP script
$('#content').append(data);
});
NOTE: The solution above uses jQuery.
Then, in your my_php_script.php, you can do something like this:
if (class::checkThis($_SESSION['cwd'] . '/' . $_GET['data_name']) == true) {
...
}
Ajax jQuery is your best solution.
This one using post method with event, just for reference...
Am I exist?
Am I exist too?
$('.anchor').click(function(){
var data_name = "name=" + $(this).attr('data-name');
$.ajax({
type: "POST",
url: "is_exist.php",
data: data_name,
success: function (data) {
alert(data.response);
}
});
};
is_exist.php
if(isset($_POST['name'])){
$data['response'] = class::checkThis($_SESSION['cwd'].'/'.$_POST['name']) == true ? "exist" : "buried";
echo json_encode($data);
}
First the code below works, but truth be told i don't know why :) it just worked after many trial and errors
I need the $_POST data submitted through the #filter-form, for loading the page as action1 function will require $_POST data.
If i remove +data or .html(data) it doesn't work anymore.
Also if i change url:"..." it does not work anymore either and i don't understand why as i don't need to to anything here, all i need is to load this page.php page and pass the $_POST so that it can output properly.
My QUESTION is, WHY does it work ? (i want to understand why putting +data or html(data) is so important to make sure $_POST is passed) and how can i make it more proper ?
Thanks for your help
<script type="text/javascript">
$("#filter-form").submit(function(event) {
$.ajax({
type: "POST",
url: "includes/page.php?action=action1",
//Specify the datatype of response if necessary
data: $("#filter-form").serialize(),
success: function(data){
alert("succeess");
$("#tableresult").load("includes/page.php?action=action1"+data).html(data);
}
});
event.preventDefault();
return false;
});
</script>';
You don't need to use .load() at all. It should be:
success: function(data) {
alert("success");
$("#tableresult").html(data);
}
This takes the response that the AJAX server returned, which should be HTML code, and puts it into the tableresult element.
The way you had it written, you're calling the server twice, which doesn't seem right.
So normally I can get my ajax to work without any issues however for some reason my script isnt passing variables through to my PHP form. Ive been trying to debug for a while and am hoping a fresh set of eyes can point out whatever dumb error I got going on (i stripped it to bare bones for simplicity, this wont pass variable).
AJAX + FORM
$('#formid').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'page.php',
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});
<form id="formid" method="post">
<input type="text" name="name">
<input type="submit" value="Add">
</form>
PAGE.php
//Get Variables
$name = $_POST['name'];
echo 'Name is: '.$name;
This should display an alert that says 'Name is (whatever the user puts in the form)' However it does not echo back what the user submits in the form. Can anyone see something wrong with this script?
Something is wrong with posting the data back to the php page data: $(this).serialize()
The code looks clean, however there may be an issue with context when doing $(this).serialize() inside the ajax function. It may be better to save your data to a variable first. The result would look something like this:
$('#formid').on('submit', function(e){
e.preventDefault();
var my_data = $(this).serialize();
$.ajax({
type: "POST",
url: 'page.php',
data: my_data,
success: function(data) {
alert(data);
}
});
});
If this doesn't work then it may actually be an issue with the PHP side.
EDIT: Added rest of JS to be more concise and clear.
You should set form method as POST:
<form id="formid" method="post">
Your code seems to be ok. $(this).serialize() should not be the problem, but if you think so, you can give an id to the text input and try data: {name: $('#your-input-id-here').val()}.
An other thing could be that e.preventDefault(); may not be working properly. Try to place it after the ajax call or replace it by return false; after the ajax call.
Thank you for all the responses, I have no idea why but adding the form in front of the id made it work. $('form#formid') I must have duplicate IDs on my page without realizing
I have a page and I ask them zipcode. While they are filling the form right after they finish writing 5 numbers of zipcode, It will check if it is covered from my database and will show a check or cross sign near it and will disable submit.
To summarize.
Will wait for visitor to type 5 digits zip code( If we can check if customer only enters number it will be a plus and great)
It will check if it is covered in database ( I don't ask for php part. Probably we will send it as POST to a php file)
If it exists in database it will show check else it will show cross and will not allow the form to be submitted.
I checked some websites but couldn't find an exact solution.
Thank you
Probably you need have an image tag besides the zip code text box with the src attribute set to an invisible image. Then perform an ajax upon the blur event.
HTML:
<input type="text" id="zip" name="zip"> <img id="imgconf" src="images/blank.png">
Javascript:
$('#zip').blur(function() {
$.ajax({
url: "script.php",
type: "POST",
data: "zip=" + $('#zip').val(),
dataType: "text",
success: function (data){
if (data=="1"){
$('#imgconf').attr("src", "images/correct.png");
} else {
$('#imgconf').attr("src", "images/wrong.png");
}
}
});
});
For the numeric validation, you may use the same PHP script to return another flag besides "1" and display it in another span element that the data entered is not numeric. Just add another key-value pair in the data part, maybe.
You will need to use AJAX. JQuery has a built in AJAX function. On each keyup event, you can have it run this AJAX function. The PHP should return a value of either 1 or 0 to make it easy. 1 obviously is match, and 0 is no-match.
$('#YourObjectID').keyup(function (event) {
searchZips();
})
function searchZips()
{
var myJSON = $.ajax({
url: options.script + '?Q=' + curValue,
type: 'POST',
contentType: 'application/json',
success: function (msg) {
if(msg==="1"){
// CODE TO SHOW YOUR X DIV
}
}
}
You will want to also add functionality on clearing the search, checking if null or empty string, etc., etc., but this is the basics that should get you going. I use this all the time. Once you get the hang of it, it's VERY useful. Then look into building a jQuery plugin. Once you can do the above functionality, you can build it into a plugin (with tons of cool options!) GOOD LUCK and happy programming.