Call PHP function with button onClick with parameter/ AJAX? - php

Hello I want to call my function download when the user click on the button, basically:
<input type='button' name='Release' onclick="document.write('<?php downloadFichier($tab1, $t2) ?>');" value='Click to Release'>
Of course doesn't work, so I try to do with a AJAX, I don't know this language, but it is possible to do what I want: call my PHP function with 2 parameters?
<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'file_product.php',
success: function(data) {
$("p").text(data);
}
});
});
});
</script>
Thank you for helping me.

You should call a js-function with onclick event like this:
<input type='button' name='Release' onclick="downloadFichier(param1, param2)" value='Click to Release'>
And your AJAX-function should be like this:
function downloadFichier(param1, param2){
$.ajax({
type: 'POST',
url: 'file_product.php',
data: "param1=" + param1 + "&param2=" + param2,
success: function(data) {
$("p").text(data);
}
});
You can get your params in PHP-script from the $_REQUEST array by their names (param1, param2).

#PaulBasenko inspired this alternative, where you set the parameters through some <input type="hidden" /> :
HTML
<form action="#" method="POST" id="form1">
<input type="hidden" name="tab1" value="<?= $tab1 ?>" />
<input type="hidden" name="t2" value="<?= $t2 ?>" />
<button type="submit">Click to Release</button>
</form>
Javascript
$(function() { // equivalent of "$(document).ready(function(){"
$('body').on('submit', '#form1', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type : 'POST',
url : 'file_product.php',
data : formData,
success : function(data) {
$('#p').text(data);
}
});
});
});
PhP
<?php
$tab1 = (isset($_POST['tab1'])) ? $_POST['tab1'] : null;
$t2 = (isset($_POST['t2'])) ? $_POST['t2'] : null;
// process & return json_encoded data
?>
How it works ?
When clicking on the button, which is a type="submit", it will trigger the submit event for its parent form. Then, jQuery listen to this event and immediately blocks it using èvent.preventDefault() in order to call Ajax instead of a regular synchronous call to a php file.

Related

how can i insert two different form using one controller method by one trigger in codeigniter?

I have try but, i want to do it with ajax on click one button, want to send two form value to table using one method bu controller in codeigniter.
Suppose these are your forms
<form name="frm1" id="frm1">
<input type="text" name="txt1" >
<input type="text" name="txt2">
</form>
<form name="frm2" id="frm2">
<input type="text" name="txt3" >
<input type="text" name="txt4">
</form>
<button type="button" id="btn">Submit</button>
Ajax Script
<script type="text/javascript">
var BASE_URL = "<?php echo base_url(); ?>";
$( document ).ready(function() {
$( "#btn" ).click(function() {
$.ajax({
type: 'POST',
url:BASE_URL + "Controller/save",
data: $('#frm1, #frm2').serialize(),
success: function (data) {
data = JSON.parse(data);
console.log(data);
}
});
});
});
</script>
By this in the save method you can get the values of the forms in controller
function save()
{
echo $this->input->post('txt1');
echo $this->input->post('txt2');
echo $this->input->post('txt3');
echo $this->input->post('txt4');
}

how to checkbox value stored array when click checkbox using ajax

HTML
<input type="checkbox" name=options[cid]" value='1'
onChange="chkdeptCount(this.value)" class="test">
<input type="checkbox" name=options[cid]" value='2'
onChange="chkdeptCount(this.value)" class="test">
jquery:
function chkdeptCount(val){
$.ajax({ url: '../ajax/AjaxCall.php',
data: {Action:'IMPLODEARRAY',arrVal: val},
type: 'post',
success: function(output) {
alert(output);
$('.result').html(output);
}
});
}
PHP:
if($_POST['Action']=='IMPLODEARRAY'){
$arr_val[] = $_POST['arrVal'];
print_r($arr_val);
}
When I run this code does not return array value. It returns a single value WHY?
Note that, you are missing the quote here name=options[cid]".
And you are using onChange="chkdeptCount(this.value)" event with current value this, this will only return one value at once.
This is very basic Example:
HTML:
<form method="post" id="formID" action="">
<input type="hidden" name="Action" value="IMPLODEARRAY">
<input type="checkbox" name="options[cid]" value='1' class="test">
<input type="checkbox" name="options[cid]" value='2' class="test">
<input type="submit" name="submit" value="Submit" id="SubmitButton">
</form>
AJAX:
<script type="text/javascript">
$(document).ready(function(){
$("#SubmitButton").click(function(){ // when submit button press
var data = $("#formID").serialize(); // get all form input in serialize()
$.ajax({
url: YourURL, // add your url here
type: "POST", // your method
data: data, // your form data
dataType: "json", // you can use json/html type
success: function(response) {
console.log(response); // your response
},
beforeSend: function()
{
// if you want to display any loading message
}
}); // JQUERY Native Ajax End
return false;
});
});
</script>
PHP:
<?php
if(count($_POST) > 0){ // if you have some value in AJAX request
if($_POST['Action'] == 'IMPLODEARRAY'){ // your condition
print_r($_POST['options']); // get all checkbox value.
}
}
?>
Few more example will help you to understand, you can you use: Submitting HTML form using Jquery AJAX |
jQuery AJAX submit form

Sending Multiple data to PHP page without reloading page

Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});

Wordpress Ajax Form with two submit buttons

I am working in wordpress and I have one form and two submit buttons. I am using ajax and it is wordpress.
When first submit button is pressed I want statement 1 to be echoed and when submit button number 2 is pressed I want state 2 be echoed. I have followed the code tutorials but when I press submit from the control returns empty or no result and in inspect there is no error in the browser. Below is my code.
HTML Form
<form id="voteform" action="" method="post">
<input name='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
<input name='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
</form>
I am not copying the enqueue code but just the actual php function that executes
function articlevote ()
{
if ($_POST['vote'] == 'one') {
echo json_encode("1 vote button is pressed");
die();
}
else if ($_POST['vote'] == 'two') {
echo json_encode("2 vote button is pressed");
die();
}
}
Ajax and jquery
jQuery(function ($) {
$(document).on("click","input[name=vote]", function() {
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});
Again kindly note that I am using wordpress so kindly guide me in this thanks
This should get you what you need:
Html:
<form id="voteform" action="" method="post">
<input type="text" name="field1" value="field one value"/>
<input type="text" name="field2" value="field two value"/>
<input class='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
<input class='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
</form>
jQuery
jQuery(function($) {
var yes = {ajaxurl:"mypage.php"}; // created for demo
$('.vote').click(function(e) {
e.preventDefault(); // stop the normal submit
var _data = $('#voteform').serialize()+'&vote=' + $(this).val();
//alert(_data)
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data: _data,
success: function(html) {
$("#myresult").html(html); // you had `res` here
}
});
});
});
$(document).ready(function(){
$('input[value=\'one\'], input[value=\'two\']').on('click', function(){
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});

onclick form send via ajax no page refresh

I've been racking my brains for days looking at examples and trying out different things to try and get my form to submit with Ajax without a page refresh. And Its not even sending the data now.. I don't know what I'm doing wrong..Can someone run through my ajax and form please.
Toid is the users id and newmsg is the text in which the user submits. The two values get sent to the insert.php page.
I would really appreate the help. I'm new to Ajax, and I look at some of it and don't have a clue. If I finally got it working, It may help me realize what I've done wrong. I am looking up tutorials and watching videos..but it can be very time consuming for something that would be simple to someone in the know on here. It maybe that I've got the wrong idea on the ajax and it makes no sense at all, sorry about that.
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
homestatus()
event.preventDefault();
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
});
return false;
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
</div>
</form>
INSERT.PHP
$user1_id=$_SESSION['id'];
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&isset($_POST['toid'])){
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
}else{
rawfeeds_user_core::create_streamitem("3",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
Try using firebug to identify bugs in your code. It's a really good companion for developing javascript. Nearly all of your bugs led to error messages in the firebug console.
You had several errors in your code, here is the corrected version:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){alert('success');}
});
});
});
And here the corrected html:
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
Actually onsubmit event has to be used with form so instead of
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
it could be
<form id="myform" method="POST" class="form_statusinput" onsubmit="homestatus();">
and return the true or false from the function/handler, i.e.
function homestatus()
{
//...
if(condition==true) return true;
else return false;
}
Since you are using jQuery it's better to use as follows
$("form#myform").on('submit', function(event){
event.preventDefault();
var toid = $("#toid").val(); // get value
var content = $("#newmsg").val(); // get value
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + toid + "&newmsg=" + content,
success: function(data){
// do something with data
}
});
});
In this case your form should be as follows
<form id="myform" method="POST" class="form_statusinput">
...
</form>
and input fields should have a valid type and value attribute, Html form and Input.
I think you should read more about jQuery.
Reference : jQuery val and jQuery Ajax.
change the form to this
<form id="myform" ... onsubmit="homestatus(); return false">
you don't need the onsubmit attribute on the submit button, but on the form element instead
homestatus might be out of scope
function homestatus () {
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
}
This isn't tested, but try this (I annotated some stuff using comments)
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
// not sure what this does, so let's take it out of the equation for now, it may be causing errors
//homestatus()
// needed to declare event as a param to the callback function
event.preventDefault();
// I think you want the value of these fields
var toid = $("#toid").val();
var content = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+toid +"&newmsg="+ content,
success: function(){
}
});
return false;
});
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" / >
</div>
</form>
It's a lot easier to let .serialize() do the work of serializing the form data.
The submit handler also needs event as a formal parameter, otherwise an error will be thrown (event will be undefined).
With a few other changes, here is the whole thing:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
homestatus();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: formData,
success: function(data) {
//...
}
});
});
});
</script>
<form id="myform" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" >
</div>
</form>
Unless you are omitting some of your code, the problem is this line:
homestatus()
You never defined this function, so the submit throws an error.
You may want to take a look at jQuery (www.jquery.com) or another js framework.
Such frameworks do most of the stuff you normally have to do by hand.
There are also a bunch of nice helper functions for sending form data or modifying html elements

Categories