I'm trying to confirm deleting something, but I can't seem to get it to work.
When the button for 'deleteReply' I'm getting an alert message, but as far as I can tell nothing else is happening. I'm trying to simply echo the posted variable but it doesn't seem to work.
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
On my delete processing page I just have
$echo $_POST['replyID'];
Why do you have
if(isset($_POST['deleteReply'])){
?>
Before the javascript function? Did you expect to trigger the javascript code based on the $_POST['deleteReply'] var?
You have to keep in mind that php is processed server-side and outputs an HTML page. Your javascript code will only run in the client after all the php has run.
A much more elegant solution would be asking for a confirmation BEFORE sending the AJAX request.
And also, your ajax call doesn't seem to do what you're expecting. You're manually setting 2 parameters to send to your PHP which will have no use for it if you do the confirmation server-side.
A parameter should be something like the Reply ID of the reply you want to delete, and send the request to a different php file for handling.
I'd suggest you rewrite your code as Marian Zburlea is doing for you.
EDIT
Ok, if you want a simple confirm window, try this:
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('delete.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
EDIT
If you have multiple delete buttons, the best way to do this would be storing the replyID as the parameter to pass to your function. Echo your delete buttons in your php like this:
echo '<input type="button" value="Delete" onclick="deleteSomething(\'' . $replyID . '\')" />';
This way, the $replyID will be stored in the page's HTML, which will be passed to the deleteSomething(replyID) function which you now have to define (preferably in the document's head after the JQuery lib):
<script type="text/javascript">
function deleteSomething(replyID)
{
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
}
</script>
Note that I removed the ID from the buttons to don't generate dupplicate IDs and they are no longer needed, as I've added a function call in the onclick event instead of binding an anonymous function to their IDs as you were doing previously.
<input type="button" id="deleteSomething" value="Delete" />
<div id="yesno" style="display:none;">
<input type="button" id="buttonYes" value="Yes" />
<input type="button" id="buttonNo" value="No" />
</div>
<script type="text/javascript">
// Here you attach a click event to the button Yes with id buttonYes
$('#deleteSomething').click(function() {
$('#yesno').css('display', 'block');
});
$('#buttonNo').click(function() {
$('#yesno').css('display', 'none');
});
$('#buttonYes').click(function() {
$.ajax({
beforeSend: function(e) {
// Code to process before calling AJAX
},
url: "pathToPHPFile.php",
dataType: "json",
type: "POST",
data: {
parameter: 'Yes',
},
success: function (m) {
console.log(m);
alert(m.text);
},
error: function (e) {
console.log("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
// This is a separate php file named pathToPHPFile.php
if(isset($_POST['parameter']) && $_POST['parameter'] == 'Yes'){
/* here you put the code that deletes the message */
$response['text'] = 'messageDeleted'
echo json_encode($response);
}
Related
I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}
I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
I have tried searching quite a bit but can't seem to make anything work.
I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.
What I have so far:
HTML:
<html>
<form id="form">
<input id="info" type="text" />
<input id="submit" type="submit" value="Check" />
</form>
<div id="result"></div>
</html>
JS:
<script type="text/javascript">
var info= $('#info').val();
var dataString = "info="+info;
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
});
</script>
PHP:
<?php
$url = '/api.php?&info='.$_POST['info'];
$reply = file_get_contents($url);
echo $reply;
?>
When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.
I cannot get any solutions to work.
Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
return false;
});
Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(
Thanks everyone for your help, I have it working now.
I was doing a few things wrong:
I was using single quotes in my php file for the URL and also for the $_POST[''] variables.
I needed to add return false; as Steve pointed out.
I did not have a "name" for the input elements, only an ID.
I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax. The code below.
/* ... */
$('#submit').click(function (){
$.ajax({
var info= $('#info').val();
var dataString = "info="+info;
/* ... */
I am using a single form in two different scenarios - Create and Edit.
I do something like
<?php
if($status == 'new')
echo '<button id="btnSubmit" type="submit" class="btn">Submit!</button>';
else
echo '<button id="btnEdit" type="submit" class="btn">Edit!</button>';
?>
What I want to achieve on my javascript end is to validate the form and call the correct web service according to which button is pressed. I am using the jQuery Validation Plugin found here.
Javascript
$('#myForm').validate({
submitHandler: function(data) {
$.ajax({
url: "service1.php"
...... other AJAX stuff ..........
});
}
}
$('#btnSubmit').click(function() {
// call service1.php
});
$('#btnEdit').click(function() {
// call service2.php
});
The method for validate can be a single function and you can set a flag(For example you will get an id in the edit page) to identify edit page or add page. So that you can check the flag in submit handler and submit the form to where it needs to be submitted. I'm not familiar with PHP and i hope this might help you.
Based on Marikkani's suggestion, I have implemented the below and it works. Hope it helps someone with a similar problem using Javascript and PHP.
In my form file I used a hidden div to store the type (new or edit).
<input type="hidden" id="type" value="<?php echo $type; ?>" />
Thereafter, in my javascript file I retrieve this value and check before calling the respective ajax.
$('#resForm').validate({
submitHandler: function(form) {
var type = $('#type').val();
if(type == 'new') {
$.ajax({
url: "service1.php"
.... other AJAX stuff
});
} else { // type is edit
$.ajax({
url: "service2.php"
.... other AJAX stuff
});
}
}
});
I'm sending form data to a PHP file via AJAX, using jquery I hoped I could send the data easily seeing as it's only one text box etc. On submit click event the form data should be serialised and sent to submit.php, then I should get an alert from the php file with the response. Why doesn't it work?
Thanks.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$('#submit').click(function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
</script>
Then the HTML:
<form id="myform" >
<input type="text" name="content" value="button should be on same line" /><input
type="submit" class="button" value="Submit" id="submit" />
</form>
You haven't initalized the DOM ?
$(document).ready(function(){
// do your work here
});
EDIT :
Try this:
$("#submit").live("click", function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
});
First, try to determine that the form is submitting correctly. try submitting to
url: '/submit.php'
instead, as that may not have been the correct path.
Second, try sending the value unserialized and see if you get a correct.