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
Related
I am trying to conctenate/embed database value from php script into my api URL
but i don't know how to get it right, I am not familiar with php
it needs to embed the varible from DB in order to access API values like this
api/rfq/1 (example)
I tried this so far
php code:
<?php
require_once('connection.php');
session_start();
if(!$con){
die('Please Check Your Connection'.mysqli_error());
}else{
$query="select BusinessID from business where username='".$_SESSION['User']."'";
$result=mysqli_query($con,$query);
while($row =mysqli_fetch_array($result)){
$results[]=implode($row['BusinessID']);
}
echo json_encode($results);
// echo 'Works ASF '+$hey;
}
?>
jQuery file:
$(function() {
$.getJSON('getID.php', function(data) {
$.each(data, function() {
alert(data.column);
})
})
var $hello = $('#hello');
$.ajax({
type: 'GET',
dataType: "json",
url: 'http://slimapp/api/rfq/"'+$_SESSION['User']+'"',
success: function(hello){
$.each(hello, function(i,order){
$hello.append('<div class="panel panel-default"><div class="panel-thumbnail"></div><div class="panel-body"><p class="lead"><b><img src="assets/img/Profile.png" height="28px" width="28px">'+order.Title+'<i class="glyphicon glyphicon-plus"></i>Make Bid</b></p><p><img src="assets/img/RFQ.png" height="28px" width="28px">'+order.Description+'</p><p><img src="assets/img/Clock.png" height="28px" width="28px">'+order.Date+'</p><hr/><p><img src="assets/img/email.png" height="28px" width="28px">'+order.email+'</p><p><img src="assets/img/Phone.png" height="28px" width="28px">'+order.cellphone+'<p><textarea class="form-control" placeholder="Comment"></textarea><br/><li id="btn1"></li><button class="btn btn-success pull-left" type="button" style="border-radius:12px">Comment</button></p></div></div>');
})
}
})
});
I expect to get data from url like this http://slimapp/api/rfq/1
You Jquery file should look like this:
function apiCall(user) {
var url = 'http://slimapp/api/rfq/'+ user +''; // This var is creating the right URL, using the parameter USER of the function
$.ajax({
type: 'GET',
dataType: "json",
url: url, // Calling the new right URL
success: function(hello){
// Handle your success
}
})
};
Here you are creating a new function, that receives the parameter User that you wanna pass in the URL.
Your PHP file should look like this:
<?php
$results = '1';
?>
<script>
apiCall(<?php echo $results ?>); // Passing the value 1 as a parameter for the function
</script>
Here you are calling the function apiCall and passing the value of the variable $results as parameter.
I am new to Ajax and I am trying CRUD operations using the same. I have an index.php page where I can insert and display data, also I have links to update and delete data over there.Create, Read, Update are working fine. Now the problem is that when I click the link to Delete, I am successfully sending the id to the delete_back.php and the value is getting deleted but the success message which should be printed on the index.php as I have a div named #delete_msg over there but somehow the success message is being printed on delete_back.php.
index.php
<div id="delete_msg"></div>
select_back.php
<?php
include("config.php");
$data=mysqli_query($con,"select * from student");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a href='update_front.php?id=$row[0]&nm=$row[1]&add=$row[2]&cont=$row[3]'> Update </a></td>";
echo "<td><a class='delete' href='delete_back.php?id=$row[0]'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
?>
delete_back.php
<?php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data=="true")
{
echo "Data Deleted";
}
else
{
echo "Delete Error";
}
?>
ajax file
$(".delete").click(function(event){
event.preventDefault();
$.ajax({
url:"delete_back.php",
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})
add data-id attribute to anchor tag:
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can do in your ajax be like:
$("#delete").click(function(event){
var obj = $(this); // first store $(this) in obj
var id = $(this).data('id'); // get id of data using this
$.ajax({
url:"delete_back.php",
dataType:"html",
data: { id: id },
type: "Post",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})
in your php file:
$id=$_POST['id'];
First of all, I really hope you don't have a loop which prints multiple anchors with same ID...
That said, according to your html, your JS should be like the followin, otherwise you will lose your id value:
$("#delete").click(function(event){
event.preventDefault();
var my_href = $(this).attr('href');
$.ajax({
url: my_href,
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
return false;
});
But this isn't a really nice coding style.. I would suggest to use html5 data- attribute to store your id value
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can also use javascript:; instead of # if you don't want your url to change..
And your JS should be like:
$("#delete").click(function(event){
// you can avoid preventing default behaviour because your anchor doesn't have any href value
var del_id= $(this).data('id');
$.ajax({
url: "delete_back.php",
dataType:"html",
data: {id: del_id} // use object for better reading
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
});
I also suggest you to check .done() construct LINK and deferred.done()
I believe that the delete link is coming from a loop containing other delete links too. If so, this is what you should do.
echo '<td><a class="lnk-delete" href="#" data-id="'.$row[0].'">Delete</a></td>'; //The delete links should have 1 class name
Then make your ajax call
$('.lnk-delete').click(function(e){
var id = $(this).data('id');
ajax({
url: 'delete_back.php'
data: {id: id},
type: 'POST',
success: function(data){
$('#delete_msg').html(data);
}
});
});
Get the id of the item you want to delete in php
$id = $_POST['id'];
<?php
//select_back.php
echo "<td><a id='delete' href='#'>Delete</a></td>";
?>
<input type="hidden" id="hidden_id" name="id" value="<?php echo $row[0]; ?>">
<script>
$("#delete").click(function(event){
event.preventDefault();
var hidden_id =$("#hidden_id").val();
$.ajax({
type:'GET',
url:"delete_back.php",
data:"id="+hidden_id,
success:function(data){
if(data.trim() == 'success')
{
$("#delete_msg").html("<div style='color:green;'>deleted successfully</div>");
}else{
//error
}
}
});
});
</script>
<?php
// delete_back.php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "Delete Error";
}
?>
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.
I am trying to write an ajax function such that when i click the submit button, name = "Add", it will call for a php file named "addtobucketlist.php" and run the functions in it.
This is the ajax function in my file called "script.js" which is not working, and I have no idea why.
(I have verified that the hideshow('loading',1); at line 2 is working.)
function Addtobucketlist(){
hideshow('loading',1); //line 2
error(0);
$.ajax({
type: "POST",
url: "http://utourpia.me/php/addtobucketlist.php",
data: $('#addBucket').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
}
});
}
Below is my header.php
$(document).ready(function(){
$('#addBucket').submit(function(e) {
Addtobucketlist();
e.preventDefault();
});
});
Below is my form, this is being written such that when ajax is run, the form will be hidden and div class done will be shown.
echo '<div class=form>';
echo '<form id=addBucket action="http://utourpia.me/php/addtobucketlist.php" method=post>';
echo '<input type="submit" name="add" value="Add" /><img id=loading src="../../images/loading.gif" alt="working.." />';
echo '</form>';
echo '</div>';
echo '<div class="done"><p>Added successfully! <br /></p>';
echo '</div>';
below is addtobucketlist.php:
if (isset($_POST['Add']))
{
add_to_bucket_list($location_id, $username);
die(msg(1,"<p>Added!</p>"));
}
else
{
var_dump($location_id);
var_dump($username);
}
function msg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
any help would be appreciated!
Try using
if (!empty($_POST['Add']))
{
instead of isset. Add the
error: function( jqXHR, textStatus, errorThrown )
function to your ajax call to see what the error being thrown is.
You use a capital 'A' in your php _POST variable 'Add', and in your html form it is a lowercase a.
The text you're outputting from your php script might not be identified as proper json. Use the php function json_encode() on an array of output values instead.
action is not required as you are doing it via ajax postremove action="http://utourpia.me/php/addtobucketlist.php remove msg.status checks from $.ajax as it is only going to execute on success
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;
}