codeigniter update database using ajax then show - php

I would like this function:
After I select an option I want to update right away the database and then show it right away also inside a certain div. How can I achieve this?
Here's my HTML:
<select id="category1" name="cat1">
<option>Hardware</option>
<option>Software</option>
<option>Network</option>
</select>
AJAX code:
$('#category1').on('change',function(){
var data = $("cat1").val();
var ticket = '<?php echo $ticket_details[0]["cTicketNo"];?>';
if(data){
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo base_url();?>User/TicketView/update_cate",
data: {data: data,ticket: ticket},
success:function(response){
alert('successful');
},
error: function(response){
alert('tangina!');
}
});
}
});
Controller:
function update_cate(){
$this->TicketView_m->update_cat1();
redirect($_SERVER['HTTP_REFERER']);
}
Model:
function update_cat1(){
$ticket_id = $_POST['ticket'];
var_dump($cat = $_POST['data']);
$this->db->set('vCategory',$cat);
$this->db->where('cTicketNo',$ticket_id);
$this->db->update('tconcerns');
}
THanks for all the help!

Drop that redirect($_SERVER['HTTP_REFERER']);, You don't need that.
First of all, AJAX will allow you to send data to server without redirecting to another page.
Based on your AJAX dataType. It is JSON. So for you to get the result, You have to encode it to JSON like json_encode(['result' => 'things you want to show']).
Then you can access it in your response like this:
success:function(response){
alert('successful');
var res = response.result; //Access the JSON
$("#certainDiv").html( res ); //Print to the div you want
}
And it is also better to get the post request in your controller then pass it to your model:
function update_cate(){
$ticket_id = $this->input->post('ticket');
$cat1 = $this->input->post('cat1');
$this->TicketView_m->update_cat1($ticket_id, $cat1);
echo json_encode(['result' => 'things you want to show']);
}

Related

How to understand and retrieve multiple values from a php script through jquery $.ajax function?

While using jquery $.ajax or $.post, to submit a value (say uid {user id}) how can I define a callback function to retrieve multiple values from the php script and retrieve values from my mysql table say(user details, corresponding to the uid) and store them in vars, using the default datatype:datatype???
Can anyone please show me both the jquery and php scripts please. And yes the database is runninga mySQL 5.5.24 and PHP version is 5.3
instead of using $.ajax you can also use this...
var id=$("#id").val();
$.getJSON('script.php', {id:id}, function(json) {
var id=json.id;
var name=json.name;
var email=json.email;
});
}
in your php scrip..
<?php
mysql_connect($host,$dbuser,$dbpass);
mysql_select_db($db_name);
$id=$_GET['id'];
$query="select * from tbl_name where id='$id'";
$rs=mysql_query($query);
$row=mysql_fetch_assoc($rs);
$id=$row['id'];
$name=$row['name'];
$email=$row['email'];
$data=array("id"=>$id,"name"=>$name,"email"=>$email);
echo json_encode($data);
?>
The best way to do this would be to send it back to javascript as a json object.... so for your user example
// assuming post containing a username, using pseudo code for db access
$row = $db->fetchAssoc("select * from users where username = '".dbEscape($_POST["username"]."'");
header("Content Type: application/json");
echo json_encode($row);
ajax code will be like follows
$.ajax({
type: "POST",
url: "your_page.php",
data: { param1: "val1", param2: "val2" }
}).done(function( data) {
// do your callback operation
});
get values from your_page.php like below
$_POST["param1"] , $_POST["param2"]
if you want to know more then click here
I think this will solve your problem.
<script type="text/javascript">
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data contains the data we get from serverside
{
}
});
</script>
dataType: json..so jason will return multiple values. from you php script
echo json_encode($array_of_val);
$.ajax({
type: "POST",
dataType:"html",
url: "ajax_page.php",
data:"params1="$params1"&params2="+$params2,
}).done(function(value) {
// write your callback operation
});
you can get your data on ajax_page.php using an post method like
$_POST['params1'];
and
$_POST['params2'];
$query= select statement
$items=array();
while ($row = mysql_fetch_object($rs)) {
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);

jQuery AJAX refresh page content after success

I'm updating my database with jQuery .click() and then calling my AJAX; my question is once the SQL has ran what is the best way to refresh the content on the page so I'll be able to do the previous action again, currently I'm using window.location.reload(true); but I don't like that method because I don't want to have the page reloading all I want is for the content on the element I used to update it with to be to match the database field after the AJAX was successful
Here's my jQuery:
$(document).ready(function(){
$("span[class*='star']").click(function(){
var data = $(this).data('object');
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success: function(data){
if(data == false) {
window.location.reload(true);
} else {
window.location.reload(true);
}
}
});
console.log(data.art_featured);
});
});
PHP:
<section class="row">
<?php
$sql_categories = "SELECT art_id, art_featured FROM app_articles"
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row">
<div class="column one">
<?php if($row['art_featured']==0){
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star"></span>
<?php
} else if($row['art_featured']==1) {
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star-color"></span>
<?php
}
?>
</div>
</div>
<?php
}
} else {
echo "FAIL";
}
?>
</section>
EDIT:
I need to update the class .star or .star-color with art_featured depending on what the value of a art_featured is at the time, basically where ever I'm echoing out art_featured I need that to reload once the Ajax is successful.
EDIT:
$("span[class*='star']").click(function(){
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success:function(art_featured){
//remember $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object')),{
art_featured: art_featured
});
}
});
console.log(data.art_featured);
});
If you can just return art_featured after the MySQL database success, it'll send it back to the ajax success function. here, we can manipulate data, however, first we should store reference to the element that was clicked on.
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
Now in our success function, instead of using data just use art_featured because that's all we are returning. Now we can update the existing data object on the target.
success:function(art_featured){
//remmeber $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object'),{
art_featured: art_featured
}));
}
The above will extend the existing data object, allowing key:value pairs to be redefined based on the object we are extending.
You should find this working as intended.
I don't fully understand your question so let's assume the content you want to change is a div with class div, and you want to replace the content with the content just sent i.e. the data. Then you would need to return the data (probably using JSON would be easiest), then your call would be
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
for(n in data){
$('.div').append('<p>'+data[n]+'</p>');
}
}
});
Note addition of dataType return as being json, then iterating over the json data by for n in data, then using n to call the data from the array. So if the third item was name then you could do something like
$('.div').append('<p>Name is '+data[3]+'</p>');
You will have to return the data from the PHP form by json encoding it which can be done with the json_encode php function. If it's cross domain you'll have to use jsonp
EDIT:
If you already know the data you want to replace before you send the form (i.e. don't need a response) then you can just put those variables into the success call back. This will wait for the ajax to return successfully, then update your div.
So you could have this
var updateText = yourDataFromForm
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
$('.div').append('<p>'+updateText+'</p>');
}
});

Wordpress - fetch user info using jQuery ajax POST request

I am working in Wordpress trying to use an ajax request to fetch user data by passing the user id.
I can see that the user id sends correctly via AJAX POST but I am getting an internal error message and I don't know why.
At first I thought it was because I was trying to fetch some custom fields that I had added to the user profile but even when I simplified my script I am still getting the error message.
Any help is much appreciated!
Front End
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: 'wp-content/themes/twentyeleven/author_info.php',
data: {id: id},
dataType: 'html',
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
author_info.php
$user_id = $_POST['id'];
$forename = get_the_author_meta('user_firstname', $user_id);
$output = $user_id;
echo $output;
Error Message
500 (Internal Server Error) jquery.min.js:4
Mathieu added a hackable approach to intercepting a request and redirecting it, which is fine. I prefer to build out AJAX responses that return json_encoded arrays.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
url: 'http://absolute.path/wp-admin/admin-ajax.php',
data: {'action' : 'ajax_request', 'fn': 'getAuthorMeta', 'id': id},
dataType: 'json',
success: function(data) {
//We expect a JSON encoded array here, not an HTML template.
}
});
return false;
});
Now we build out the function to handle our ajax requests.
First, we need to define our ajax add_action method ->
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
We need to use both add_action lines here. I won't get into why. You'll notice the _ajax_request here. This is the 'action' that we sent over in our AJAX function data: {'action' : 'ajax_request'}. We use this hook to validate our AJAX request, it can be anything you'd like.
Next, we'll need to build out or function ajax_handle_request.
function ajax_handle_request(){
switch($_REQUEST['fn']){
case 'getAuthorMeta':
$output = ajax_get_author_meta($_REQUEST['id']);
break;
default:
$output = 'That is not a valid FN parameter. Please check your string and try again';
break;
}
$output = json_encode($output);
if(is_array($output)){
return $output;
}else{
echo $output;
}
}
Now let's build our function to actually get the author meta.
function ajax_get_author_meta($id){
$theMeta = get_the_author_meta([meta_option], $id);
return $theMeta;
}
Where [meta_option] is a field provided by WP's native get_the_author_meta function.
At this point, we'll now go back to our success:function(data) and (data) is a reference to the json_encoded array we've returned. We can now iterate over the object to get our fields and output them into the page as you'd like.
You are not in a POST at that moment because you are calling a specific page of your template that probably doesn't correspond to any article in your blog.
Instead, create a pluggin that will do this:
add_action('template_redirect', 'my_author_meta_intercept');
function my_author_meta_intercept(){
if(isset($_POST['getAuthorMeta'])){
echo get_the_author_meta('user_firstname', $_POST['getAuthorMeta']);
exit();
}
}
This will short circuit the request to the same page as before when you call it using:
http://mysite/mycurrenturl?getAuthorMeta=testMetaKey
So calling that post normally will return the article as usual, but if you pass in ?getAuthorMeta, it will stop the template from being selected and simply return the exact content you want it to return.
In your page, you just have to change your javascript to:
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: window.location.href,
data: {getAuthorMeta: id},
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
Just make sure you adapt the concept to what you need!
I would rather recommend you to use WP AJAX action method.
As in your case, add the following to your functions.php file.
add_action('wp_ajax_get_user_info', 'ajax_get_user_info');
add_action('wp_ajax_nopriv_get_user_info', 'ajax_get_user_info');
function ajax_get_user_info() {
//Handle request then generate response using WP_Ajax_Response or your html.
}
then in javascript tag.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
jQuery.post(
ajaxurl, /* if you get error of undefined ajaxurl. set it to "http://example.com/wordpress/wp-admin/admin-ajax.php"*/
{
'action':'get_user_info',
'user_id':id
},
function(response){
alert('The server responded: ' + response);
}
);
});
I would recommend you to read the 5 tips for using AJAX in WordPress.
p.s; Code above is not tested, it may have errors. but you get the idea.

why couldn't I get value through Ajax call?

I've created one Ajax function like this:
function searchPlanAjax(url){
jQuery('#loader').css('display','block');
var plan = jQuery('.rad').val();
var site = url+"fbilling_details/subscription";
jQuery.ajax({
type: "POST",
url: site,
data: "plan="+plan,
//data: "business_name="+val+"&bs="+bs,
success: function(msg){
jQuery('#loader').css('display','none');
}
});
}
Which I'm calling on radio button's onclick:
<?php echo $form->text(BILLING_DETAIL.'][id_plan', array('type'=>'radio', 'value'=>$val[PLAN]['id'], 'id'=>'id_plan_'.$val[PLAN]['id'], 'class'=>'rad','onclick'=>'searchPlanAjax('."'".SITE_NAME.ROOT_FOLDER_NAME."'".')')); ?>
The Ajax call will be processed in controller of cakePHP like this:
if(!empty($_REQUEST['plan'])){
$search_plan = $this->{PLAN}->find("all",array("conditions"=>array("id=".$_REQUEST['plan'])));
$this->set('search_plan',$search_plan);
}
but I couldn't get value in $search_plan variable. thanks if anybody can help.
Look at conditions in your find query
if(!empty($_REQUEST['plan'])){
$search_plan = $this->{PLAN}->find("all",array("conditions"=>array("id" => $_REQUEST['plan'])));
$this->set('search_plan',$search_plan);
}

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories