PHP Function with jQuery AJAX? - javascript

I have a question regarding, PHP functions, jQuery and AJAX.
If I have a button in my php index like this:
<input type="submit" value="Download" id="download"/>
And I have another php file (dubs.php) that contains this:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
?>
And my jQuery, like this:
$(document).ready(function(e) {
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
});
});
});
How do I tell my AJAX request to select for example the second function?
I have no idea on how to do this, I've tried it with "success: first()" or with "success: function(){ first() }" but that did not work.

In your ajax pass some params to identify which function you want to use like this
$("#download").click(function(){
$.ajax({
type : "POST",//If you are using GET use $_GET to retrive the values in php
url : "dubs.php",
data : {'func':'first'},
success: function(res){
//Do something after successfully completing the request if required
},
error:function(){
//If some error occurs catch it here
}
});
});
And in your php file
you can retrive the values in data send via ajax and do the following
if(isset($_POST['func']) && $_POST['func']=='first'){
first();
}
else{
second();
}

This is what I would do:
Your PHP:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
if (isset($_POST["first"])) first();
if (isset($_POST["second"])) second(); //add 'else' if needed
?>
your jQuery:
$.post("dubs.php", {"first":true}, function(result) {
$("#someDivToShowText").text(result);
});
Then, according to the object you send to $.post, the php file will know which function to run.

Try this in your PHP page:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
switch($_POST['func']) {
case "first":
first();
break;
case "second":
second();
break;
default:
// Define your default here }
?>
and this in your JS:
$(document).ready(function(e) {
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'func':'first'}
});
});
The func variable will tell php which function to run!
});

why don't you try to pass with data:{func:f1} and get it on php side and if f1 is there then fire the first function. Although you can send multiple:
jQuery:
$("#download").click(function(e){
e.preventDefault(); // <----stops the page refresh
$.ajax({
type: "GET",
url: "dubs.php",
data:{'func':'f1'}
});
});
PHP:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
if(isset($_GET['func']=='f1'){
first();
}else{
second();
}
?>

JS
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'function':'first'}
});
});
PHP
call_user_func($_GET['function']);
NOTE
Be careful with $_GET parameters, better check first the contents of $_GET

Related

I have to pass data value to controller using ajax

View File product_grid
<div data_id="<?php echo $ro['category_id']; ?>" name="id" class="cbp-filter-item">
<?php echo $ro['category_name']; ?></div>
// try to post data using ajax
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>.index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
Hear i can pass the id to view but not work properly please help me to solved this problem
Controller ::
public function product_grid()
{
$id= $this->input->post('id');
}
You must have to use print or echo otherwise there will be no response sent to client side so use echo like,
public function product_grid(){
$id= $this->input->post('id');
echo 'Data-Id is: '.$id;
}
And use the URL like,
url:"<?=base_url()?>index.php/Home/product_grid", // let there is / in the end of base_url()
AJAX Code,
jQuery.ajax({
url:"<?=base_url()?>index.php/Home/product_grid",
type:'POST',
data: {id:id}, // no need of quotes to JSON Object keys
success:function(data) {
alert(data);
}
});
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>+index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
url:"<?=base_url()?>+index.php/Home/product_grid"
Use + for concatination instead of .

Jquery - GET url value and store in a variable

I would like to GET the value from my url and store it in a variable the to use it in my sql query as a where statement. My admin_id is good, but the $x is not working.
here is what I got.
The URL http://localhost/ict138final/admin/Aviewrecords.php?edit=2
The Query
$id=$_POST['admin_id'];
$x=$_POST['edit'];
$query=mysql_query("DELETE FROM passed_deliverable WHERE deliverable_id={$id} && user_id={$x} ");
function Delete() {
window.location.reload();
lol = $('#wee').text();
var bayotmarkyu = "<?php echo $_GET['edit']; ?>";
$.ajax({
type:'POST',
url:'Adeletedeliverable.php',
data: {admin_id:lol,edit:bayotmarkyu},
success: function(data) {
}
});
}
Try this way to assign admin_id & edit using $_POST because you send AJAX call using POST method.
//on Adeletedeliverable.php file
print_r($_POST); //only for debug before assign
$id=$_POST['admin_id'];
$x=$_POST['edit'];
$query=mysql_query("DELETE FROM passed_deliverable WHERE deliverable_id={$id} && user_id={$x} ");
die(json_encode(array('status'=>'success')));
//On javascript funciton(Aviewrecords.php),so just $_GET['edit'];
function Delete() {
window.location.reload();
lol = $('#wee').text();
var bayotmarkyu = "<?php echo $_GET['edit']; ?>";
$.ajax({
type:'POST', // see your ajax call method carefully
url:'Adeletedeliverable.php',
data: {admin_id:lol,edit:bayotmarkyu},
success: function(data) {
alert(data.status);
}
});
}
Your calling the "x" variable wrong.
Should be $x
and your get should be a post
U have to use $_GET instead of $_POST than.
$x=$_GET['edit'];

Usage of Ajax post

EDIT:
This is what i managed to build...but it still dont work..
$(document).ready(function(){
$("tr").click(function(){
txt=$("input[name=path]").val();
$.ajax({
type: "POST",
url: contract.php, // the same page where i have the table
data: txt, // the variable containing the dynamic id from the clicked row
success: success, // i have no idea what is this parameter for....
dataType: dataType // i have no idea what is this parameter for....
});
});
});
PHP:
$row=mysql_fetch_array($query){
echo '<tr id="'.$row['id'].'">';
echo '<td></td>';
echo '</tr>';
}
What i want,is when the user click on a row , the row id(which is dynamic), must be taken , and returned with ajax post , so i can use it in another query.I have to do this without reloading the page, thats why i try to do it with ajax.
If it's ok to use jQuery i would use something like this to build my table (beside the mysql_*):
<?php
$row=mysql_fetch_array($query){
echo '<tr class="listContractRow" data-path="'.$row['id'].'">';
echo '</tr>';
}
?>
Then catch the click event with a jQuery listener:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).on('click','tr.listContractRow', function(e){
var path = $(this).data('path');
//Use the variable path here in your AJAX call
//Assuming you want a GET request, you can also use $.ajax or $.post here
$.get('YOUR_AJAX_URL_HERE?path='+path, function(){
//Do something after the ajax call
});
});
</script>
EDIT
In your PHP you can do something like:
<?php
if(isset($_GET['path']))
{
//Query here with the variable $_GET['path'];
//Echo the results you want
//Perform an exit here, since it's an AJAX call. You probably don't want to echo the code below (if there is)
exit();
}
?>
jquery ajax get example
$.ajax({
type: "POST",
url: "index.php",
data: "{param: "param"}",
success: function(msg) {
},
error: function(err) {
}
});

Call function inside CodeIgniter's controller using jquery / ajax

Can somebody please explain to me what is the right way to call a php function with jquery / ajax in Codeigniter. Right now, this code isn't working and i cant figure out whay. Note that admin.php controler is inside admin map. Thanks in advance
html code
<form action="#" method="POST" id="change">
<input type="hidden" value="<?php echo $row->id_product; ?>" id="prod" >
<input type="submit" value="switch" >
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
my function inside admin.php controller
public function do_search(){
$id = $this->input->post('id');
return $id;
}
Jquery AJAX script
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'admin321/do_search',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Config / routes.php
$route['admin/do_search'] = "admin_controller/admin/do_search";
I know that this is old post, but maybe someone will find this usefull.
I solve this problem by adding index.php in url. Even if the index.php is hidden using rewrite.
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("index.php/admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Maybe like this:
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
You have to load this helper:
$this->load->helper('url');
#edit
$route['admin/do_search'] = "admin_controller/admin/do_search";
This code is unnecessary.
In the past, I have set up a route for the ajax request. Something like this:
$route['admin/search/(:any)'] = 'admin_controller/admin/do_search/$1';
Then my ajax request would look like this:
var prod = $('#prod').val();
$.ajax({
type: 'post',
url:'admin/search/'+prod
...
});
Or, you can grab the form action via jQuery and use that as your url.
<form action="admin/search/123" method="post">
$.ajax({
type: 'post',
url: $('form').attr('action')
...
});
I know this works. My routes file is the default.
I loaded CI URL helper in my controller __construct() function
$this->load->helper('url');
Here's my ajax:
/*
*Ajax function to load confirmation page
*/
var formID=$("div form");
formID.submit(function(event){ //activated on submit event
event.preventDefault(); //stops page from reloading
$.ajax({
type:"POST",
url:'<?php echo site_url("plan/process")?>',
data:formID.serialize(),
success:function(data){
$("div #msg_area").html(data);
window.setTimeout(function(){parent.location.reload()},3000);
}
});
});
I have multiple controllers so it calls the specific one call plan and the \n the function process. The process function one looks like this:
function process (){
$json_data = strtolower(json_encode($this->input->post()));
$res = array();
//Simple Error/success display...
$res = json_decode($this->plan->process_plan($json_data ),true);
if(array_key_exists('error',$res)){
$window = "warning";
$error=explode(":",$res['error']);
$result['message']="<h2><span class='color-dark'>Submission error:</span> ".$error[0]." </h2><p>".$error[1]."</p>";
}
else{
$window = "success";
$result['message'] = "<h2>Submission was a success</h2>";
}
echo $this->load->view("common/components/".$window,$result);
}
This works great for me. Hopefully it helps.
in your routes file you have: admin321/do_search NOT: admin/do_search
You can also try using the absolute path:
`http://www.website.com/admin/do_search` or `http://localhost/admin/do_search`
in the ajax url parameter

Call php function from javascript and send parameter

I would like to send 'ID' to JS function then send the same ID again from JS function to php function.
Please tell me what is the wrong in my code!
<script type="text/javascript">
function deleteclient(ID){ //I receive the ID correctly until now!
var x = "<?php deleteclient11('ID');?>";
return false;
}
</script>
<?php
function deleteclient11($x)
{
echo "$x";
}
?>
You need to use AJAX, it's easy with jQuery or another library, so I'll demonstrate with jQuery.
javascript
var deleteClient = function(id) {
$.ajax({
url: 'path/to/php/file',
type: 'POST',
data: {id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
};
php file
<?php
if (isset($_POST['id'])) {
deleteClient11($_POST['id']);
function deleteClient11($x) {
// your business logic
}
}
?>
More info: jQuery.ajax()

Categories

Resources