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
Related
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);
}
I have written Jquery Ajax call but i got Parsererror.. in following js code i have checked which select element is changed in dynamic_slct. and i have checked generic or Company and then call GnrtTemp() with pass selected Element value.. if I select generic my follwing Code(function GnrtTemp and ajax call) is working.. if i select company i got Error parsererror.. my doubt is same ajax call working Generic and is not working as company.. what is the problem? How to fix that problem i have attached my js code and also PHP code .. If i did any mistake pls correct me.. suggest to solution.?
JS
$('#dynmic_slct').on("change", "#master ,select[name='company'], select[name='generic']", function(element){
if(element.target.name == 'generic' || element.target.name == 'company') {
GnrtTemp(element.target.value);
}
});
function GnrtTemp(id){
$.ajax({
method: "POST",
url: "ajaxRequest.php",
dataType: "JSON",
data: {fn: "getTemp", id: id},
success: function(reqResult){},
complete: function (jqXHR, textStatus) {
alert(textStatus);
}
});
}
ajaxRequest.php
<?php
$finalRes = array();
if($_POST['fn'] == 'getTemp'){
$template_src = getTemp($_POST['id']);
$finalRes['result'] = $template_src;
echo json_encode($finalRes);
}
function getTemp($id){
$db = new DB();
$Query = "SELECT template_src
FROM master
WHERE refid =$id";
$qryRes = $db->query($Query);
return $qryRes;
}
?>
My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;
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).
How can I use some PHP variables from the ajax-send.php to the index.php file? I use AJAX as shown below. Do I have to replace AJAX with something else?
index.php
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
}
});
ajax-send.php
$token = $_POST['one'];
echo "ok"
$toINDEX = "use this in index.php"
Try this
Ajax
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
var response = data;
//alert(data);To see what you have received from the server
}
});
PHP
if(isset($_POST['one'])){
$token = $_POST['one'];
echo "ok";
$toINDEX = "use this in index.php";
die();
}
In PHP just echo variable or json_encode array. In JS do the following:
var result = $.ajax({
url: this.fileUrl,
type: "POST",
data: data,
async: false,
dataType: 'json'
}).responseText;
Your vaiable is fully accessable.
take the variables in php sessions
//On page 1(ajax-send.php)
session_start();
$_SESSION['token'] = $_POST['one'];
//On page 2(index.php)
session_start();
$var_value = $_SESSION['token'];
You can simply echo the variable and then access it via javascript inside the success function.
But a better approach would be to json_encode the data. The beauty of this is that it will help you to pass multiple values/variables in a single echo. So
PHP
.
..
if(<all is okay>)
{
$toINDEX = "use this in index.php"
$data['result'] = 'ok';
$data['msg'] = $toINDEX;
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
Javascript
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
dataType:'json',
success: function(data) {
if(data.result == 'ok')
{
console.log(data.msg);
console.log(data.some_other_value);
}
else
{
// something went wrong
}
}
});
The important thing to note here is dataType:'json' which tells the function to expect the returned data in json format.
EDIT:
As per you comment, you could do this
$toINDEX = "use this in index.php";
// now use the variable here itself
mysql_query("SELECT * FROM table WHERE column = '$toINDEX'");
.
.
if(<all is okay>)
{
$data['result'] = 'ok';
$data['msg'] = 'anything you would like to show the user';
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);