Send a JSON object to the controller Codeigniter - json

I had a problem. When I try to send my JSON data to the controller and try to use it there I just got an empty array. I checked the XHR and my post is not empty but somehow the controller doesn't like it. :)
In my view:
$.ajax({
type : "POST",
url : "http://www.domain.hu/bet/placebet/",
data : "{'places':'" + JSON.stringify(arr) + "'}",
contentType : "application/json; charset=utf-8",
dataType : "json",
success : function(msg) {
alert("Good");
},
fail : function(msg) {
alert("Bed");
}
});
And in my controller:
public function placebet() {
$places = $this->input->post('places');
echo json_encode(array('places'=>$places));
exit;
}
So far I got an empty record. Any ideas?

since you are sending through a JSON string, then accepting it in post, then re-encoding it that seems to me like it would cause an issue. Try json_decoding it as suggested or you might also try a
print_r(json_decode(array('places'=>$places));
since you are expecting an array back, print_r is the way to go.

Related

Problem with php handling ajax in the same file

I have a serious problem, I can't receive data sent by ajax in php. I've read many tutorial about that but it still not resolved. So if you guys have the magic solution, it'll make my day.
Here is the code, note that it is in the same file problem.php.
assocStored is an array or object, and it have the right data if I check it on jvascript
window.onload = function(e){
var assocStored = JSON.parse(localStorage.getItem("associes"));
$.ajax({
type : "POST",
data : {"problem" : assocStored},
success : function(res){
console.log("action performed successfully");
}
})
}
<div>
<h3>php</h3>
<?php
var_dump ($_POST);
if( isset($_POST['problem']) ){
foreach ($_POST['problem'] as $associe) {
echo($associe["sex"]." ".$associe["firstname"]." ".$associe["lastname"]);
}
exit;
}
?>
</div>
As my comment above, I guess your request send a GET method.
In your code, you are using type is POST but type is an alias for method. You should use type if you are using versions of jQuery prior to 1.9.0.
So you can modify your ajax to here:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
success : function(res){
console.log("action performed successfully");
}
})
If it continues not working, add this code to ajax:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
beforeSend: function(req) {
if (req && req.overrideMimeType) {
req.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success : function(res){
console.log("action performed successfully");
}
})
I hope it works.

ASP MVC Areas and JSON POST

I have a project with areas and would like to post a view model as JSON to a controller method.
This is what I have, with performance being generated in the default area and passed to the view in area SeatSelection:
$("#addToCartButton").click(function () {
var json = #Html.Raw(Json.Encode(performance));
$.ajax({
url: 'https://#(Request.Url.Host)/SeatSelection/Home/AddToCart',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
And the action method for testing:
[System.Web.Http.Route("SeatSelection_AddToCart")]
[System.Web.Http.HttpPost]
public JsonResult AddToCart(PerformanceViewModel performance)
{
return Json(performance.Name);
}
I created the following route:
context.MapRoute(
"SeatSelection_AddToCart",
"SeatSelection/Home/AddToCart",
new { action = "AddToCart", controller = "Home", id = UrlParameter.Optional },
namespaces: new string[] { "myProject.Areas.SeatSelection.Controllers" }
);
But all I get is a internal server error 500. I also tried to use [FromBody] and setting a breakpoint to the method, but it is not invoked. I can't figure out what's wrong or missing, please help.
UPDATE
This is the json / performance:
PerformanceID=00000000-0000-0000-0000-000000000000&Name=Performance+15&StartDate=%2FDate(1360364400000)%2F&EndDate=%2FDate(1500328800000)%2F&LatestDateBookable=%2FDate(1450911600000)%2F&Organizer=Organizer+15&Location=Location+15&Availability=75&IsFull=false&IsBookable=true&HasPrice=true&BookableSeats=11&BookedSeats=94&Description=Description+of+Performance+15&Price=443
I found an error: "invalid json primitive: performanceid"
First of all, I would recommend you to use #Url.Action helper method instead of generating url like this: https://#(Request.Url.Host)/SeatSelection/Home/AddToCart.
Secondly, always validate params which comes from the browser. return Json(performance.Name) looks suspicious. What is performance will be null? This might be a problem of your internal server error 500.
If this is not a problem then try to send string instead of JSON to the server and validate and parse JSON on the server side.
You can use Url.Action method like this. I suppose SeatSelection is an area in your project.
$.ajax({
url: '#Url.Action("AddToCart", "Home", new { Area = "SeatSelection"})',

Retrieving json data with jquery in html local file

i need help ! i want to retrieve json data from a Codeigniter server.
This is my html local file (d://myproject/index.html)
$.ajax({
type: "POST",
url : serverUrl+'mobcontroller/users/',
crossDomain: true,
async: false,
data : $("#formlogin").serialize(),
dataType : MobileJsonType[1],
beforeSend : function(){//do stuff here},
success : function(responseData) {
alert(JSON.stringify(responseData));
},
error : function(jqXHR, textStatus, errorThrown) {
// do stuff here
},
complete: function(xhr, settings){
alert(JSON.stringify(xhr)+'\n'+settings);
}
});
and codeigniter controller look like this
public function index()
{
$type_message = 'success';
$message = 'Mobile plateform';
$this->output->set_header("Access-Control-Allow-Origin: *");
$this->output->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
$this->output->set_status_header(200);
$this->output->set_content_type('application/json');
$this->output->_display();
echo json_encode( array('type_message' => $type_message, 'message' => $message) );
}
i obtain json data response with the js error
Uncaught SyntaxError: Unexpected token :
Please help me!
Change your success function to
success: function(data) {
console.log(data)
}
and let us know what the output is.
I'm unfamiliar with codeigniter but is it possible that $this->output->_display(); echos something which the JS is trying to parse? If you place
ob_clean();
above your
echo json_encode(...
it will clear the buffer which was going to be sent back to the JS, and that way only your encoded JSON will go back which the JS can parse.
You ajax request should be something like this.
$.ajax({
type: "POST",
url : serverUrl+'mobcontroller/users/',
crossDomain: true,
async: false,
data : $("#formlogin").serialize(),
beforeSend : function(){//do stuff here},
success : function(responseData) {
alert(JSON.stringify(responseData));
},
error : function(jqXHR, textStatus, errorThrown) {
// do stuff here
},
complete: function(xhr, settings){
alert(JSON.stringify(xhr)+'\n'+settings);
}
});
I have removed propertydata dataType : MobileJsonType[1]
Also you dont need to use JSON.stringify.
The returned result is already json due to php's json_encode
And the error you are facing is due to beforeSend because beforeSend first hits the server to check if the request is allowed or not. if it sends true the actual request will proceed otherwise you need to handle it yourself. I assume you need to send some token with serialized data. Hope it helps. if you remove property beforeSend the request will work fine i think.

How to read a Json file in jQuery

I'm using VS2012, and running an ASP.NET MVC4 project.
I cannot seem to get this to fire below :
$.ajax({
url: "~/xml/JsonTest.json",
type: "GET",
dataType: "json",
success: function (json) {
alert("HI");
}
});
I also tried it this way , but to no avail :
$.getJSON('../xml/JsonTest.json', function (json) {
alert("GET JSON !");
});
Is it somehow not finding the directory structure ?
thanks.
Bob
The first one definitely won't work, since ~ doesn't mean anything client-side. What actual URL is requested by the second example? Does it send an AJAX request at all? What is the response?
If you have a dynamic server-side URL then you'll want to use server-side code to dynamically build it in the rendered output. Something like this:
$.ajax({
url: '#Url.Content("~/xml/JsonTest.json")',
type: 'GET',
dataType: 'json',
success: function (json) {
alert("HI");
}
});
This would result in the client-side JavaScript being rendered with the full URL for the server-side path "~/xml/JsonTest.json".
Best solution for my case was to properly code it up in a C# method as follows :
public string getJsonParameters()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
string jsonStr = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/myKeys.json"));
JsonParameters jsonData = (JsonParameters)ser.Deserialize(jsonStr, typeof(JsonParameters));
return jsonStr;
}

how to set jsonp callback in retrieving restful web service data via jquery

I have asked a question regarding invalid label on firebug which happens when I try to retrieve data from my restful web service. Most of the answers I received was about setting a callback function. but I can't seem to get the right juice from it. can you show me an exact code on how to do it? or atleast correct the code here:
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
processdata:true,
jsonp: false, jsonpCallback: "success",
url: 'http://localhost:8732/Service1/data/10',
success : function success(data) {
jsonResponse = eval("(" + data + ")");
alert(jsonResponse)
},
error : function(req,status, ex) {
alert(ex);
}
Thanks,
Wow, you've got a lot of unnecessary stuff there. Try this:
$.ajax({
url: 'http://localhost:8732/Service1/data/10',
dataType: 'jsonp',
error: function(req, status, ex) {
// your code here
},
success: function(data) {
//your code here
// Please note: you don't need to 'eval' the json response.
// The 'data' variable will be loaded with the object that the json string represents.
// By the way, don't use 'eval', ever.
}
});
jQuery will take care of the callback on the url. See here: http://api.jquery.com/jQuery.ajax/
UPDATE
Why jsonp? If you're getting this from localhost, why not just json? As discussed in the comments below, your server currently is not capable of a jsonp response, but it can do json.