I'm trying to detect which was button was pressed with jQuery and then server-side do different things depending on the outcome.
The jQuery works fine (although I may have gone about it in a long- handed way) but I can't figure out why in my code whichever button I press I get the same response from php: "Add button detected". I hope someone can tell me what I've got wrong?
The jQuery
$(document).ready(function() {
$(".btn_add").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function() { //If remove btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
The Php
<?php
$btn=$_POST["btn"]; //Other posted variables removed for simplicity
if($btn="btn_add"){
echo "<h1>Add button detected</h1>";
//Do stuff
}
elseif($btn="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
The html Form
<td>
<form id=\ "myForm\" class=\ "myForm\" action=\ "\" method=\ "post\" enctype=\ "multipart/form-data\">
<input type=\ "hidden\" name=\ "user_id\" value=". $collab_userid." />
<input type=\ "hidden\" name=\ "id\" value=".$upload_id." />
<button type=\ "submit\" id=\ "btn_remove\" class=\ "btn_remove\" name=\ "btn_remove\">Remove</button>
<button type=\ "submit\" id=\ "btn_add\" class=\ "btn_add\" name=\ "btn_add\">Approve</button>
</form>
</td>
You should add the pressed button to your formdata, otherwise the click couldn't be detected.
$(document).ready(function() {
$(".btn_add").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_add"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function() { //If remove btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_remove"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
Change php code as follows
<?php
$btn=$_POST["btn"]; //Other posted variables removed for simplicity
if ($btn=="btn_add") {
echo "<h1>Add button detected</h1>";
//Do stuff
} elseif ($btn=="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
You need not have two separate function for jquery button handling. Also you can remove the button type="submit" from your code since you are detecting the click event
$(document).ready(function() {
$("button").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
console.log(url);
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
<form id="myForm" class="myForm" action="\" method= "post" enctype="multipart/form-data">
<input type="hidden" name="user_id" value=". $collab_userid." />
<input type="hidden" name="id" value=".$upload_id." />
<button type="submit" id="btn_remove" class="btn_remove" name= "btn_remove">Remove</button>
<button id="btn_add" class= "btn_add" name="btn_add">Approve</button>
</form>
</td>
You can use the parse_url() and parse_str() for getting the query string in php. In order to use $btn=$_POST["btn"]; tbn attribute must be passed as a form data, query parameters wont will be available through this method
<?php
$parts = parse_url($url);
parse_str($parts['query'], $query);
$btn = $query['btn'];
if($btn=="btn_add"){
echo "<h1>Add button detected</h1>";
//Do stuff
}
elseif($btn=="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
Your code works just make var url = process_ajax4.php that will fix your problem.in PHP use == instead of =, also add e.preventDefault() to your button clicks to prevent the form from being submitted with action='url'
$(document).ready(function() {
$(".btn_add").on("click", function(e) { //If add btn pressed
e.preventDefault();
var id = this.id;
var url = "process_ajax4.php";
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_add"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function(e) { //If remove btn pressed
e.preventDefault();
var id = this.id;
var url = "process_ajax4.php";
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_remove"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
i think your code looks ok.
i think in php you cannot compare string by =
you may need to change it to strcmp(strA,strB)==0 in order to ensure the input parameter is add button or remove button.
You don't actually need the jQuery code at all. Since both btn_remove and btn_add are submit buttons, you can check which of the buttons where used to submit the form by using:
if(isset($_POST["btn_remove"])) {
//Remove button was pressed.
}
Related
I must submit a form and I need to include the value of the submit button that was clicked. How can I do that? This is my code:
<form id="form_update" >
<input type="text" class="form-control" name="title" value="" >
<input type="hidden" name="prova" value="prova" />
<button type="submit" name="salva" value="delete" class="btn btn-success">delete</button>
<button type="submit" name="salva" value="modify" class="btn btn-success">modify</button>
<button type="submit" name="salva" value="save" class="btn btn-success">save</button>
</form>
$(document).on('submit', '#form_update', function() {
return callAjax($(this).serialize());
});
function callAjax(data) {
$.ajax({
type: 'POST',
url: 'call/function.php',
data: data,
success: function(data) {
// code
},
error: function(data) {
alert('error');
}
});
return false;
};
I would change the event type to a click on the button and the access their values with $(this).val()
$(document).on('click', 'button', function(e) {
e.preventDefault(); // Prevent from submitting form.
var buttonValue = $(this).val();
return callAjax($('#form_update').serialize());
});
Use the below function.
$(document).on('submit', '#form_update', function() {
var val = $("input[type=submit][clicked=true]").val();
return callAjax($(this).serialize()+'&clickedVal='+val );
});
It will pass the clicked button value with the ajax request.
Thanks...
With Arun solution I get undefined val value...
With Daan solution the problem was the same...
But with your response I have resolved with a mix :)
$(document).on('click', 'button', function(e) {
e.preventDefault(); // Prevent from submitting form.
var buttonValue = $(this).val();
return callAjax($('#form_update').serialize()+'&salva='+buttonValue );
});
Thanks a lot ;)
the problem is that i am unable to insert data in my database without reloading
i have tested it without the note_sql.js and my note_sql.php works fine but there seems to be a problem in my js file if some body could point me in the right direction it would be wonderful
Index.php
<form id="noteform" action="note_sql.php" method="POST">
<input type="text" name="note"></input>
<input id="sub" type="submit" value="Save Note" />
</form>
<span id="result_note"><span>
<script type ="text/javascript" src="jquery/note_sql.js"></script>
note_sql.js
$("#sub").click(function(){
var data = $("#noteform: input").serializeArray();
$.post($("#noteform").attr("action"),data,function(info){$("result_note").html(info); });
clearInput();
});
$("#noteform").submit(function(){
return false;
});
function clearInput(){
$("#noteform :input").each(function(){
$(this).val('');
});
}
Use Jquery Ajax the working code is given below :
please add ID to Note Form Element :
<pre>
<script>
$(document).ready(function () {
$("#sub").click(function () {
var name = $("#note").val();
var message = $("#message").val();
$.ajax({
type: "post",
url: "note_sql.php",
data: "name=" + name,
success: function (data) {
alert(data);
}
});
});
});
</script>
</pre>
I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>
The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/
I have a form with a textarea and a button. To show the textarea value in another tab of the same window on a button click I used this:
<input type="button" name="preview" id="inline_submit_a" value="PREVIEW" />
<script>
$('#inline_submit_a').click(function(evt) {
var msg = document.getElementById('message').value;
var myLineBreak = msg.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '<br />');
jQuery.ajax({
type: 'POST',
url: '/someajax.php',
data: "msg="+myLineBreak,
success: function(data) {
window.open("<?=SITEURL?>includes/templates/preview/template1/postoffer_preview.php?offer="+data,'_blank');
return false;
}
});
});
</script>
I'm sending through query string,
How to send the value to another page through POST and not the query string(GET) since it takes only upto limited characters.
Also, How to get the html content (With breaks),
I used this: var myLineBreak = msg.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '<br />');
But breaks for some text.
Also, window.open("<?=SITEURL?>test.php?msg="+data,'_blank'); this works good in firefox, but in Chrome, it opens a new window,
Can someone pls help me on this.. am I going in the right direction?
Thanks
Something like this, using form.target and empty window.open (code not tested) :
<form name="myform" action="postoffer_preview.php" target="myNewWin" method=post">
<input type="button" name="preview" id="inline_submit_a" value="PREVIEW" />
</form>
<script>
var open_post_window = function ()
{
window.open("","myNewWin","width=500,height=300,toolbar=0");
document.myform.submit();
}
$('#inline_submit_a').click(function(evt) {
var msg = document.getElementById('message').value;
var myLineBreak = msg.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '<br />');
jQuery.ajax({
type: 'POST',
url: '/someajax.php',
data: "msg="+myLineBreak,
success: function(data) {
open_post_window();
return false;
}
});
});
</script>
Add a little setTimeout on document.myform.submit() may be necessary.