Redirect Page With Data - php

I did some research on this topic but i cant run this id is not send to page.
listdata.php
<td class="text-center" style="min-width:130px;">
<button style="width:100%" class="btn btn-primary detail-customer" data-id="<?php echo $m->id; ?>">Bilgi</button>
</td>
ajax.php
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: "id=" + id
})
.done(function(data) {
window.location = "customers/info";
})
})
controller:
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
print $id;
//$this->template->views('customers/info', $data);
}

Are you naming your ajax file as Ajax.php? is that a PHP file? It definitely should be a js file.
From what I know from Jquery and Ajax, url key takes the location of the PHP file, and the data key should be passed as an object. Take these two files as an example:
Ajax.js
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/absolute_path/to/php_file.php",
data: {my_id:id, my_custom_key: "my_custom_value"},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function(response){
console.log(response);
}
})
.done(function(data) {
window.location = "customers/info";
})
})
Php_file.php
<?php
$id = $POST["my_id"];
$customValue = $POST["my_custom_value"];
$response = ["message"=> "We took your id which is $id and your custom value which is $customValue"];
echo json_encode($response);
?>
This is a very basic example of how to use ajax.

Please try it
$(document).on("click", ".detail-customer", function() {
var id = $(this).data("id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: {"id":id},
Content-Type:"json"
});
.done(function(data) {
window.location = "customers/info";
})
});
"we do not read your complete controller code
if your code is correct total then please
first convert data in json then
return it.
"
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
echo json_encode($id);
//$this->template->views('customers/info', $data);
}

Related

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

Ajax sends data , but returns nothing

I have got this html
<div class="Likes" data-i=<?php echo $row[8];?>>
<img src="../img/like.png">
<p class="L_c"><?php echo $row[4];?></p>
</div>
And this jquery/ajax
$(".Likes").click(function() {
var i = $(this).attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
$(this).children(".L_c").html(data);
}
});
});
Connect.php
if (isset($_GET["I"]) && !isset($_GET["C"])) {
$RandS=$_GET["I"];
$query3=$con->query("SELECT id,likes FROM uploads WHERE Rand='$RandS'");
$row=$query3->fetch_row();
$IdU=$row[0];
$Likes=$row[1];
$Sel2=$con->query("SELECT id FROM likes WHERE User_id='$NameId' AND Post_id='$IdU'");
$num_rows=$Sel2->num_rows;
if ($num_rows>0) {
echo $Likes;
}else{
$query=$con->query("INSERT INTO likes (Post_id,User_id,`DATE`) VALUES('$IdU','$NameId',NOW())");
$query=$con->query("UPDATE uploads SET Likes=$Likes+1 WHERE Rand='$RandS'");
echo $Likes+1;
}
}
But it does not return anything untill i refresh the page
The this keyword inside the $.ajax methods callback is not the element, but the ajax call itself.
You have to either set context, or just store the outer this -value
$(".Likes").on('click', function() {
var me = $(this);
var i = me.attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
me.find(".L_c").html(data);
}
});
});

Return JSON from PHP to ajax on button click

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);
}
});
});
});

Unable to retrieve variables from ajax post in codeigniter

I am new to using ajax and I am having trouble with posting variables and accessing those variables in my controllers.
Here is the Controller Code
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
/* $this->load->model('product_model');
$q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
$data = $this->product_model->get_record_specific($q);
echo json_encode($data[0]->quantity);
*/
echo $product;
}
function index()
{
$this->load->view('autocomplete_view');
}
}
If I change the echo to a string inside single quotes like this 'Hello World', it will return the hello world back to the view correctly. But it will not do the same if I try it as it currently is. Also if I use echo json_encode($product); it then returns false.
Here is view code with ajax.
$( document ).ready(function () {
// set an on click on the button
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: 'productName',
success: function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<h1> Get Data from Server over Ajax </h1>
<br/>
<button id="button">
Get posted varialbe
</button>
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
//echo $product;
//in ajax dataType is json -here You have to return json data
echo json_encode($product);
}
...
}
//javascript file
var productName = $('#productName).val();//get value of product name from form
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: {productName:productName},//You have to send some data from form
success: function(msg){
alert(msg);
}
});

Using jQuery JSON in CodeIgniter

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;
}

Categories