Unable to pass string parameter to php function via ajax - javascript

I am making the following jquery ajax call to a codeigniter php function:
$.ajax({
type:"POST",
url: "Ajax/getHtml",
data: { u : 'http://stackoverflow.com/' },
contentType: "application/json; charset=utf-8",
dataType: 'html',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR,textStatus, errorThrown);
}
});
The requested php function is :
public function getHtml() {
var_dump($_POST);
$url = $_POST['u'];
$result = file_get_contents($url);
echo ($result);
}
var_dump($_POST) yields:
array(0) { }
How can I fix this?

Php will not populate the $_POST array if the content type of the request is application/json; charset=utf-8, also you aren't sending json. Just remove the content type line and the proper(default) content type of application/x-www-form-urlencoded will be set.

Related

JQuery UI Autocomplete Wordpress

I want to add autocompletion in a nickname search bar. I do not understand why it does not work. My code is correct ?
In my file liste.php
global $wpdb;
$name = $_POST['code_postal'];
$sql = $wpdb->get_results("SELECT * FROM membres WHERE pseudo LIKE '$name%' ");
$titles = array();
foreach($sql as $key=> $value){
echo $value->pseudo;
}
echo json_encode($titles); //encode into JSON format and output
In my global.js
$('#recherche').autocomplete({
source: function(name, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-content/themes/ARLIANE/liste.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
In my index.php
<form>
<input type="text" name="term" id="recherche"/>
</form>
You can try to log ajax errors to console for more informations about the problem , something like this :
$.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-content/themes/ARLIANE/liste.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
Try to change the URL in your js code by adding a page and to associate the file liste.php as a custom page Type and Than add the page URL :
url: '<?php echo get_permalink(page_id); ?>',
If I do a include of liset.php this returns me well a table json.
But when I make my ajax call it returns a Error 500.
I think the problem comes from the jquery call with the autocomplete function.

Ajax success and error function is not calling properly in jquery

I have used postman to send the json data to the specifified url.I am getting the requred response that is json in postman.I want to send this json to some other file so i used ajax post method.Ajax post method is not called.My function is not triggering success or error here.
<?php
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$value1=json_encode($input);
//echo print_r($value1,1);
?>
<script type="text/javascript">
$(document).ready(function() {
// alert("hello");
var jsondata = <?php echo $value1 ?>;
$.ajax({
url: "/restapi/subscribe.php",
type: "POST",
data: { jsondata:jsondata },
dataType: "json",
Content-Type: "application/json",
success: function() {
alert("data sent!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
</script>
I am sending any of the json data as input.Output also json data that should be posted in subscribe.php.In subscribe.php i have written
<?php
$json=$_POST['jsondata'];
echo $json;
?>
Try with below code
<script type="text/javascript">
$(document).ready(function() {
// alert("hello");
var jsondata = <?php echo $value1 ?>;
$.ajax({
url: "/restapi/subscribe.php",
type: "POST",
data: { jsondata:jsondata },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
alert("data sent!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
</script>
and let me know if it work
You should remove Content-Type: "application/json" from your js code and use next code in your php script:
header('Content-Type: application/json');
echo json_encode($data);
I think the problem is with Content-Type
Try to replace it with contentType:"application/json"
Try to replace Content-Type: "application/json" with contentType: "application/json; charset=utf-8",

How to make a generic ajax function for php file

I hope you can understand my question. I am trying to make a generic ajax function that will send some data to a php file and get the server's response. There is a very similar question here jquery - creating a generic ajax function , however I am having some troubles sending the data in a json format. Let me provide you the JS code:
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(parameters),
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
var pars = {
id:"1",
message:"hello world"
};
function onSuccess(data) {
console.log(data);
}
CallMethod('ajaxGeneric.php', pars, onSuccess);
And now here is my php file 'ajaxGeneric.php':
<?php
$id = $_POST["id"];
$msg = $_POST["message"];
echo $id;
echo $msg;
?>
When I run the page I have this error in the Chrome's console:
SyntaxError: Unexpected token < in JSON at position 0(…)
The php file seems also to have some problems trying to get the post values. What am I doing wrong? sending the data? getting the data back?
Any help will be greatly appreciated.
Try removing JSON.stringify and pass the parameters directly,So that your function will look like this
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: parameters,
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

send post data from js to php using ajax without type cast

I have object in javascript and I need send this object to php using ajax.
I can "just send" this object, but my problem is that I need send object value types exactly as they are and not everything as string: meaning NULL as NULL, boolean values as boolean and so on...
Trying this:
var js_object= <?php echo json_encode( array("a"=>NULL, "b"=>TRUE, "C"=>1.1) ); ?>;
$.ajax({
type: "POST",
url: "some.php",
dataType: "json",
data: JSON.stringify(js_object),
contentType: "application/json; charset=UTF-8",
success: function(msg){
}
});
but this does not sends data to server at all. and not gives any error also. where I am wrong ?
There is nothing wrong with your code.
I've just add a snippet with post query to httpbin.org:
$.ajax({
type: 'POST',
url: '//httpbin.org/post',
data: JSON.stringify({name: 'test', 'null': null, 'true': true}),
success: onSuccess,
error: onError,
dataType: 'json',
contentType: 'application/json; charset=UTF-8'
});
function onSuccess(data){
// data is parsed json response
console.log('Request copy:', data.json);
console.log('Full response', data);
}
function onError(xhr) {
console.log(xhr.status, xhr.responseText);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
Server side sample script:
<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);
header('Content-type: application/json');
echo json_encode($data);

php - return the value of an ajax post back to javascript

I'm trying to test the successful submission of data from javascript to a php file by having that php file return the results of the javascript post back to javascript. I'm getting a successful response in the ajax post, but the data is an empty string. How do I find out what data was posted? Here's my code:
JAVASCRIPT:
var benefitsArray = ["someData","someOtherData"];
$('#drop-submit').on('click',function(){
if (benefitsArray.length > 0){
var formData = { "benefits" : benefitsArray };
debugger;
$.ajax({
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
console.log(data); //result is "";
debugger;
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('failure');
}
});
}
});
PHP:
<?php
echo $_POST["benefits"]
?>
UPDATE:
I got a response by, in the php code, doing:
echo json_encode($_POST['benefits']);
but the problem is that in the javascript, if I log the data, the result is
"["someData","someOtherData"]" (a string)
and not
["someData","someOtherData"] (an array)
how do I get it to return an array and not a string?
You're not parsing the JSON being sent to you.
You can make jQuery do this for you by adding dataType: 'JSON' to your $.ajax options...
$.ajax({
dataType: 'JSON',
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR) ...
Or manually with JSON.parse:
success: function(data, textStatus, jqXHR) {
benefits = JSON.parse(data);
...
}

Categories