I searched in many questions but doesn't worked for me, I want to loop through a json object returned by a controller, let me show you the code:
MODEL
public function traer_pasajero($id){
$this->db->select('*');
$this->db->from('pasajeros');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
CONTROLLER
public function traer_pasajero(){
$pasajero = $this->pasajeros_model->traer_pasajero($this->input->post('id'));
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($pasajero));
return $pasajero;
}
JS
function modificarPasajero (id) {
$.ajax({
type: "POST",
url: "http://localhost/xxx/xxx/traer_pasajero",
data: {id: id},
dataType: "text",
cache:false,
success:
function(data){
$.each( data, function( key, value ) {
alert(value);
});
}
});
}
And I receive this error in firebug:
TypeError: invalid 'in' operand a
This is the json object that I see in firebug:
[{"id":"1","primer_nombre":"xxxx","segundo_nombre":"","primer_apellido":"xxxx","segundo_apellido":"","ci":"xxx","nacionalidad":"Uruguayo","fecha_nacimiento":"5/7/1910","vencimiento":"5/5/1910","asiento":"12","habitacion":"Sgl","levante":"","telefono":"","observaciones":"","id_envio":"2"}]
dataType should be "json" instead of "text", and try to console.log(data) before each loop.
try removing this statement
return $pasajero;
as it is overwriting your json..
you can simply return
return json_encode($pasajero);
and then try
also cahnge
datatype : "json"
now to iterate you can use eval(string) or JSON.parse(string). but note that eval is dangerous
var obj = eval("("+data+")");
or
var obj = parseJSON(data);
$.each( obj, function( key, value ) {
alert(value);
});
Related
I'm trying to pass an array through an AJAX call to the backend, the array gets pushed to the backend, but I'm getting the error "Trying to get property 'id' of non-object"
This is the
var items = [];
$("input:checkbox[name='refundcheck']:checked").each(function(){
let id = $(this).val();
let item = {
"id": id,
"quantity": $('#quantity'+id).val()
};
items.push(item);
});
$.ajax({
type: "GET",
url: '{{url("/")}}/products',
data: {items:items},
dataType: 'JSON',
beforeSend:function (){
//$("#loadingDiv").show();
} ,
success: function( msg ) {
}
});
This is the console log for that array
I've tried both of these possibilities
$productarraylist = $request->items;
foreach($productarraylist as $item){
$product= dbtable::find($item->id);
}
AND
foreach($productarraylist as $i=> $item){
$product= dbtable::find($item->id);
}
This is the var_dump result of the array in the backend.
I tried to JSON.decode the array on the backend, and it says I need to pass a string, not an object.
You are dealing with arrays and not objects, try this:
foreach($productarraylist as $item){
$product= dbtable::find($item['id']);
}
The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept
i have a controller action which is return a boolean result to the jquery.
[HttpGet]
public ActionResult IsVoucherValid(string voucherCode)
{
bool result = false;
var voucher = new VoucherCode(voucherCode);
if(voucher.Status==0)
{
result = true;
}
return Json(result);
}
and call this controller using ajax code
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
alert("success");
if (data) {
//if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
},
error:alert("error")
});
in the success of ajax the json result is true then want to work the css. but this is not working please help me.
result is a variable name that only exists in that action method. It will not be included in the JSON.
I'm pretty sure that your boolean value will be stored in data since you are only sending back a single value:
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
if (data) { //if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
}
});
If in doubt, do console.log(data) to see what it contains. You should at least be doing minimal debugging before you bring the question to us.
Also, as #Stephen Muecke points out below, if you are retrieving this data with GET, you need to use:
return Json(result, JsonRequestBehavior.AllowGet);
I have upgraded to jquery 1.10.2. I am using jquery migrate and I am having the warning message "jQuery.parseJSON requires a valid JSON string"
I have not understood how I can correct that. Can anyone help me out with the best solution of how I can remove the warning message
The javascript is as follows:
function Search() {
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "html",
url: "#Url.Action("Search")",
data: JSON.stringify({myModel: $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
In the Controller:
public PartialViewResult Search(myModel myModel)
{
return PartialView("SearchResult", myModel);
}
ParseErrorFromResponse:
Function ParseErrorFromResponse(responseText, defaultError)
{
var text = responseText.replace("<title>", "TitleStart");
var startIndex = text.indexOf("TitleStart");
var endIndex = text.indexOf("TitleEnd");
return (startIndex == -1 || endIndex == -1) ? defaultError : text.substring(startIndex + 10, endIndex);
}
You need to send your data as JSON.
Where you have data: $("#DateFrom").val(), replace it with data: JSON.stringify({$("#DateFrom").val()}).
EDIT: You may need to send it as JSON.stringify({(myModel: $("#DateFrom").val()}).
The error may be related to "" or false values that used to convert to null in versions of jQuery prior to 1.9.0 per THIS PAGE
Here it the relevant excerpt including the suggested solution:
JQMIGRATE: jQuery.parseJSON requires a valid JSON string
Cause: Before jQuery 1.9.0, the $.parseJSON() method allowed some
invalid JSON strings and returned null as a result without throwing an
error. This put it at odds with the JSON.parse() method. The two
methods are aligned as of 1.9.0 and values such as an empty string are
properly not considered valid by $.parseJSON().
Solution: If you want to consider values such as "" or false
successful and treat them as null, check for them before calling
$.parseJSON(). Since falsy values such as an empty string were
previously returned as a null without complaint, this code will
suffice in most cases:
var json = $.parseJSON(jsonString || "null");
If your own code is not
calling $.parseJSON() directly, it is probably using AJAX to retrieve
a JSON value from a server that is returning an empty string in the
content body rather than a valid JSON response such as null or {}. If
it isn't possible to correct the invalid JSON in the server response,
you can retrieve the response as text:
$.ajax({
url: "...",
dataType: "text",
success: function( text ) {
var json = text? $.parseJSON(text) : null;
...
}
});
Remove content-type attribute and do like this:
function Search() {
$.ajax({
cache: false,
url: "#Url.Action("Search","ControllerName")",
dataType:"html",
data:
{
myModel: $("#DateFrom").val()
},
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
and in action:
public PartialViewResult Search(string myModel)
{
return PartialView("SearchResult", myModel);
}
I think it's because you're missing double quotes around key myModel in line
...
data: JSON.stringify({myModel: $("#DateFrom").val()},
...
and not because of jquery version upgrade.try using
data: JSON.stringify({"myModel": $("#DateFrom").val()},
Try like this.. You have to return Json as result from your Search().
public JsonResult Search(myModel myModel)
{
return Json(result);
}
and also in you Script, try like this..
$.ajax({
type:"POST"
cache: false,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("Search","ControllerName")",
dataType: "json",
data: JSON.stringify({"myModel": $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
}
});
Also check $("#DateFrom").val() is having correct value and put an
alert(data)
in success and check the returned data.
I have updated the url.
I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>