AJAX post JSON data arrives empty - javascript

This is my AJAX request
data = JSON.stringify(data);
url = base_url + "index.php/home/make_order";
//alert(url);
var request = $.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: data
});
request.done(function(response){
alert('success');
});
request.fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
My problem is that when it arrives to the PHP CI-controller $this->input->post('data'), it is empty.
This is my data: as shown before the AJAX request:
data = {"sum":"2.250","info":[{"id":"6","name":"bla","price":"1.000"}]}

First I'd like to thank all responses.
Actually it was a couple of mistakes,
First: as #bipen said, data must be sent as an object rather than a string. and when I tried it, it didn't work because I didn't put the single-quote around data
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: {'data': data}
});
Second: as #foxmulder said, contentType was misspelled, and should be ContentType
so the correct code is:
$.ajax({
url: url,
type: 'POST',
ContentType: 'application/json',
data: {'data': data}
}).done(function(response){
alert('success');
}).fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
and just FYI in case someone had issues with PHP fetching, this is how to do it:
$data = $this->input->post('data');
$data = json_decode($data);
$sum = $data->sum;
$info_obj = $data->info;
$item_qty = $info_obj[0]->quantity;

send your data as object and not string.. (not sure you have done that already unless we see you data's value.. if not then try it)
data = JSON.stringify(data);
url = base_url + "index.php/home/make_order";
//alert(url);
var request = $.ajax({
url : url,
type : 'POST',
contentType : 'application/json',
data : {data:data} //<------here
});
request.done(function(response){
alert('success');
});
request.fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
updated
if as of comments you data is
{"sum":"2.250","info":[{"id":"6","name":"bla","price":"1.000"}]}
then data:data is fine
var request = $.ajax({
url : url,
type : 'POST',
contentType : 'application/json',
data : data
});
bt you need to change your codeigniter codes to
$this->input->post('sum') // = 2.250
$this->input->post('info')

contentType should be capitalized (ContentType)
see this question

I have extended the CI_Input class to allow using json.
Place this in application/core/MY_input.php and you can use $this->input->post() as usually.
class MY_Input extends CI_Input {
public function __construct() {
parent::__construct();
}
public function post($index = NULL, $xss_clean = NULL){
if($xss_clean){
$json = json_decode($this->security->xss_clean($this->raw_input_stream), true);
} else {
$json = json_decode($this->raw_input_stream, true);
}
if($json){
if($index){
return $json[$index] ?? NULL;
}
return $json;
} else {
return parent::post($index, $xss_clean);
}
}
}
If you are using PHP5.x. Replace
return $json[$index] ?? NULL;
with
return isset($json[$index]) ? $json[$index] : NULL;

I'm not familiar with CodeIgniter, but I think you can try with global variable $_POST:
var_dump($_POST['data']);
If var_dump show data, may be $this->input... has problem

Related

Send multiple parameters to PHP (Ajax)

I'm stuck here when passing or sending multiple parameters on Ajax. It only works when I pass one. Here the Ajax code:
$.ajax({
type: "POST",
url: "dataCartas.php",
data: {valorXY: valorXY,
CentroX: CentroX},
success: function(msg){
// return value stored in msg variable
console.log(valorXY + CentroX)
}
});
And the PHP code:
$valorXY = $_POST['valorXY'];
$CentroX = $_POST['CentroX'];
include "configX.php";
if ($conn){
$sql="EXEC sp_InsertaComID #ComID = '".$valorXY."', #DR =
'".$CentroX."'";
if ($rs=sqlsrv_query($conn,$sql)){
}else{
echo (print_r(sqlsrv_errors(), true));
}
}else{
die(print_r(sqlsrv_errors(), true));
}
Sorry for my bad english :(
You can serialize a form
$.ajax({
type: 'post',
url: 'include/ajax.php',
data: $('#form').serialize(),
success: function (response) {
// do something
},
error: function(jqxhr,textStatus,errorThrown){
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
}
});
you can also use form data https://stackoverflow.com/a/8244082/3063429

data is empty from ajax request in whcms

I am trying to send a post request using ajax in whcms, but it seems that the data from the ajax request is null.
This is the ajax request:
function send_request(ticket_or_credit){
if(ticket_or_credit == 'ticket'){
var url = $("#ticket_action").val();
var ticket = $("#ticket_ticket").val();
var solution = $("#ticket_solution").val();
whmcs_data={ request_type:ticket, solution:solution };
jQuery.ajax({
type: 'POST',
url: url,
data: JSON.stringify(whmcs_data),
contentType:"application/json; charset=utf-8",
dataType: 'json',
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});
}
}
and in my php file:
$json = array("result" => "success", "message" => "Method is post", "data" => $_POST);
echo json_encode($json);
The $_POST is null.
Please help me, I haven't solve this problem for how many days :(
I removed the contentType and dataType of the ajax code just to make it default application/x-www-form-urlencoded; charset=UTF-8') and properly serialized whmcs_data variable. The output of your JSON.stringify is not properly serialized so I manually serialized it. for more information on ajax go to this : http://api.jquery.com/jquery.ajax/ and for JSON.stringify - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
try to replace variable whmcs_data declaration and ajax code with this:
whmcs_data = {
"request_type": ticket,
"solution": solution
};
$.ajax({
type: 'POST',
url: url,
data: whmcs_data,
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});

Fake path Javascript Issue

When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp

JavaScript POST falls when connect to MVC controller

I'm new in MVC and trying to create a site for training.
I need to call a POST method in my controller through JavaScript.
This is my JavaScript method:
function ActivateAddStarAndRoleWithCategories(sender, args) {
var discID = $('#DiscID').val();
var starID = $('#StarID').val();
var desc = $("#Description").val();
var strID = "";
$(':checkbox').each(function () {
strID += this.checked ? this.id + "," : "";
});
strID = strID.substr(0, strID.length - 1);
$.ajax({
type: "POST",
url: 'CreateCategoriesID',
contentType: "application/json; charset=utf-8",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
},
dataType: "json",
success: function () { alert("success!"); },
error: function () { alert("Fail!"); }
});
}
And this is my method in the controller:
[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);
return Json("OK", JsonRequestBehavior.AllowGet);
}
The view that activates the JavaScript function is already connected to the controller.
I always get error 500 - the server responded with a status of 500.
What am I doing wrong?
Thank you in advance!
I would go with the examples from the jQuery docs.
Did you try something like...?
$.ajax({
method: "POST",
url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
// This contentType is the default, so we can just ignore it
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
// I would also ignore the dataType unless your backend explicitly sends a JSON response header
//dataType: "json",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
}
}).done(function(msg) {
alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
alert('Failed with status: ' + textStatus);
});

Post JSON data along with id in Jquery AJAX

I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}

Categories

Resources