I need some help getting the value of a submit button. The code below fires off my controller function, but I am unable to get the value of the 'Invite' button. var_dump states 'bool(false)' and a 0 for Educator_Id is inserted into my final query to the database.
Thanks for any help you can give!
My submit button:
<?php foreach($educators as $educator): ?>
<button type="submit" id="Invite" name="Invite" value="<?php echo $educator->Educator_Id; ?>">Invite</button>
<?php endforeach; ?>
My jQuery function:
$("#Invite").click(function() {
var form_data = $('#validation-form').serialize();
$.ajax({
url: "<?php echo site_url('schedule/send_invite'); ?>",
type: 'POST',
data: form_data
});
return false;
})
My controller:
function send_invite() {
$email = $this->input->post('Educator_Email');
$Opportunity_Id = $this->input->post('Opportunity_Id');
$Educator_Id = $this->input->post('Invite');
$Class_Numbers = $this->input->post('Class_Numbers');
foreach($Class_Numbers as $Class_Number):
$this->ion_auth_model->update_class_educator($Opportunity_Id, $Class_Number, $Educator_Id);
endforeach;
}
My model:
function update_class_educator($Opportunity_Id, $Educator_Class, $Educator_Id) {
$Class = array(
'Educator_Id' => $Educator_Id
);
$this->db->where('Opportunity_Id', $Opportunity_Id);
$this->db->where('Class_Number', $Educator_Class);
$this->db->update('Classes', $Class);
}
Try to passing the value to a hidden input
JavaScript:
$("#Invite").live("click", function(){
var this_value = $(this).val();
$("input[name='InviteValue']").val(this_value);
});
Try this for the PHP:
<?php
foreach($educators as $educator){
echo "<input type='checkbox' name='invite[]' value='".$educator->Educator_Id."'>".$educator."<br/>";
}
echo "<input type='submit' value="Invite"/>";
It will render a checkbox for each educator and a SINGLE submit button. Then, in your JS:
$("#invite").click(function() {
var form_data = $('#validation-form').serialize();
$.ajax({
url: "<?php echo site_url('schedule/send_invite'); ?>",
type: 'POST',
data: form_data,
success: function(){
// Do something here if succeded
}
});
return false;
});
This way it only sends checked checkboxes to the server, so you can handle who is selected in your controller from there.
$Educator_Id = $this->input->post("invite[]");
instead of
$Educator_Id = $this->input->post('Invite');
I think that should work... Your final goal is a little unclear to me, but your logic is what's off in this case, and this should help clear things up.
Cheers!
Instead of using button use input like this :
<?php
$count = 0;
foreach($educators as $educator): ?>
<input type="submit" id="Invite_$count" class="invite" name="Invite" data-value="<?php echo $educator->Educator_Id; ?>" value="Invite"/>
<?php
$count++;
endforeach; ?>
And in jquery you can use :
$(".invite").click(function() {
var submit_data = $(this).data('value');
var form_data = $('#validation-form').serialize();
$.ajax({
url: "<?php echo site_url('schedule/send_invite'); ?>",
type: 'POST',
data: form_data + "&submit_data=" + submit_data
});
return false;
})
In Controller:
function send_invite() {
$email = $this->input->post('Educator_Email');
$Opportunity_Id = $this->input->post('Opportunity_Id');
$Educator_Id = $this->input->post('submit_data');
$Class_Numbers = $this->input->post('Class_Numbers');
foreach($Class_Numbers as $Class_Number):
$this->ion_auth_model->update_class_educator($Opportunity_Id, $Class_Number, $Educator_Id);
endforeach;
}
Try it. This might solve your problem.
Related
I have a problem with transmitting php data in ajax function.
What I want is to send a html form, in which i have php value from a mysqli_fetch_array. The value is the number of the post, which is my primary key.
Being new to javascript, I don't really know how to do this.
Here is my onclick function code :
<script>
function foo () {
$.ajax({
url:"vote.php?no_post=<?php $post ['no_post'] ?>", //what I'd like to do
type: "POST", //request type
success:function(result)
{
alert(result);
}
});
}
</script>
In the php page, I have this fetch array, here we focus on button named "up" :
if(!isset($_POST['more']))
{
while($post = mysqli_fetch_array($res))
{
echo
'<p>'.
'<center>'.
'<img src="image/'.$post['image_post'].'">'.
'</center>'.
'<br/>'.
'<label>'.$post['desc_post'].'</label>'.
'<p>'.
'<a id="darkBlue" href="account.php?no_post='.$post['no_post'].'">'.'#'.$post['login'].'</a>'.
'<p>'.
'<label>'.$post['time'].'</label>'.
'<p>'.
'<label>'.$post['vote_post'].' points'.'</label>'.
'<footer>';
if (isset($_SESSION['login']))
{
echo '<button class="btn btn-success" name="up" id="up" onclick="foo()">+</button>'.
' '.
'<button class="btn btn-danger" name="down" id="down">-</button>'.
' '.
'Comment'.
'<hr>';
}
EDIT***
And finally my php page where the sql request is executed :
<?php
if (isset($_POST['up'])) // 2 buttons on the first html FORM
{
$req="UPDATE post SET vote_post=vote_post+1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my url
$res=mysqli_query($con,$req);
}
else if (isset($_POST['down']))
{
$req2="UPDATE post SET vote_post=vote_post-1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my URL
$res2=mysqli_query($con,$req2);
}
else
echo 'Error';
?>
Thanks for you help.
You have missed echo in below line.
url:"vote.php?no_post=<?php echo $post['no_post'] ?>", //what I'd like to do
EDIT
As you have used POST method, it should be passed in data like:
$.ajax({
url:"vote.php",
type: "POST", //request type,
data: {
postCount : <?php echo $post['no_post']; ?>
}
success:function(result)
{
alert(result);
}
});
You can try something like that :
<script>
function foo () {
$.ajax({
url:"vote.php",
type: "POST", //request type
data: {no_post: <?php echo '$post['no_post']'?>}
success:function(result)
{
alert(result);
}
});
}
</script>
It's better to use data : [...] instead of using parameters in url
I have written code for button to send a value to php file using ajax as show below :
<script>
$(document).ready(function(){
$(".open-AddBookDialog").click(function(){
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax({
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result1){
var packagetype = package_type;
alert(packagetype);
}
});
});
});
</script>
This is the ajax code for the button which i have written. My button code is :
<a data-toggle="modal" id="custId" data-name="<?php echo $arr["package_name"]; ?>" data-id="<?php echo $arr["id"]; ?>" href="#myModal" class="open-AddBookDialog btn btn-submit" OnClick='change(this);'>Book / Enquiry / Pay</a>
When clicking this button in href, I want to send a id value to a php file using ajax.
data1.php
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
$arr = mysqli_fetch_array($query1);
echo $arr['package_type'];
echo $arr['package_price'];
mysqli_close($con);
?>
using the id value, I want to pick multiple rows of package type and package price from the database having the same id value.After picking the multiple rows of these values i want to send it to the main php file and display all the values of all the rows picked from the database.
Can anyone suggest how to do this ?
<script>
$(document).ready(function()
{
$(".open-AddBookDialog").click(function()
{
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax(
{
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result)
{
resultJson=jQuery.parseJSON(result);
$.each(resultJson.packageDetails, function(i, item) {
var packagetype = item.package_type;
var package_price = item.package_price;
alert("packagetype :- "+packagetype+" ----- package_price :-"+package_price);
});
}
});
});
});
</script>
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
//$arr = mysqli_fetch_array($query1);
while( $strPackageResult=mysqli_fetch_array($query1,MYSQLI_ASSOC) )
{ $ArrPackage[]=$strPackageResult; }
if( isset($strPackageResult) ){ unset($strPackageResult); }
mysqli_free_result($query1);
if( isset($query1) ){ unset($query1); }
$myResultPackageArray=array();
if( isset($ArrPackage) && is_array($ArrPackage) && count($ArrPackage)>0 ) {
$tempArray=array();
foreach( $ArrPackage as $tempPackage )
{
$tempArray['package_type']=$tempPackage['$tempPackage'];
$tempArray['package_price']=$tempPackage['package_price'];
$myResultPackageArray['packageDetails'][] =$tempArray;
}
}
mysqli_close($con);
echo json_encode($myResultPackageArray);
?>
There are some basic things you should know first then you can easily rectify your errors.
Debuging javascript
Prepared Statements
PHP Error Handling
This is not you have asked but as a programmer i will suggest you to go through it.
As going through your code
var packagetype = package_type;
package_type is undefined. If you are using chrome inspect element and check the console you will see the error.
Hope this will work.
I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I've header file in which I have search box where user can search for products, this works on ajax request & for getting the info I've livesearch.php file.
Now with the searched products, I want to add 'Add to Cart' button directly. So in fact for every search result there will be one button to add that product in cart. To achieve this, I need to add another ajax request for adding that product into cart.
But nothing's happening while I click on add button. Here's my code.
Header.php
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function()
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function()
{
$(document).live('click', '.buynow', function()
{
var productid = $(this).attr('id');
var quantity = $('.quantity_'+productid).val();
var type= $('.type_'+productid).val();
$.ajax
({
type: "POST",
url: "db_addtocart.php",
data: {'quantity'=quantity, 'type'=type, 'productid'=productid},
success: function(option)
{
this.attr('value','Added');
}
});
return false;
});
});
</script>
<?php
<input type="text" id="text" class="searchproductbrand">
?>
livesearch.php
<?php
while(blah blah){
echo "<input type='text' id='quantity' class='quantity_".$row["productid"]."'>".
" <select name='type' class='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>";
"</select>";
echo " <input type='button' class='button' id='".$row["productid"]."'
class='buynow' value='Buy Now'>";
}
?>
db_addtocart.php
This file gets the values of variables & insert into table, nothing sort of important.
What wrong am I doing? Any help will be appreciated.
Try updating your js to the code below. I used .delegate() instead of .live() as according to the manual it is better to use with jQuery 1.4.3+.
$(document).ready(function() {
$(".searchproductbrand").keyup(function(){
var kw = $(".searchproductbrand").val();
if(kw != ''){
$.ajax({
type: "POST",
url: "livesearch.php",
data: {kw:kw},
success: function(option){
$("#livesearch").show();
$("#livesearch").html(option);
$("#livesearch").css("border","1px solid #A5ACB2"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
});
}
else {
$("#livesearch").html("").css("border","0px"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
return false;
});
$(document).delegate('.buynow','click', function(){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val(); // changed from .quantity_ to #quantity - requires change in php code
var type= $('#type_'+productid).val(); // changed from .type_ to #type - requires change in php code
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this, // added as 'this' below was out of scope. see the docs for more info
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added'; // changed from this.attr('value','Added');
}
});
return false;
});
});
This will also require you to update the html created in livesearch.php to the following code. Mainly changing from class=... to id=...
<?php
while(blah blah){
echo "<input type='text' id='quantity_".$row["productid"]."' />";
echo " <select name='type' id='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>".
"</select>";
echo " <input type='button' class='button buynow' id='".$row["productid"]."' value='Buy Now'>";
}
?>
Here is a working JSFiddle example - http://jsfiddle.net/X8n3d/
What's going on is that your $(".buynow").click is bound to the element which are in the dom on load of your page. Any button with .buynow added after that has no event.
You need to use jQuery's on() method so the click event works for all elements.
Juste replace $('.buynow').click(function(e){..}) with $(document).on('click', '.buynow', function(e){..}) and it should work.
In CI, I have setup a controller with a method of logsig(). Then in my index() method I'm calling a view called startpage. In my view I'm using JSON to make an asynchronous call between my view and my controller. How would I code the call. Below is the code I have:
Contoller:
function logsig() {
$this->load->view('startpage', $sync);
header('Content-type:application/json'); .............
View:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// blink script
$('#notice').blink();
$("#action_button").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "processing/logsig.php",
data: dataString,
json: {session_state: true},
success: function(data){
if(data.session_state == true) { // true means user is logged in.
$("#main1").hide();
$('#main1').load('<?=$sync?>').fadeIn();
} else if(data.session_state == false) { // false means user is being registered.
$("#action_button").remove();
$('#success').load('<?=$sync?>');
// onLoad fadeIn
}
}
});
}
});
});
</script>
You can't have your controller load a view and return JSON at the same time. Break out the JSON portion to a separate function.
An oversimplified example could look like this:
// Your existing function, but only displaying the view
function logsig() {
$this->load->view('startpage', $sync);
}
// A new function whose sole purpose is to return JSON
// Also notice we're using CI's Output class, a handy way to return JSON.
// More info here: codeigniter.com/user_guide/libraries/output.html
function get_json() {
$this->output->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
}
Then, in your JavaScript, call get_json:
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url('processing/get_json.php'); ?>",
// ... truncated for brevity ...
});
If I read your question correctly, your JS postback code isn't working:
url: "processing/logsig.php",
Your CI url should be something like:
url: <?php echo site_url("processing/logsig"); ?>,
The site_url() function requires the URL helper. Load that in the beginning of your loadsig() function:
$this->load->helper('url');
Try This
Controller ---------
public function AjaxTest() {
$rollNumber = $this->input->post('rollNumber');
$query = $this->welcome_model->get_students_informationByRoll($rollNumber);
$array = array($query);
header('Content-Type: application/json', true);
echo json_encode($array);
}
View-----
<?php echo validation_errors(); ?>
<?php echo form_open('welcome/SearchStudents'); ?>
<input type="text" id="txtSearchRoll" name="roll" value="" />
<input type="submit" name="btnSubmit" value="Search Students" onclick="return CheckAjaxCall();"/>
<?php echo '</form>'; ?>
Scripts ----------
function CheckAjaxCall()
{
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>welcome/AjaxTest',
dataType:'json',
data:{rollNumber: $('#txtSearchRoll').val()},
cache:false,
success:function(aData){
//var a = aData[0];
//alert(a[0].roll);
$.map(aData, function (item) {
var stData = "<td>"+ item[0].roll +"</td>" +
" <td>"+item[0].Name+"</td>" +
"<td>"+item[0].Phone+"</td>" +
"<td> Edit </td>"+
"<td> Delete </td>";
$('#tblStudent').text("");
$('#tblStudent').append(stData);
//alert (item[0].roll + " " + item[0].Name);
});
//alert(aData);
},
error:function(){alert("Connection Is Not Available");}
});
return false;
}