Could not receive AJAX POST data in PHP - javascript

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.

Related

Where do PHP echos go when you are posting to a page?

This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)

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

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

jQuery ajax fails to send one of multiple variables to php

I have this ajax send two variables to php, it sends the 2nd one trough fine but the first variable is always reported by php as NULL, i console log the javascript variable before sendign it and it does return an array of strings so I have no idea what is going on.
console.log(givenSpots);
jQuery.ajax({
type: "POST",
url: "includes/map/update.php",
data: {'spots': givenSpots, 'thisEvent': givenEvent},
dataType: "json",
cache: false,
async: false,
success: function(result){
response = result;
}
});
The receiving PHP is:
session_start();
if(isset($_SESSION["adminid"])){
$currentUser = $_SESSION["adminid"];
} else if(isset($_SESSION["vartotojasid"])){
$currentUser = $_SESSION["vartotojasid"];
} else $currentUser = false;
if ($currentUser) {
file_put_contents("update.txt", "0 ");
include_once "../../../../../../connection.php";
$event = $_POST["thisEvent"];
if (isset($_POST["spots"])) {
$data = $_POST["spots"];...
you need to encode your array to json before sending it to php, you can use
JSON.stringify(postDataArray)
or using jquery $.post :
$.post(yourURL, {
data : $.toJSON(postDataArray)
}, function(response){
//do something with your response
}
);
than just decode it with php and use it on your server

Using ajax to send a JS variable, but how can I use PHP variables afterwards to my main file?

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

Categories

Resources