Retrieve data using ajax from php - php

I have an ajax code which passes data to php and then retrieves data from php...
function updateDatabase(syncData){
$.ajax({
type : 'POST',
async: false,
url : 'php/syncData.php',
dataType : 'json',
data: {myData : syncData}, //i even used this "mydata"+syncData
success : function(result){
res = result;
},
error : function() {
res = false;
}
});
return res;
}
And here's my php code...
<?php
include("database.php");
if(isset($_GET['myData'])){
$data = $_GET['myData'];
$insert = "INSERT INTO `mydata` VALUES (NULL,'$data')";
mysql_query($insert);
$data = mysql_insert_id();
echo json_encode($data);
}
?>
Here's javascript function that pass/calls ajax...
<script>
var theData = "blahblah";
var alertData = updateDatabase(theData);
alert(alertData);
</script>
the problem is that when i use htmt/text as data type it alerts empty/blank output, but when i used json as data type it alerts false where i conclude it went to error function not to success... anyone knows what's the proper way to do this? or maybe i'm just missing something? Thanks!

Well, you're posting the data using jQuery, but you're looking for a $_GET value in the PHP. Fix that and see if it changes anything.
Edit: It should look like this:
...
if(isset($_POST['myData'])){
$data = $_POST['myData'];
...

Try to set content type in your PHP file:
header( 'Content-Type: application/json' );
Then echo your data:
echo json_encode( $data );
Then exit script:
exit;
Hope it helps!

Related

Ajax call to PHP action/function with array as data (in wordpress)

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

Trying to extract information throught a PHP file Undefined

I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

$.ajax call doesnt work with dataType:'json'

Please excuse me if this sounds stupid but I have been at it for quite some time now and cant figure out the problem.
so what I am trying to do is :
--Make a ajax call to a php script that queries mongodb collection for some documents
-- This ajax calls gets a json back and renders it on browser.
The problem I am having is at the first step itself.
here's my ajax call :
$.ajax({
type :'get',
url: "get_data.php",
dataType : 'json',
success: function(msg){
alert(msg);
}
});
here's the php code:
$n = new MongoClient();
$dbname = "wsd";
$db = $n->$dbname; //get the collections..
$collection = $db->raretweets;
$cursor = $collection->find();
header('Content-type: application/json');
echo json_encode($cursor);
I suspected the problem might be with the $cursor object , So I tried the following basic stuff
$data = 3;
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode($data);
Even this gives me an error "No element found" in console logs of firebug.
I was wondering if anybody can hint me about the problem.
What if you try something really basic, something like this:
$.get(url, function(data){
if(data!='Error') {
alert(data);
}
And in PHP
$data = 3;
if($data) {
echo number_format($data);
} else {
die('Error');
}
Does this give you a result?

Not getting json array in php

I am passing a json in my ajax request but it is just returning 10 every time, why??
whay my array in not getting passed??
Here is my code:
jQuery(document).ready(function($){
$('#list-3 .ajaxcall').click(function(){
$.ajax({
type : "GET",
url : ajaxurl,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data : {
gpl_args : JSON.stringify({"cat":"26","posts_per_page":"4","paged":1}),
gpl_layout : {"show_thumb":"1","columns":"4","thumb_height":"85","thumb_width":"85","title_link":"1","content_excerpt":"50","posts_per_page":"4"}
},
success : function(response) {
// The server has finished executing PHP and has returned something,
// so display it!
$("#list-3").append(response);
}
});
});
});
and:
$args = isset($_REQUEST['gpl_args']);
//$args = json_encode(isset($_REQUEST['gpl_args']));
print_r($args)
Update:
my data inside ajax:
data : { gpl_args : JSON.stringify(<?php echo json_encode($args); ?>),
JSON.stringify(gpl_layout : <?php echo json_encode($layout); ?>)},
Simple fix. You have to DE-code the json, not EN-code it.
$args = isset($_REQUEST['gpl_args']) ? $_REQUEST['gpl_args'] : null;
$args = json_decode(stripslashes($args));
print_r($args)
See your php script:
$args = isset($_REQUEST['gpl_args']);
//$args = json_encode(isset($_REQUEST['gpl_args']));
// $args is false(Boolean type), But not json
print_r($args); // print_r(false); is show nothing!!
right way:
$json_array[] = isset($_REQUEST['gpl_args']) ? $_REQUEST['gpl_args'] : false;
echo json_encode($json_array); // will show json string
Aren't you printing the boolean result of isset() instead of the actual args?

Categories