Calling PHP file on button click - php

I have two different buttons in my page. clicking on the first one must call a php file named derive_rules.php while cliking on the second one must call another file named derive_rules1.php using ajax. For same i tried following code. But it is not working,
<script>
$(document).ready(function() {
$(".deriver").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules.php',
data: 'kw='+val+'&agent='+agent,
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
if(data.success == 'true') {
$("#results_holder").show();
$("#results").html(data.msg);
$("#keyword").val('');
}
else {
alert(data.msg);
}
}
});
}
});
});
</script>
and those are mu buttons
<td><b>+ New Rule</b></td>
<td><input type = "text" name = "Keyword" id = "keyword" style = "width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type = "button" value = "Verify" class = "Buttons deriver" rel = "<?php echo $_GET['id']; ?>"/></td>
<td><input type = "button" value = "Add" class = "Buttons deriver" rel = "<?php echo $_GET['id']; ?>"/></td>
</tr></table>
what changes should i apply on my code to make it work???? as i want

Here is the quick solution.
HTML
<button class="same" data="derive_rules">Button One</button>
<br/>
<button class="same" data="derive_rules1">Button Two</button>
jQuery
$(".same").click(function(){
var url = $(this).attr("data");
//alert(url);
$.ajax ({
url: url+".php",//pass the url here or you can use whatever I used .php. And do the other stuff etc.
});
});
For more go to my JSFILLDE
If you need my help. Please find me any of social network by searching yeshansachithak.
Here Is Your Code - As You Want - For more explain
<table>
<tr>
<td><b>+ New Rule</b></td>
<td><input type="text" name="Keyword" id="keyword" style="width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type="button" data="your_file_name" value="Verify" class="Buttons deriver" rel="<?php echo $_GET['id']; ?>"/></td>
<td><input type="button" data="your_file_name" value="Add" class="Buttons deriver" rel="<?php echo $_GET['id']; ?>"/></td>
</tr>
</table>
Just pass another attribute in your <button data="your_file_name" ...... Then use your ajax call as like you did. Your button class is driver. Please see below.
<script>
$(document).ready(function() {
$(".deriver").click(function() {
//Edit by Yesh
var url = $(this).attr("data");
//To check
alert(url);
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
//url: 'derive_rules.php', //Edit by Yesh
url: url+'.php',//You can use whatever extension (.html ect..)
data: 'kw='+val+'&agent='+agent,
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
if(data.success == 'true') {
$("#results_holder").show();
$("#results").html(data.msg);
$("#keyword").val('');
}
else {
alert(data.msg);
}
}
});
}
});
});
</script>
Thanks dude.
If you need my help. Please find me any of social network by searching yeshansachithak.

look at classes on button , need to change selector
$(document).ready(function() {
$(".deriver0").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules.php',
data: {kw:val,agent:agent},
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
alert(data);
}
});
}
});
$(".deriver1").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules1.php',
data: {kw:val,agent:agent},
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
alert(data);
}
});
}
});
});
</script>
<td><b>+ New Rule</b></td>
<td><input type = "text" name = "Keyword" id = "keyword" style = "width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type = "button" value = "Verify" class = "Buttons deriver deriver0" rel = "<?php echo $_GET['id']; ?>"/></td>
<td><input type = "button" value = "Add" class = "Buttons deriver deriver1" rel = "<?php echo $_GET['id']; ?>"/></td>
</tr></table>

Related

can i fetch and populate different fields using function(data) jquery?

i want to populate two fields when some one fill up card no.
<input type="text" id="name" name="name" class="form-control" Value="<?php echo $grow['name']; ?>">
<input type="text" id="address" name="address" class="form-control" Value="<?php echo $grow['address']; ?>">
but this code populate field one by one. can any one suggest be better code for populating two fields from database. Thank you
jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k=$(this).val();
var q="name";
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q='+q,
cache: false,
success: function(data)
{
if(data){
$("#name").val(data);
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
$("#address").val(data);
}
}
});
}else
$("#name").val("");
$("#address").val("");
}
});
});
});
</script>
getresult.php
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select * from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
echo $row[$q];
?>
Try to extract both name and address from database and json them
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select address,name from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
$result = array(
'name'=>$row['name'],
'address'=>$row['address']);
echo json_encode($result);
After that parse them via jquery
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
var parsedData = jQuery.parseJSON(data);
$("#name").val(parsedData.name);
$("#address").val(parsedData.address);
}
}
});
Javascript Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k = $(this).val();
var q = "name";
$.ajax({
type: 'POST',
url: "getresult.php",
data: 'k='+k,
cache: false,
success: function(data)
{
var jsonArr = $.parseJSON(data);
if(typeof response =='object')
{
$("#name").val(jsonArr.name);
$("#address").val(jsonArr.address);
}
else
{
$("#name").val("");
$("#address").val("");
}
}
});
});
});
</script>
PHP Code:
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k = $_POST['k'];
$sql = mysql_query("select * from inward where krishi='$k'");
$row = mysql_fetch_assoc($sql);
echo json_encode(array('name' => $row['name'], 'address' => $row['address']);
?>

Pass checkbox values into an array using ajax to php

I am needing some help passing checkbox values into an array using ajax and retrieving the values in my controller. The following code is not working. I receive the error: "Invalid argument supplied for foreach()". Var_dump gives string(42) "Educator_Classes[]=1&Educator_Classes;[]=3
Thanks for any help you can provide.
My html form input:
<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>
My jquery:
$("#Send_Invite").click(function() {
var form_data = {
Opportunity_Id: $('#Opportunity_Id').val(),
Educator_Id: $('#Educator_Id').val(),
Educator_Classes: $('#Educator_Classes:checked').serialize(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('schedule/update_educator_class'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#response').html(data);
}
});
return false;
})
My controller:
function update_educator_class() {
$Educator_Id = $this->input->post('Educator_Id');
$Opportunity_Id = $this->input->post('Opportunity_Id');
$Educator_Classes = $this->input->post('Educator_Classes');
foreach($Educator_Classes as $Educator_Class):
$this->ion_auth_model->update_educator_class($Opportunity_Id, $Educator_Class, $Educator_Id);
endforeach;
}
You have to use [] for name attribute and not for id, otherwise it can't act like an array
<input type="checkbox" id="Educator_Classes" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>
And also your jQuery code can be simpler:
$("#Send_Invite").click(function() {
var form_data = $(this).closest('form).serialize();
form_data['ajax'] = 1;
$.ajax({
url: "<?php echo site_url('schedule/update_educator_class'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#response').html(data);
}
});
return false;
});
To debut what's passed to $Educator_Classes you can do this:
var_export($Educator_Classes);
The Solution is that you have to take the array of name attribute of checkbox.
Like :
<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>

Removing appended div box using jquery ajax

I have to implement two functions, append and delete on set of comments. The insertion and deletion are working properly unless in one case.
When i try to remove newly added comment (before refreshing page), it wont remove. But when i refresh the page that comment removes swiftly.
Here's some code.
Following ajax is appending and removing the comment div.
<script type="text/javascript">
$(function() {
$(".commentbutton").click(function()
{
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='')
{
alert("Please enter your comment");
}
else
{
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$('.delcombutton').click(function()
{
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
</script>
Structure of my div
echo "<div id='post{$postseq}'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form'.$postseq.'" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext'.$postseq.'" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$postseq.'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
PS: Sorry for such a raw code, i have very limited internet now.
You have to use delegation for dynamically added elements:
$(document).on('click','.delcombutton',function(){...});
Use event delegation model with .on() for dynamically added elements
$(function() {
$(document).on('click', '.commentbutton', function() {
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='') {
alert("Please enter your comment");
}
else {
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$(document).on('click', '.delcombutton', function() {
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});

CodeIgniter: jQuery post and load next page

I am successfully able to save the input value using ajax post but it is not loading the next page.
Client Side code:
<script type="text/javascript">
function notifyEmail() {
var form_data = {
'email':$('#inviteEmail').val()
};
alert($('#inviteEmail').val());
$.ajax({
url: "<?php echo site_url('main/email_invites'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
return true;
}
});
}
</script>
<input type='text' id='inviteEmail' placeholder='Enter email'/>
<a href='#' name='email' id='invite-all' onclick='notifyEmail();' class='btn'>Notify Me</a>
Controller Code:
function email_invites()
{
$this->load->model('emailInvites');
if($query = $this->emailInvites->saveEmailInvite())
{
$this->load->view('emailInvites');
}
}
What I do is the following which could help you
<script type="text/javascript">
function notifyEmail() {
var form_data = {
'email':$('#inviteEmail').val()
};
alert($('#inviteEmail').val());
$.ajax({
url: "<?php echo site_url('main/email_invites'); ?>",
type: 'POST',
data: form_data,
dataType:'json',
success: function(msg) {
if(msg.response)
//load the content in the body or wherever you want
jQuery('body').load("<?php echo site_url('main/email_invites/show'); ?>");
else
console.log("Opps, Something wrong happend");
return true;
}
});
}
</script>
<input type='text' id='inviteEmail' placeholder='Enter email'/>
<a href='#' name='email' id='invite-all' onclick='notifyEmail();' class='btn'>Notify Me</a>
In the controller
function email_invites($action = 'process')
{
if($action == 'process')
{
$this->load->model('emailInvites');
$query['response'] = $this->emailInvites->saveEmailInvite();
echo json_encode($query);
}
else
{
$this->load->view('emailInvites');
}
}
You do not need to echo the url, just use it in ajax call like this,
$.ajax({
url: 'main/email_invites',
type: 'POST',
data: form_data,
success: function(msg) {
return true;
}
});
If site_url method returns the required url, then the ajax call needs to be,
$.ajax({
url: "<?php echo site_url('main/email_invites'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
return true;
}
});

Values from javascript to PHP

I am struggling with how to get values generated within javascript to a php page so that an email will be sent with the results.
function sendmemail(){
var data = 'result=' + result.val();
$.ajax({
url: "process.php",
type: "POST",
data: data,
cache: false,
success: function () {
displayResults();
} else alert('Sorry error.');
});
}
That else part is a syntax error, you can't add an else clause in that way.
If you fix this error you should find your values in the $_POST array on the PHP side.
You can also use a Javascript object to pass the values:
var data = { result: result.val() }
which is more readable.
process.php...
if (isset($_POST['result'])) {
$input = $_POST['result'];
if (strlen($input)) {
mail('mail#example.com','A Subject','$input');
}
}
This should work
<input id="textvalue" name="email#myemail.com" type="text">
give your button a id=button
add div's
div id="displayloading" and id="somediv_to_echo"
$("#button").click(function() {
$('#displayloading').fadeIn('slow', function() {
my_value = $("#textvalue").val().replace(/ /g,"+");
$("#somediv_to_echo").load("mail_send.php?d=" + my_value + "&md=" + new Date().getTime());
$("#textvalue").val("");
});
});
Lets do it form the begining.
HTML:
<form id="frm">
<input type="text" name="email" value="sample#sample.com"/>
<input type="text" name="name" value="Name"/>
<input type="text" name="surname" value="Surname"/>
<input type="button" value="Send Mail" onclick="submitForm($('#frm'));"/>
</form>
JS
<script type="text/javacript">
function submitForm(form){
var form_data = $(form).serialize();
$.ajax({
type: "POST",
url: "process.php",
data: form_data,
dataType: 'json',
success: function(data){
if(data.result === 1){
$(form).html("<h2>FORM SEND SUCCESS</h2>");
}else{
$(form).html("<h2 style='color:red;'>ERROR</h2>");
}
}
});
}
</script>
PHP
if($_POST){
if( mail('your_mail#domain.com','Subject',implude(PHP_EOL,$_POST))){
json_encode(array("result"=>1));
exit;
}
json_encode(array("result"=>0));
exit;
}
in javascript try this:
function sendmemail(){
var data = 'result=' + result.val();
var img = document.createElement('img');
img.src='process.php?'+data;
img.style.position='absolue';img.style.width='1px';img.style.height='1px';img.style.top='-10px';
document.body.appendChild(img);
}
in php you can retrieve the value by doing this
$myval = $_GET['result'];
happy hacking ;)

Categories