I have to pass data value to controller using ajax - javascript

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 .

Related

Ajax not able to post javascript variable to php

I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>

How to get POST data using Jquery AJAX

I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>

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()

PHP Function with jQuery AJAX?

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

Categories

Resources