Print json from mysql - php

Hi all I have a site developed in codeigniter.
In some function I have to retrieve data from mysql and print the result in javascript because is an ajax call.
Thi is my php function to retrieve data:
public function getCityByNameOnly($name) {
$query = $this->db->query('SELECT * FROM city WHERE name LIKE "%'.$name.'%" ');
$city = array();
foreach ($query->result() as $row)
array_push($city, $row);
return json_encode($city);
}
}
And this is my ajax call:
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "text",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name_en + '<br> ');
}
}
});
}
})
I append the result into a div but is always undefined.
This is the console.log of my created json:
{"id":"125","name_it":"Lèsina (Hvar)","name_en":"Hvar","nation_id":"23","region_id":"0","active":"1"},{"id":"127","name_it":"Trogir (Traù)","name_en":"Trogir","nation_id":"23","region_id":"0","active":"1"},{"id":"1088","name_it":"Città del Capo","name_en":"Cape Town","nation_id":"101","region_id":"0","active":"1"}]
How to print this json into my success function in javascript?
Thanks

change the datatype:"json" in the ajax will solve the issue
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "json",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name + '<br> ');
}
}
});
}
})

Related

CodeIgniter Json Ajax Database insertion is not working

I have tried to solve this issue, here i am inserting dynamic inputbox box values into database including their title. But not working...
Inputbox dynamic generation: (This works well)
$('#myTable tbody').append("<tr><td>"+rno+"</td><td>"
+item.stdname+"</td><td><input type='text' name='stdmark[]' class='mark' title='"+item.stdid+"' style='padding: 0px; width: 50px;'/></td></tr>");
Ajax to Send these values into controller:
$('#marklist').submit(function(e){
//var mark = 10;
jsonObj = [];
$("input[class=mark]").each(function() {
var id = $(this).attr("title");
var subjectmark = $(this).val();
item = {}
item ["stdid"] = id;
item ["mark"] = subjectmark;
jsonObj.push(item);
});
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>office/addmark",
data: {senddata :JSON.stringify(jsonObj)},
dataType: "json",
processData:false,
contentType:false,
cache:false,
async:false,
success:
function(retrived_data){
}
});
e.preventDefault();
});
Controller:
public function addmark()
{
$marks = json_decode($this->input->post('senddata'), true);
$this->load->Model('wtcmodel');
foreach($marks as $row)
{
$data = array(
'stdid' => $row->stdid,
'mark' => $row->mark
);
$this->wtcmodel->adddata($data);
}
}
Model:
public function adddata($data)
{
$this->load->database();
$this->db->insert('table_info',$data);
}
you can post input data using this method.
var stdid = $('input[name="stdmark[]"]').map(function(){
return $(this).attr('title');
}).get();
var marks = $('input[name="stdmark[]"]').map(function(){
return this.value;
}).get();
$.ajax({
type: 'POST',
url: 'users.php',
data: {
'stdid[]': stdid,
'marks[]':marks
},
success: function() {
}
});
You can access stdid[] and marks[] variable as array directly in controller.
Controller
public function addmark()
{
$stdid = $this->input->post('stdid');
$marks = $this->input->post('marks');
$this->load->Model('wtcmodel');
foreach($stdid as $key => $row)
{
$data = array(
'stdid' => $stdid,
'mark' => $marks[$key]
);
$this->wtcmodel->adddata($data);
}
}
why did't use Jquery serialize function : http://api.jquery.com/serialize/
$('#marklist').submit(function(e){
e.preventDefault();
//var mark = 10;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>office/addmark",
data: $(this).serialize(),
dataType: "json",
processData:false,
contentType:false,
cache:false,
async:false,
success:
function(retrived_data){}
});
});
or you can use param : http://api.jquery.com/jquery.param/

selecting 2 different option values and sending data to php using ajax

I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.
This is my jQuery code:
$(document).ready(function() {
$("#updateStatus").change(function() {
var opt = $("#updateStatus").val();
$("#updateStatus1").change(function() {
var sta = $("#updateStatus1").val();
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: "option=" + opt + "&status=" + sta,
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
});
});
});
This is my PHP code:
$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (!$row) {
echo json_encode("fail");
} else {
echo json_encode("sucess");
}
Replace your existing ajax function like this
$(document).ready(function() {
var opt = '';
var sta = '';
$("#updateStatus").change(function() {
opt = $("#updateStatus").val();
});
$("#updateStatus1").change(function() {
sta = $("#updateStatus1").val();
callAjax(opt,sta);
});
});
function callAjax(opt,sta) {
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: "opt=" + opt + "&sta=" + sta,
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
}
You are passing the json body as a query string, and you are declaring to use dataType: "json"
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: "option=" + opt + "&status=" + sta,
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
instead that you should do it like this:
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: {"option": opt, "status": sta},
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
You are sending request under data using "option=" and "&status=" but you are reading these values in PHP through $_POST['opt'] and $_POST['stat'] which should actually be $_POST['option'] and $_POST['status'] respectively.
Also you need to change the data request to JSON format like data: {option:opt,status:sta} for your dataType is JSON
Your code should be like this
$(document).ready(function () {
$("#updateStatus,#updateStatus1").change(function () {
var opt = $("#updateStatus").val();
var sta = $("#updateStatus1").val();
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: {option:opt,status:sta},
dataType: 'json',
success: function (data) {
alert(data + "hello");
}
});
});
})
and php code should like this
$id = $_POST['option'];
$status = $_POST['status'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (!$row) {
echo json_encode("fail");
} else {
echo json_encode("sucess");
}
Thanks every one looks like i just had to change some code in ajax this is my new code which is working fine
This is my PHP code I got rid of if(!$row)
mysql_select_db("dts_db",$con);
$id=$_POST['opt'];
$status=$_POST['sta'];
$query="UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result=mysql_query($query);if(!$result){ die("My sql query result ".mysql_error());}
else {
echo json_encode("success");
}
and this is my ajax
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: {opt:opt,sta:sta},
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});

Magento Ajax Request - how to correctly pass data?

Since couple of weeks(two) started my adventure with Magento. So far I've learned a little but have a problem how to send data using Ajax (jQuery).
$(document).ready(function(){
var total = $(this).find(\"input[class=tramp]:checked\").length;
$(\".caret input[type='checkbox']\").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
This is my Ajax, so as you can see trying to send brand and value. AjaxController.php looks like this:
class Amber_Checkbox_AjaxController extends Mage_Core_Controller_Front_Action {
public function indexAction()
{
$brand = Mage::app()->getRequest()->getPost('brand', 'value');// not sure or I should use data?
if($brand )
{
....
$this->getResponse()->setBody($brand);
echo $brand;
...
}
}
}
remove \"
$(document).ready(function(){
var total = $(this).find("input[class=tramp]:checked").length;
$(".caret input[type='checkbox']").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
remove \", $ replace with jQuery and pass absolute URL Mage::getUrl('checkbox/ajax/index');
$.ajax({
data: data,
url: '<?php echo Mage::getUrl("checkbox/ajax/index"); ?>',
method: 'POST',
success: function(result){
console.log(data, total);
}});

Access Data from Database with Ajax

I have tried just about every solution and I know my database returns values if i hard code in the php so the issues is returning the values or determining if it is actually sent as post. It gets to the success function and alerts Worked but I am getting undefined for Item ID.
$(document).ready(function() {
$('.check').click(function(){
alert("Step1");
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "GET",
url: "XXX.PHP",
data: { "ID": thisID},
cache: false,
async:true,
datatype: "json",
success: function(data)
{
alert("WORKED");
alert(data.ItemID);
}
});
});
});
Here is the PHP
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
function retrieve($ID)
{
$stmt = $mysqli->query("SELECT * FROM database1.menu WHERE ItemID = $ID");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
You could try something like this. Not sure if this is what you need.
$(".check").click(function(event){
event.preventDefault();
var $this = $(this);
var thisID = $this.attr('id');
$.ajax({
type: "POST",
url: base_url + "url.php",
data: {
id: thisID
},
dataType: "text",
cache:false,
success:
function(data){
alert(data);
}
});
return false;
});

Using AJAX form submit to submit and retrieve data from MySQL

Basically, I'm trying to make it so that when a post is submitted to my site, it sends the post using AJAX so that they don't change page, and then if the AJAX post is successful, retrieve all the posts for said user from MySQL and write them onto the page.
My problem is that the browsers (Chrome, IE) are completely ignoring the AJAX request.
My form:
<div id="updatestatus">
<form action="" method="post" id="ps">
<textarea name="status" id="status"></textarea>
<input type="hidden" name="uid" id="uid" value="<?php echo $uid; ?>" />
<input type="submit" id="poststatus" name="poststatus" value="Share" />
</form>
</div>
My AJAX request:
$(function() {
$("#poststatus").click(function() {
var status = $("textarea#status").val();
if (status == "") {
return false;
}
var uid = $("input#uid").val();
var dataString = 'status='+ status + '&uid=' + uid;
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid=<?php echo $uid; ?>",
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>);
return false;
}
});
return false;
});
});
});
});
My ajax/query.php request
<?php
//connect stuff
$uid = strip_tags(stripslashes(htmlspecialchars(htmlentities(mysql_real_escape_string($_GET['uid'])))));
$result = mysql_query("SELECT * FROM mingle_status WHERE uid = '$uid' ORDER BY timestamp DESC"); //query
$array = mysql_fetch_row($result); //fetch result
echo json_encode($array);
?>
Thanks in advance for any help - Joe
In this section of JS code
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid=<?php echo $uid; ?>",
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>);
return false;
}
});
return false;
});
});
You need to remove the ending bracket after the curly brace which follows the last return false, such as...
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid=<?php echo $uid; ?>",
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>");
return false;
}
});
return false;
};
});
Try this
$(function() {
$("#poststatus").click(function() {
var status = $.trim($("#status").val());
if (status == "") {
return false;
}
var uid = $("#uid").val();
var dataString = 'status='+ status + '&uid=' + uid;
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid="+<?php echo $uid; ?>,
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>);
return false;
}
});
return false;
}
});
});
});

Categories