data is empty from ajax request in whcms - javascript

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 );
}
});

Related

How to retrieve data from node.js to Ajax?

I'm trying to learn sending/receiving data from Ajax to node.js. I am able to send the data from ajax but not able to receive. Not able to solve the problem. That'd be great if someone can explain where I'm going wrong.
Ajax
$(document).on('submit', '#searchdata', function (e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: location.pathname,
method: 'POST',
type: 'POST',
data: formData,
processData: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var ret = JSON.stringify(data);
console.log('Success: '+JSON.stringify(data))
},
error: function (xhr, status, error) {
console.log('Error: ' + JSON.stringify(error));
},
});
});
node.js
var myData = '';
request.on('data', function (data) {
myData += data.toString();
});
response.writeHead(200, {
'Content-Type': 'text/json',
'Access-Control-Allow-Origin' : '*'});
response.end(myData);
});
I see this statement in the jQuery Ajax documentation:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use
jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
I believe you will need to change the code similar to as mentioned above in the documentation.
Have you checked that the server/api you are posting to return a response (use postman)
Have you checked the headers for the request. You may need to add authorization headers(pretty common practice with public apis)
Have you appended a client_id, app_id or api_key onto the request
Have you authenticated your request (basically point 2/3)
2 and 3 should return a response, in either case, I would use postman to check. If postman should at the very least return a response. Check the headers and the http status header. If you are getting a 200 response, and no content back there is likely an issue with the route or server configuration
Ajax example
$(document).on('submit', '#searchdata', function (e) {
e.preventDefault();
//Get form by id
var $form = #("#form_id");
//Form data
var formData = new formData($form);
$.ajax({
url: 'http://localhost:300/edit/11', //path to api
method: 'POST', //Method to use (GET by default)
data: formData, //The data to be posted
dataType: 'json', //Expected reponse format
}).done(function(res){
//Results here can contain an error - this is common for custom error types
//Test for custom error assuming in the format res.error
if( typeof res.error == 'undefined'){
console.log(res)
}else{
//You have an error
}
}).fail(function(err){
console.log(err)
})

php sending values to ajax faild error

I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});

How to send a JS object with ajax

I have the following Jquery code that sends a ajax request to add-to-cart.php.
var productData = {
"product_id": s_product_id,
"product_opties": s_product_opties,
"product_aantal": s_product_aantal
}
productData = JSON.stringify(productData);
$.ajax({
url: 'inc/add-to-cart.php',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: productData,
type: 'POST',
success: function(response) {
alert(response.d);
},
error: function(e){
console.log(e);
}
});
Add-to-cart.php:
<?php
print $_POST['product_id'];
?>
I am having two problems, the first one is that the $_POST['product_id'] does not exists when i ask for it and secondly when the ajax response returns it goes directly to the error: function and not succes function
The console log says:
[object Object]{readyState: 4, responseText: "<br /> <b>N...", status: 200, statusText: "OK"}
If the status is OK why does it jump to the error: part?
Thanks!
Try with:
...
var productData = {
'product_id': s_product_id,
'product_opties': product_opties,
'product_aantal': product_aantal,
}
$.ajax({
url: 'inc/add-to-cart.php',
dataType: 'json',
data: productData,
type: 'POST',
success: function(response) {
console.log(response.d);
},
error: function(e){
console.log(e);
}
});
...
Omitting the AJAX contentType parameter and the part where you stringify your JSON, that's already ready to be sent to your url, so, isn't needed.
Remove the line
productData = JSON.stringify(productData);
Then do not return HTML <br> ... from add_to_cart.php, you need to return a JSON string created by the PHP function json_encode and NOTHING ELSE.
Like in:
<?php echo json_encode(array('d' => 'value of d'));
First: status Code from the Webserver is 200 cause he deliverd an existing site.
Second: You dont need to stringify the json object by urself

JavaScript, Ajax ,php parsererror, and How get post Json?

I got this code in game.php to refresh .refre, but I always get "parsererror". jsonString is from jsonString= JSON.stringify(object);
<div class="refre"></div>..
<script>...
jsonString ={"right":0,"arrayQ":[{"0":"10","idQ":"19"},
{"0":"34","idQ":"20"},{"0":"89","idQ":"14"}],"lives":40};
$.ajax({
type: 'POST',
data: jsonString,
dataType: 'json',
url: 'Q.php',
contentType : 'application/json; charset=utf-8'
}).done( function (data, status) {
$('.refre').load('Q.php');
alert('Right');
})
.fail( function (data, status) {
alert("Wrong: "+status);
});
...</script>
The other file is Q.php, this read the POST and send some HTML, Now It is just for check the information of the POST.
<?php
$value = json_decode($_POST);
$categories = json_decode(file_get_contents('php://input'));
print_r($value);
print_r($categories);
?>
What's wrong with the ajax?? how I get the POST in Q.php? how can I get 'lives' from the JSON in Q.php?
Try this,
<div class="refre"></div>..
<script>...
jsonString =[{"right":0,"arrayQ":[{"0":"10","idQ":"19"},
{"0":"34","idQ":"20"},{"0":"89","idQ":"14"}],"lives":40}];
$.ajax({
type: 'POST',
data: jsonString,
dataType: 'html',
url: 'Q.php',
contentType : 'application/json; charset=utf-8'
}).done( function (data, status) {
$('.refre').html(data);
alert('Right');
})
.fail( function (data, status) {
alert("Wrong: "+status);
});
...</script>
<?php
$value = json_decode($_POST);
$categories = json_decode(file_get_contents('php://input'));
print_r($value);
print_r($categories);
?>
What you call jsonString is not JSON, it is a javscript object.
When you pass an object to data of $.ajax , jQuery will form encode that data.
In php you would retrieve lives using $_POST['lives']. It is not being sent as JSON
Think of the keys in the object as name of a form input.
As for your output, you can only ever return one JSON string from server. The JSON must have one set of open/close braces so it can be turned into one array or object
<div class="refre"></div>
<script>
jsonString =[{"right":0,"arrayQ":[{"0":"10","idQ":"19"},{"0":"34","idQ":"20"},{"0":"89","idQ":"14"}],"lives":40}];
$.ajax({
type: 'POST',
data: jsonString,
url: 'Q.php',
}).done( function (data, status) {
$('.refre').html(data);
alert('Right');
})
.fail( function (data, status) {
alert("Wrong: "+status);
});
</script>
Q.php:
print_r($_POST);
This is OK. The 'data' will not be send as json. $_POST is an array in Q.php, you don't need to json_decode it.

AJAX post JSON data arrives empty

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

Categories

Resources