How to get the jSON data value? - javascript

I just want to ask about my problem. I am a beginner in using jquery.
My problem is I want to get the json string from my jquery ajax request but I don't know how. Because I want to check if the json string values are correct.
Here's my code in jquery ajax:
$('#search-btn').on('click',function(){
var query = $("#keyword").val();
var image = "<?php echo base_url()."/resources/loading/loading43.gif"; ?>";
$('#loading').html("<img src='"+image+"' class='loeader' align='center' />");
var query_url = "<?php echo site_url('item_controller/searchItem'); ?>";
$.ajax({
type:'POST',
url: query_url,
data:{query: $("#keyword").val(), data_filter: $("#keyword").attr("data-selection")}, //how can I get the value of data_filter? and pass it to the controller?
dataType:'json',
async: false,
success:function(d){
//some codes for success. . .
},
});
$("#selection_filter").on('change',function(){
var filter = $("#selection_filter").val();
$("#keyword").attr("data-selection",filter);
});
This is the code for the events.
<table border="1" style="width: 100%; align: left" cellpadding="10" cellspacing="10" align="left">
<tr>
<td colspan="3">
<h5>SEARCH ITEM</h5>
</td>
</tr>
<tr>
<td style="width: 15%">
<label>Choose search filter: </label>
</td>
<td style="width: 25%">
<select id="selection_filter">
<option value="code">ITEM CODE</option>
<option value="itemname">ITEM NAME</option>
</select>
</td>
<td>
<input type="text" name="keyword" id="keyword" style="width: 80%" data-selection="code" /> <input type="button" value="SEARCH" id="search-btn" class="k-button" style="font-size: 12px" />
</td>
</tr>
</table>
This is my code for accessing the controller (CodeIgniter)
public function searchItem(){
$query = $this->input->post('query');
$filter = $this->input->post('data_filter');
if($filter == "code"){
$querySearch = "SELECT item_code,item_name from items WHERE item_code LIKE '%".$query."%' GROUP BY item_code";
}else{
$querySearch = "SELECT item_code,item_name from items WHERE item_name LIKE '%".$query."%' GROUP BY item_code";
}
$resultSearch = $this->db->query($querySearch);
$count = $resultSearch->num_rows();
echo json_encode($resultSearch->result_array());
//echo json_encode($querySearch);
}
What I want to get is:
In my ajax. There is a data that contains the value of keyword and data filter. Now What I need to do is get the data_filter value and pass it to the controller.

You can get the response inside your ajax like this
$.ajax({
type:'POST',
url: query_url,
data:{query: $("#keyword").val(), data_filter: $("#keyword").attr("data-selection")},
dataType:'json',
async: false,
success:function(res){
console.log(res.item_code);//Will give you the item code
console.log(res.item_name);//Will give you the item name
},
});

Ok got it just an error in my syntax. Thanks for the response guys.

Related

How to fetch database values in html text boxes on button press without refreshing page in php?

I want to fetch database values into text boxes without refreshing page. with page refresh it goes fine but I don't want to refresh it.
My code is shown below.
PHP
<?php
include 'Connection.php';
$sql=mysqli_query($connect,"select * from `registration`");
while ($row=mysqli_fetch_array($sql))
{
echo "<tr>
<td>".$row['Emp_Code']."</td>
<td>".$row['Full_Name']."</td>
<td>".$row['Permanent_Address']."</td>
<td>".$row['Mobile_No']."</td>
<tr>";
if (isset($_POST['Fetchdetails']))
{
$userid = $_POST['userid'];
$fetchquery = mysqli_query($connect,"select * from `registration` where `Emp_Code` = '$userid'");
if (mysqli_num_rows($sql)>0)
{
while ($row=mysqli_fetch_array($fetchquery))
{
$employeecode=$row['Emp_Code'];
$fullname=$row['Full_Name'];
$permanentaddress=$row['Permanent_Address'];
$mobileno=$row['Mobile_No'];
}
}
}
}
?>
My HTML Code is
<html>
<body>
<div align="center" id="div">
<table width="400" border="1">
<tr align="right" style="background-color:#FFF;">
<td width="100">Permanent Address : </td>
<td width="100">
<input type="text" name="permanentaddress" id="permanentaddress" placeholder="Permanent Address" size="15" value="<?php echo $permanentaddress;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Employee Code : </td>
<td width="100"> <input type="text" name="employeecode" id="employeecode" placeholder="Employee Code" size="15" value="<?php echo $employeecode;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Full Name : </td>
<td width="100"> <input type="text" name="fullname" id="fullname" placeholder="Full Name" size="15" value="<?php echo $fullname;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Mobile No. : </td>
<td width="100"> <input type="text" name="mobileno" id="mobileno" placeholder="Mobile No." size="15" value="<?php echo $mobileno;?>"/> </td>
</tr>
</table>
</div>
<br>
<div align="center">
<input type="submit" name="Fetchdetails" value="Fetch Details" id="Fetchdetails" />
</div>
</body>
</html>
How can I fetch values from database into text boxes without refreshing web page?
You can use AJAX to achieve the dynamic loading of the data.An Example would be:
$.ajax({
url: "yourscript.php",
cache: false,
success: function(html){
$("#results").append(html);
}
});
where yourscript.php is your backend script, where the database calls would be executed and returned back to your success on successful request.
Please note that the data should be exchanged in a serialized format(for AJAX requests the most common approach is JSON).
You can achieve this by json.
Try the following code.
PHP Code
<?php
include 'Connection.php';
$userid = $_GET['userid'];
$fetchquery = mysqli_query($connect,"select * from `registration` where `Emp_Code` = '$userid'");
if (mysqli_num_rows($sql)>0)
{
while ($row=mysqli_fetch_array($fetchquery))
{
$return['employeecode']=$row['Emp_Code'];
$return['fullname']=$row['Full_Name'];
$return['permanentaddress']=$row['Permanent_Address'];
$return['mobileno']=$row['Mobile_No'];
}
}
echo json_encode($return);
Javascript Code
$("#Fetchdetails").click(function(e) {
e.preventDefault();
var userId = $(this).attr('data-user-id');
$.ajax({
type: "GET",
url : 'http://localhost/test/get_data.php?userid='+userId,
dataType : 'json',
success : function(response) {
$('#permanentaddress').val(response.permanentaddress);
$('#employeecode').val(response.employeecode);
$('#fullname').val(response.fullname);
$('#mobileno').val(response.mobileno);
},
error : function() {
alert('There was an error');
}
});
});
Note : you have to replace following line with your php file url.
url : 'http://localhost/test/get_data.php

How do I display data back from a javascript calling a php function?

I'm using a MVC framework and in my view I have my javascript code
this is in my view:
<script>
$(document).ready(function(){
$(document).on('click','#filtr',function(){
var id_val = $('#id_val').val();
var key_val= $('#key_val').val();
console.log(id_val);
console.log(key_val);
$.ajax({
url:"<?php echo base_url()?>filter/filtr",
method:"POST",
data:{
id_val:id_val,
key_val:key_val
},
/*beforeSend:function(){
$("container_tab").html("Searching...");
},*/
success:function(data){
$("container_tab").html(data);
}
})
});
});
</script>
<div class="table-responsive">
<table class="table table-striped table-hover" id="dataTables-example">
<tr>
<td>
Filter by...
</td>
<td>
ID: <input type="text" id="id_val" name="id_val" value="3" />
</td>
<td>
KEY: <input type="text" id="key_val" name="key_val" value="asdf12" />
</td>
<td>
<button type="button" class="btn btn-info btn-sm" id="filtr">FILTER</button>
</td>
</tr>
<br />
<div id="container_tab"></div>
</table>
</div>
I want the table that comes back from my controller to fill <div id="container_tab"></div>
in my filter controller I have my filtr function, but this function for now does not return $filter_list even though I'm still not doing the actual query.
public function filtr(){
$filter_list = '';
$filter_list .= '
<tr>
<td style="vertical-align: middle;" class="text-center">this should be sent to view as a table row</td>
</tr>
';
echo $filter_list;
}
when I do a console.log within my javascript function the values '3' and 'asdf12' are display but I'm not getting anything back on screen from my controller function calling filtr.
There is a minor error in your success function, your containor has a id called container_tab so use a # in front of its name like this
success:function(data){
$("#container_tab").html(data);
}

How do I get a form populated using ajax and codeigniter

I am trying to teach myself code igniter and mvc. I have a working site in php that allows the input of an isbn number and returns the title, rank etc. I use ajax to get the information from amazon and then put it into the existing form. This works great, now i am trying to convert it to code igniter. My view is buybackmws.php and looks like this:
<?php echo validation_errors();?>
<?php echo form_open('buyback', $title);?>
<table height="220">
<tr>
<td><label>ISBN</label></td>
<td><input type="text" id="isbn" name="isbn" value="<?php echo set_value('isbn'); ?>" /></td>
<td></td>
<td rowspan=7><a id="detailURL" href="#" target="_blank"><img id="bookCover" src="<?php echo base_url();?>images/imgNotFound.gif" height="200px" /></a></td>
</tr>
<tr>
<td><label for="quantity" class="label">Quantity</label></td>
<td><input type="text" id="quantity" name="quantity" value="<?php echo set_value('quantity'); ?>"/></td>
<td></td>
</tr>
<tr>
<td><label for="payPrice" class="label">Price to Pay</label></td>
<td><input type="text" id="payPrice" name="payPrice"/></td>
<td></td>
</tr>
<tr>
<td><label>Edition</label></td>
<td><input type="text" id="edition" name="edition" readonly="readonly"/></td>
<td></td>
</tr>
<tr>
<td><label>Title</label></td>
<td><input type="text" id="title" name="title"/></td>
<td></td>
</tr>
<tr>
<td><label>Sales Rank</label></td>
<td><input type="text" id="salesRank" name="salesRank" readonly="readonly" /></td>
<td></td>
</tr>
<tr>
<td></td><td><input type="button" id="buy" value="Buy" /></td><td></td>
</table>
<?php echo form_close() ?>
my js with the ajax is buybackmws.js:
$('#isbn').keydown(function () {
//retrieve price to pay (and other data)
var isbn = $('#isbn').val();
$('#quantity').val('0'); //default quantity to 0
$('#buy').attr('disabled', false).css('backgroundColor', '');
$('#quantity').css('border', '');
$('#payPrice').css('border', '');
$('#payPrice').css('backgroundColor', '');
$('#payPrice').css('color', '');
$.ajax({
type: "POST",
url: ' ../verifybuyback/title',
async:false,
dataType: "json",
data: ({isbn: isbn }),
success: function(data){
console.log(data);
$('#title').val(data.title);
$('#salesRank').val(data.salesRank);
$('#edition').val(data.edition);
$('#binding').val(data.binding);
$("#detailURL").attr("href",data.DetailURL);
} //end of success
});
verifybuyback is:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Verifybuyback extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('amz','',TRUE);
$this->load->helper('amazon');
}
function title()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('isbn', 'ISBN','trim|required|xss_clean|callback_title_check' );
if($this->form_validation->run('title')==FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('buybackmws');
}
else
{
//GOTO RESTRICTED AREAS
redirect('buybackmws', 'refresh');
}
}
function title_check()
{
//Field validation succeeded. Validate against database
$isbn=$this->input->post('isbn');
//QUERY AMAZON FOR THE INFORMATION
$result = basic($isbn);
if($this->session->userdata('amazon'))
{
$sess_array = array();
$result=$this->session->userdata('amazon');
$sess_array=array(
'title'=>$result['Title'],
'rank'=>$result['SalesRank'],
);
}
else
{
$this->form_validation->set_message('get_title', 'Invalid ISBN number');
return false;
}
}
} //END OF BUYBACK
When I test it, and look at what is shown in the response tab, the information is there. My console.log is not doing anything so i don't think the information is being returned to the js. I am therefore having an issue getting everything into the view. How do I do this?
EDIT: I got the console.log in the ajax success to show the results in Firebug, but they are still not populating the form. Any ideas??
you are using datatype json for ajax . Remove json datatype and use
$data['view'] = $this->load->view($view, $this->data, true);
$this->output->set_output($data);
you can now access data.view in ajax
OR
with json in datatype
Use
$data['view'] = $this->load->view($view, $this->data, true);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
Also if you redirect in controller from ajax it will not work for page . you need to redirect in ajax after success return data

after posting multiple variables sucess or request.done not working

That post helped me to pass variables from a php Form to javascript.
Now I would like to send them to a php file which should update a DB with the values. For simplicity I created this file which should just return the values to check if it works:
addCOmmentsToDBtest.php:
<?php
$video_id = $_POST['VideoId'];
$starttime = $_POST['starttime'];
echo "Test! \n StartTime = " .$starttime. " videoId = " .$video_id; ?>
The whole jquery $.ajax function which calls addCOmmentsToDBtest.php is in the file below (JqueryTest.php). I tired to pass the data in the url:
url: "addCommentsToDBtest.php?starttime="+ starttime +"endtime="+ endtime +"&text="+text+"&videoid="+videoid,
or to pass the data like this
$.ajax({
url: "addCommentsToDBtest.php",
type: "POST",
data: {
'videoId': '<?php echo $video_id ?>',
'starttime': starttime,
'endtime': endtime,
'text': text,
'cat': cat
}
Both didn't work. The problem is also that in this simple example the string from addCOmmentsToDBtest.php
echo "Test! \n StartTime = " .$starttime. " videoId = " .$video_id;
is not passed to the div tag "log". (I also tried to insert the value in the db, like it should be at the end - didn't work).
To pass the string I tried:
success: function(data) {
$("#log").html("Sucess"+ data);
}
or
complete: function(data) {
$("#log").html("Sucess"+ data);
}
or
request.done(function( msg ) {
$( "#log" ).html("Sucess! Msg =" + msg );
});
The screenshot of the Chrome debugger:
The question is: How can I pass the Data from addCOmmentsToDBtest.php back to check if the variables got transfered in this simple example?
And what I try to achieve in the end is:
To pass the Data from JqueryTest.php to addCOmmentsToDBtest.php and update my DB.
Thanks in advance for any help.
Here the file which contains the whole javascript and php form.
JqueryTest.php:
<?php
$video_id = '153fb143';
?>
<!DOCTYPE html>
<html>
<head>
<title>JQUERY</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function addCommentsToDB () {
var videoid = document.getElementById('videoid').value;
var starttime = document.getElementById('starttime').value;
var endtime = document.getElementById('endtime').value;
var text = document.getElementById('text').value;
var cat = document.getElementById('cat').value;
alert ("starttime ="+starttime+"; Endtime = "+endtime+"; text = "+text);
$.ajax({
url: "addCommentsToDBtest.php?starttime="+ starttime +"endtime="+ endtime +"&text="+text+"&videoid="+videoid,
// check ''
// url: "addCommentsToDBtest.php?starttime="+ starttime +"endtime="+ endtime +"&text="+text+"videoId='"+videoId+"'",
// with data use that:
// url: "addCommentsToDBtest.php",
type: "POST",
/* Does not Work
data: {
'starttime': starttime,
'endtime': endtime,
'text': text,
'cat': cat }, */
success: function(data) {
$("#log").html("Sucess"+ data);
}
});
};
</script>
</head>
<body>
<div id="log"> <p>log</p></div>
<div id="msg"></div>
<table>
<tr>
<td><div id="div1">div1</div></td>
<td><div id="div2">div2</div></td>
</tr>
<tr>
<td><div id="div3">div3</div></td>
<td><div id="div4">
<!--ADD Table-->
<form method="post" onsubmit="addCommentsToDB()" action="<?php $_SERVER['PHP_SELF']?>" >
<table width="150px" border="1" cellpadding="0">
<tr>
<td width="25px"><p>start</p></td>
<td width="25px"><p>end</p></td>
<td width="75px"><p>Text</p></td>
<td width="10px"><p>cat</p></td>
<td width="5px"><p>+</p></td>
</tr>
<tr>
<td><input style="width: 75px" type="time" name="starttime" id="starttime"></td>
<td><input style="width: 75px" type="time" name="endtime" id="endtime"></td>
<td><input style="width: 75px" type="text" name="text" id="text"><input type="hidden" id="VideoId" name="VideoId" value="<?php echo $video_id; ?>"></td>
<td>
<select width="15" name="cat" id="cat">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
<td><input type="hidden" name="videoid" id="videoid" value="<?php echo $video_id ?>"><input name="ADD" type="submit" value="add"> </td>
</tr>
</table>
</form>
</div></td>
</tr>
</table>
</body>
</html>
First of all set addCommentsToDB(); return false; into onsubmit of your form. Without it your form will continue submitting.
Second don't use url with GET parameters if you are using ajax POST. Send your data using data attribute.
You need to add an & to the 2nd variable
url: "addCommentsToDBtest.php?starttime="+ starttime +"endtime="+ endtime +"&text="+text+"&videoid="+videoid,
Should be
url: "addCommentsToDBtest.php?starttime="+ starttime +"&endtime="+ endtime +"&text="+text+"&videoid="+videoid,

Updating table rows in datatables with jquery

How can I use jQuery ajax to handle checked checkboxes? How do I then send each checked checkbox in the html table, to ajax.php?
This is what I've tried so far:
ajax.php
session_start();
if (isset($_POST['id']) && isset($_POST['to']) && isset($_SESSION['user']['id'])) {
if (is_numeric($_POST['id']) && is_numeric($_POST['to'])) {
include("mysql_connector.php");
$user = $_SESSION['user']['id'];
$sendTo = mysql_real_escape_string(trim($_POST['to']));
foreach ($_POST['id'] as $id) {
$id = mysql_real_escape_string(trim($id));
mysql_query("UPDATE `email` SET status = '$sendTo' WHERE `email_id` = '$id' AND `userid` = '$user'");
}
}
}
Javascript:
$(".submit").click(function() {
var id = $("#id").val();
var to = $("#bins").val();
var dataString = 'id=' + id + '&to=' + to;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
});
});
html:
<form method="POST">
<table id="inventory" class="table">
<thead>
<tr>
<th style="text-align: center;">Check All</th>
<th>Time Received</th>
<th>Email</th>
<th>Subject</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="2" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>0</td>
</tr>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="3" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>1</td>
</tr>
</tbody>
</table>
</br>
<select name="bins" class="bins">
<option value="1">Archive</option>
<option value="2">Read</option>
<option value="3">Unread</option>
<option value="4">Save</option>
</select>
<input type="submit" name="move" value="Move" class="submit" style="width:auto;"/>
</form>
Thank you for reading.
First, it is invalid to have multiple dom elements with duplicate ids. If those checkboxes need ids, make them unique. If they don't need ids, then just drop them completely.
To get a list of the values of all checked checkboxes, do:
var checkedVals = [];
$("input[type='checkbox']:checked").each(function() {
checkedVals.push($(this).val());
});
Or you can fetch different groups of checkboxes by name:
var checkedMsgVals = [];
$("input[name='msg[]']:checked").each(function() {
checkedMsgVals.push($(this).val());
});
To send these to php, just include them in your data packet when you make the call. To do this you'll want to send an object over, not a querystring.
var dataObj = {'id': id, 'to': to, 'checkedValues': checkedMsgVals };
$.ajax({
type: "POST",
url: "ajax.php",
data: dataObj,
});

Categories

Resources