unable to parse xml data with AJAX + Wordpress - javascript

Ok, I am officially stumped. I have been trying to find why my calls for specific items in a PubMed xml data file are not working... I can execute this one with my current coding:
$test = (string)$id_json->PubmedArticle->MedlineCitation->PMID;
but if I try to get a variable that is in a deeper array, it does not return a value. I have even tested with console.log(data) and I get my PMID returning but not my other, deeper values in the XML file. For example;
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
returns nothing for data in console.log(data)
Here is my function in wordpress:
function get_abstract(){
$id = $_POST['abstractid'];
$pubmed_api_call = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id='.$id;
$id_wpget = wp_remote_get($pubmed_api_call, array('timeout' => 20));
if( is_wp_error( $id_wpget ) ) {
echo "Error Contacting PubMed, please refresh page and try again";
die();
}
$id_xml = wp_remote_retrieve_body($id_wpget);
$id_json = simplexml_load_string($id_xml);
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
if($test === ""){
echo "NOTHING";
die();
}
echo $test;
die();
}
and here is my javascript AJAX call:
jQuery(document).ready(function() {
jQuery('.reference_header').click(function(e) {
jQuery(this).find("i").toggleClass("arrow-down arrow-up");
jQuery(this).nextUntil('.reference_header').slideToggle('fast');
var abstractid = jQuery(this).data("id");
e.preventDefault();
jQuery.ajax({
url: get_abstract.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
abstractid: jQuery(this).data("id"),
action: 'get_abstract'
},
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data);
console.log(data);
}
});
});
});
I cannot find out why it doesnt work... any help is greatly appreciated.

So I figured out the solution to the issue... you need to pass the string text as a json object to AJAX for it to read properly...
working code:
PHP:
echo json_encode(array("result" => "$test"));
die();
AJAX:
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data.result);
console.log(data.result);
}

Related

Delete post using $.ajax

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID
<button type="button" onclick="submitdata();">Delete</button>
When click this button then following $.ajax process running.
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:datastring,
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
And delete.php is
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_GET['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
This code not working post not deleted. Please how do I do?
You likely want to not only match the "GET" you use in your PHP but also add the ID to the button
<button class="del" type="button"
data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>
using $.get which matches your PHP OR use $.ajax({ "type":"DELETE"
$(function() {
$(".del").on("click", function() {
$.get("delete.php",{"post_id":$(this).data("id")},
function(html) {
alert(html);
}
);
});
});
NOTE: Please clean the var
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Using ajax DELETE with error handling
$(function() {
$(".del").on("click", function() {
$.ajax({
url: "delete.php",
method: "DELETE", // use "GET" if server does not handle DELETE
data: { "post_id": $(this).data("id") },
dataType: "html"
}).done(function( msg ) {
$( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
In the PHP you can do
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_REQUEST["post_id"] ....
}
since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET
here is how it sould be
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_POST['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
for the JS code
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:{"post_id":post_id},
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
here i've supposed thqt the give you the real id post you're looking for !!
The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request
Change:
type:"POST",
url:"delete.php",
data:datastring,
to
type:"DELETE",
url:"delete.php?" + datastring,
in PHP
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
$id = $_REQUEST["post_id"];
// perform delete
}
DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.
Follow #roberts advise and also:
You should have a way to handle errors eg.
to your ajax code add this:
error:function(e){
alert(e.statusText)// if you like alerts
console.log(e.statusText)// If you like console
}
You should also check your error logs. Assuming you use apache2 and linux
execute this in terminal:
tail -f /var/log/apache2/error.log
This gives you a very elaborate way to code. You also eliminate the problem of trial and error.

Script return blank just in jQuery AJAX

I've got very frustrating problem. I send AJAX request to PHP file and when I see Chrome Network Tools, it donť return any JSON. But when I try post the same data via POSTMAN tool in Chrome, it return right. When I open script normally, it return right. Just when I sen request via AJAXm it return nothing.
This is my PHP file: (I know it's functionally useless at this time, i need fix this error before it can do what I need)
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
echo $json;
At line 3 must be problem, because when I put it out, it works. But function is 100% exist, 'cause when i put nonsense name of function, it write an error. DB query is also right, i tried it in phpMyAdmin console.
This is my AJAX request:
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if(vysledek.stav===1){
window.location.href("../index.php")
}
else if(vysledek.stav===2){
alertify.error('Špatné uživatelské jméno');
}
else if(vysledek.stav===3){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
How I wrote, if I open PHP file in browser, it echo {"stav":2}, when I try POSTman, it echo {"stav":2}. But when I run AJAX request, it makes nothing. I really don't know what is wrong.
EDIT
Firebug:
Here
can you please try with the following code
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if( parseInt(vysledek.stav) == 1 ){
window.location.href("../index.php")
}
else if( parseInt(vysledek.stav) == 2 ){
alertify.error('Špatné uživatelské jméno');
}
else if( parseInt(vysledek.stav) == 3 ){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
<?php
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
print_r($json);
?>
Remember to parse JSON to the response
...
success: function (vysledek){
var vysledek = (vysledek);
if(vysledek.stav === 1){
window.location.href("../index.php")
}
...

jQuery basic ajax GET + php return

EDIT: fixed _ typo (2x), added header, still logging 100.
Upon clicking a button in my JavaScript, I'm firing this function (parameter: 100)
ajaxManager = new AjaxManager();
ajaxManager.requestHexContent(100);
function AjaxManager (){
this.requestHexContent = function(id){
$.ajax({
type : 'get',
url : 'simulator/hexFiller.php',
dataType : 'json',
data: {
gameid: id,
},
success : function(ret){
console.log(ret);
},
error : function(){
alert("error")
}
});
},
}
this is my hexFiller.php
<?php
header('Content-Type: application/json');
$ret;
if (isset($_GET["gameid"])){
if ($_GET["gameid"] == 100){
$ret = 200;
}
else {
$ret = "error";
}
}
echo json_encode($ret);
?>
Now, what i would expect to happen is for my browser to log "200" to the console, or, "error".
Instead it logs "100" to the console.
Can someone explain to me the fundamental error in my thinking?
As discussed in the comment, working code is mentioned below:
I only replaced $GET with $_GET.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function AjaxManager() {
this.requestHexContent = function (id) {
$.ajax({
type: 'get',
url: 'simulator/hexFiller.php',
dataType: 'json',
data: {
gameid: id,
},
success: function (ret) {
console.log(ret);
},
error: function () {
alert("error")
}
});
}
}
ajaxManager = new AjaxManager();
ajaxManager.requestHexContent(100);
</script>
hexFiller.php
<?php
$ret;
if (isset($_GET["gameid"])) {
if ($_GET["gameid"] == 100) {
$ret = 200;
} else {
$ret = "error";
}
}
echo json_encode($ret);
?>
You have a slight error in your PHP code. You're trying to use $GET[] to get parameters passed to the PHP script. But, it's $_GET[] that you need to use. See http://php.net/manual/en/reserved.variables.get.php.
You are not returning a json element from your PHP file.
Add header('Content-Type: application/json'); at the top of your PHP file.
Also your $_GET declaration is incorrect.
Why it is returning 100, I don't really know, probably an error number. But your PHP code is wrong, it's $_GET not $GET.

Jquery Ajax get not passing values

This is driving me crazy...
$(document).on("click",".load",function(b){
b.preventDefault();
$.get("/url/get.php",{
id: 123
},
function(a){
$("#result").html(a);
})
});
This loads the page as expected but when I do print_r($_GET) it shows it's empty...
Any ideas?
Backend:
if (isset($user) == false) {
session_start();
$path_to_root = "../";
require($path_to_root."require/loads.php");
$PDO = new PDO(DB_CONN, DB_USERNAME, DB_PASSWORD);
$user = new User($PDO);
}
$i = 0;
print_r($_GET);
Please, try this way, using done() function:
$(document).on("click",".load",function(b){
b.preventDefault();
$.get("/url/get.php",{
id: 123
}).done(
function(a){
$("#result").html(a);
})
});
As said in jquery docs that´s the way to send payload data with GET.
Anyway, you can also use ajax:
$.ajax({
url: "/url/get.php",
type: "get", //send it through get method
data:{id:123},
success: function(response) {
$("#result").html(a);
},
error: function(xhr) {
$("#result").html("ERROR");
}
});
Anyway, if you are still viewing those errors, the problem souhld be in your backend as #AmmarCSE commented.
Hope it helps
EDIT some text about the difference between jquery methods success() and done() :
jQuery ajax success callback function definition
please try this
$(document).on("click",".load",function(b){
b.preventDefault();
$.ajax({
method:'get',
url : '/url/get.php',
data : '{id:123}',
dataType: 'json', //json,html any you will return from backend
success:function(a){
$("#result").html(a);
}
})
});
Try using
$data = file_get_contents("php://input");
$r = json_decode($data);
instead of $_GET in you php file, then print $r

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Categories

Resources