jQuery basic ajax GET + php return - javascript

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.

Related

unable to parse xml data with AJAX + Wordpress

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

Could not receive AJAX POST data in PHP

I'm trying to post a variable as an object to my PHP file, but it doesn't receive any data. I tried window.alert(u.un) to test whether the data is being passed from AJAX call, and it works fine and there are no errors in my console. But still I'm not getting data in PHP file, there are no errors either.
This is my AJAX function
function getfulldetails(n)
{
var u={un:n}; window.alert(u.un);
var locationto= "getfull.php";
$.ajax({
type: "POST",
url: locationto,
data: u,
processData: false,
contentType: false,
success: function(response)
{
window.alert(response);
}
});
return false;
}
This is my PHP file
<?php
session_start();
if($_SERVER['REQUEST_METHOD']==='POST')
{
if(isset($_REQUEST["un"]))
{
function validate_data($data)
{
require 'connectcred.php';
$data = trim($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = htmlspecialchars($data);
$data = mysqli_real_escape_string($conn,$data);
return $data;
}
$u=validate_data($_REQUEST["un"]);
echo $u;
}
else
{
echo "something's wrong";
}
}
?>
I'm getting result only from the else part.
I've used AJAX using the code below many times to get data from Form and it worked like a charm, but its not working when I assign an object myself.
Don't set Content-Type / contentType to false. You also need to send an actual query string.
For now, this should fix it:
$.post(locationto, u, (response) => {
window.alert(response);
});
Alternatively, use data: "un=" + n
Also, in your PHP, use only $_POST.

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 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