Retrieving json data with jquery in html local file - html

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.

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.

Send a JSON object to the controller Codeigniter

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.

Crossdomain request

I try to load static html pages from another server.I make crossdomain request.
$(document).ready(function (){
$("div[src]").each(function(){
var staticFileURL = $(this).attr('src');
$.ajax({
url: staticFileURL,
dataType: 'jsonp',
data: {},
error: function(xhr, status, error) {
alert(error);
},
success: function() {
alert("success");
},
jsonp: false,
jsonpCallback: 'jsonpCallback'
});
});
});
But I got in chrome error "SyntaxError:Unexpected token <".
In FF "SyntaxError:Invalid xml attribute value".
What's wrong.Could somebody help me?
JSONP is to get json data from the server, it looks like you are trying to received HTML data.
Try to put your HTML data inside JSON object on the server and then read that HTML on the success callback:
for example, your json data from the server:
{ html: "<html><head>...</head></html>" }
also, your success callback should look like:
success: function(**data**){
}

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.

How to read JSON string in servlet

This question seems to have the answer to what I am trying to do, but it does not seem to work for me. The servlet posts fine and in the watch window I can see my json object there for the _parameters member variable of the servlet HttpRequest, but I can't seem to get the parameter out.
Here is my code.
Javascript:
// build data from input fields
var jsondata = '{"author":"TEST", "title":"XYZ"}';
$.ajax({
type : 'POST',
dataType : 'json',
data: jsondata,
url : '/submitquote',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
Servlet (I also tried with "author" and "title" but nothing comes back):
// get data
String postData = req.getParameter("jsondata");
This is what I see using variable watch for _parameters on the request object:
{{"author":"TEST", "title":"XYZ"}=}
How the heck do I get that stuff out?
Any help appreciated!
First, the datatype argument specifies the type of the data coming out, not the data going in.
Second, the data argument should give a dictionary of parameters, and one of the parameters in this case is the already-stringified JSON object:
var jsondata = {"author":"TEST", "title":"XYZ"};
$.ajax({
type : 'POST',
dataType : 'json',
data: { jsondata : JSON.stringify(jsondata)},
url : '/submitquote',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
Now, req.getParameter("jsondata") has the (still-JSON-stringified) data and you need to parse it yourself. JSON.org makes a very nice library you can use.
Two further notes:
There are two "jsondata" here. First is the JavaScript variable, assigned in the first line and used inside the stringify call; second is the Ajax parameter name, specified right after data: { and used in the getParameter call.
If you are really just passing "author" and "title", you can forget all about JSON and just use your original Javascript plus req.getParameter("author") and req.getParameter("title").