Json object in javascript Codeigniter - javascript

This is the Jquery that calls the function in controller. But it is not able to read the Json_encoded object. I am using codeigniter. Why?
$(this).ajaxSubmit({
type : "POST",
url: '../index.php/user/signin', // target element(s) to be updated with server response
cache : false,
dataType:'json',
success : function(data){
data = $.trim(data);
alert(data);
var obj = jQuery.parseJSON(data);
alert(obj.Condition);
},
error: function(){
}
Controller
$arr = array('Condition' => $condition, 'Message' => $msg);
// header('Content-Type: application/json');
echo json_encode($arr);

Try to use eval instead parseJSON
In js:
$(this).ajaxSubmit({
type : "POST",
url: '../index.php/user/signin', // target element(s) to be updated with server response
cache : false,
dataType:'json',
success : function(data){
data = $.trim(data);
alert(data);
var obj = eval('(' + data+ ')');
alert(obj.Condition);
},
error: function(){
}
I think also that it is not necessary to use $.trim to process response data

Try
url: <?=site_url('user/signin')?>,
If you are not posting anything you can simply use jquery getjson.
http://api.jquery.com/jQuery.getJSON/
It works fine.
check browser console, and tell me any errors are there.

Related

How to simply read html from any url via javascript and proxy?

This is my proxy.php file:
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though
and my reader.js:
$(document).ready(function () {
var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeURIComponent('http://www.blue-world.pl')
$.ajax({
url : url,
type : 'GET',
dataType : 'json'
}).done(function(data) {
console.log(data.results.result[1].category); // Do whatever you want here
});
});
But it doesnt print anything. Can you help me solve it? I am not quite good with this.
Currently your are trying to get JSON response. Change dataType to html.
dataType: 'html'
It looks like you are trying to get an HTML response as JSON.
If the content is HTML you should turn you ajax call to:
$.ajax({
url : url,
type : 'GET',
dataType : 'html'
}).done(function(data) {
console.log(data); // data contains the html as a text
});
Use either dataType: 'html' in reader.js (to get HTML data)
OR
echo(json_encode(file_get_contents($url))); in proxy.php (for JSON data)
Try jQuery.parseJSON for json format
$.ajax({
url : url,
type : 'GET',
dataType : 'json'
}).done(function(data) {
var data = jQuery.parseJSON(data);
console.log(data.results.result[1].category); // Do whatever you want here
});
});

Jquery get json data from data type dataString

I have the following jquery function which submits data to the database :
$('#book_client_form').submit(function (event) {
dataString = $("#book_client_form").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>operations/book_client",
data: dataString,
success: function (data) {
console.log(data);
$('.job_card_id').val(data[0].id);
$(".info_box_reload").show('slow');
setInterval(function () {
$(".add_new_client_div").hide('slow');
$(".clients_table_div").show('slow');
}, 3000);
}
});
event.preventDefault();
return false;
});
Once the data is supposed to returned the last insert id in json format which gives me the following output :
[{"id":"17"}]
But when I try to pass it to a text field or alert it , I get an undefined output or passes empty. Please advise on how can I pass it to the text input? I'm using datatype : datastring.
did you try parsing the JSON data?
data = JSON.parse(data);
console.log(data[0].id); // you can see the id in the dev console
$('.job_card_id').val(data[0].id);
or you can set dataType : 'jsonp' to get a JavaScript object as response
use dataType, its case sensitive.

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

how to create correct PHP json response

Hello i have a page can calla an ajax page in json with jquery.
i just set
dataType: "json"
in ajax call and i set header in php
header("Content-type: application/json; charset=utf-8");
but when i try read my response in a client i have this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var o = JSON.parse(jsonString);
For more information
PHP file function:
function _addToWishlist($v,$db){
$ris = array();
$data = array();
$data[0]=20;
$data[1]=25;
$data[2]=30;
$ris['stato']="1";
$ris['mex']="DA IMPLEMENTARE!!!";
$ris['data']=$data;
$ris['action']="";
ob_clean();
echo json_encode($ris);
}
and thi is a php response:
{"status":"success","stato":"1","mex":"DA IMPLEMENTARE!!!","data":[20,25,30],"action":""}
in client i use this javascript:
$.ajax({
url: "common/function/include/dataLoad.php",
type: "POST",
data: datas,
async:false,
//dataType: "text",
dataType: "json",
success: function(ris) {
// Run the code here that needs
// to access the data returned
//$(this).parent
//alert (ris);
risp=ris;
//var a = JSON.parse(ris);
tryParseJSON(ris);
//return ris;
},
error: function() {
alert('Errore di rete');
}
}).done(function(){
if(divwhere!=""){
$(divwhere).html(risp);
}
if(actionAfter!=""){
eval(actionAfter);
}
});
the function for test json is here: stackoverflow
how can i do for create a correct call json? thank you very much
jQuery will automatically parse a JSON response for you - you don't need to do it again. The returned ris object is ready for you to work with as-is. Assuming the request works, there is no problem with the format of your PHP response.
success: function(ris) {
console.log(ris.status); // = 'success'
console.log(ris.mex); // = 'DA IMPLEMENTARE!!!'
},

send multidimensional array to php using ajax as json and receive html text to show in a div

First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});

Categories

Resources