How to make a generic ajax function for php file - javascript

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

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.

PHP $_POST empty during AJAX post request

Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer)
Problem: PHP $_POST variable seems to be empty
JS/AJAX
var postData = [cmd, data];
alert(postData = JSON.stringify(postData));
$.ajax({
url: "./backendTag.php",
type: "post",
data: postData,
dataType: 'json',
success: function (response) {
alert(response); // Empty
//logToServerConsole(JSON.parse(response));
},
error: function(jqXHR, textStatus, errorThrown) {
logToServerConsole("E3"); // Communication Error
console.log(textStatus, errorThrown);
}
});
PHP
<?php echo json_encode($_POST);
The reason for the same is probably because you are not posting properly in javascript. Before i add the codes, let me add a couple of tips on how to debug in these situations.
First is, you check if the request is properly formed. Inspect the network in browser dev tools.
Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP
Now as far as the code goes
here is the javascript
$.ajax({
method: "POST",
url: "url.php",
data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
alert(msg);
});
and in php you can simply check using
<?php
print $_POST["name"];
?>
which would work perfectly. Notice how the data in javascript is a list, while from what you wrote seems to be json string
Apparently we can't pass an array directly after serializing him. The following code resolved the problem. (Split array)
data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};
$.ajax({
url: "./backendTag.php",
type: "post",
data: JSONata,
dataType: 'json',
/* Handlers hidden*/
});
JSON content won't be parsed to the $_POST globals. If you want to reach them, try to get from php://input with:
file_get_contents('php://input')
And I suggest giving the content-type during the ajax request:
contentType: 'application/json',
If it's not working, try to set the data as a string, with JSON.Stringify, like the following:
data: JSON.stringify(postData)

Unable to pass string parameter to php function via ajax

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.

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

Multiple AJAX calls with errors

I'm trying to make a generic function that allows me to get data from different sources at the same time.
I based my solution on this post, and ended up with this:
var servicesURL = 'http://www.somedomain.com/services/xml_proxy.php?url=';
function getExternalData(service, callback) {
$.ajax({
type: 'GET',
url: servicesURL+service,
dataType: 'jsonp',
jsonpCallback: 'myfunction',
success: function(data) { callback(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus+': '+errorThrown); }
});
}
getExternalData('data1.xml', function(data) {
console.log(data)
});
getExternalData('data2.xml', function(data) {
console.log(data)
});
Here's the code of the proxy I'm using:
<?php
header('Content-type: application/json');
$url = $_GET['url'];
echo 'myfunction('.json_encode(simplexml_load_file($url)).')';
?>
It works fine when I make a single call to the function, but when I make more that one call (as I did above), I get the following errors:
parsererror: Error: myfunction was not called
Uncaught TypeError: Property 'myfunction' of object [object Object] is not a function
Any help would be highly appreciated
Try putting the second call inside the callback of the first. That should fix the issues you are having.
http://forum.jquery.com/topic/multiple-jsonp-requests-causing-errors

Categories