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.
Related
I'm trying to post to php using ajax.
I can't seem to figure why the data isn't been posted.
The console.log shows 'success'.
var obj shown is for check only.
the code:
var obj = {'age':'32'};
obj = JSON.stringify(obj);
$.ajax({
type: 'post',
data: {'phpobj': obj},
dataType: 'json',
success: function(data){
//do whatever.
console.log('success');
}
});
and the php (in the same url):
if (isset($_POST['phpobj'])) {
echo 'phpobj is POSTED:</br></br>';
$php_obj = $_POST['phpobj'];
$decoded = json_decode($php_obj, true);
var_dump($decoded);
} else {
echo 'phpobj Wasnt POSTED';
}
Thanks for helpers.
Please try replacing your code like this
JQUERY
$.ajax({
type: 'post',
data: {'age': 32},
dataType: 'json',
success: function(data){
//do whatever.
console.log('success');
}
});
PHP
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo 'REQUEST is POSTED:</br></br>';
$age= $_POST['age'];
var_dump($_POST);exit;
} else {
echo 'phpobj Wasnt POSTED';
}
Change the rest according to your requirements. Thanks
i encounterd the same problem before, i gave up using ajax to post.
you can use the jquery to create a form then let the user submit it to php.
I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)
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.
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.
I'm retrieving a json string as below with jquery ajax and displaying it on a xhtml page
{"pID":"T1","avBal":147765035.20,"accBalance":147713417.00}
I have the jquery written like this,
$.ajax({
type : "GET",
url : '../accData.xhtml',
dataType : "json",
async : true,
cache : false,
success: function(data) {
if(data!=null){
$("#accBalance").text(data.accBalance);
$("#avBal").text(data.avBal);
}
},
error : function() {
}
});
The issue here is it displays the "avBal" as 147765035.2 and "accBalance" as 147713417 without the zero's all the zero's at the end of the values are truncated automatically. Is it a limitation in jQuery or json or something else is wrong here?
please replace your script as below:
$.ajax({
type : "GET",
url : '../accData.xhtml',
dataType : "json",
async : true,
cache : false,
success: function(data) {
if(data!=null){
//chage is here...
$("#accBalance").text(parseFloat(data.accBalance).toFixed(2));
$("#avBal").text(parseFloat(data.avBal).toFixed(2));
}
},
error : function() {
}
});
Not jQuery's or JSON's fault, but JavaScript. JavaScript is loosely typed, and 123 & 1.23 are both of the type Number. If the precision is important, treat those values as strings.
Here is a nifty function that will format the values as required:
function toFixed(value, precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(value * power) / power);
}