AJAX take data from POST with PHP - javascript

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

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Calling a php function from Javascript and using a javascript var in the php code

JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !

Header wont redirect when passedthrough ajax

Not sure if this is possible but I have a page that submits a form with AJAX and if it meets certain conditions it should automatically take the user to another page. NOTHING is outputted before the header tag its just a bunch of conditions.
Problem: Header redirect not working...
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
header("Location: http://localhost/manage/card.php?id=$id");
Headers can only be modified before any body is sent to the browser (hence the names header/body). Since you have AJAX sent to the browser, you can't modify the headers any more. However, you can have the add.php script called via AJAX return the $id parameter. Then that parameter can be used in JavaScript to redirect the page: window.location = 'http://localhost/manage/card.php?id=' + id.
More info on PHP header(): http://www.php.net/manual/en/function.header.php
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
window.location = 'http://localhost/manage/card.php?id=' + data;
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
echo $id;
exit;
You indicate in the question that under certain conditions, you want a redirect.
To do that, you would want to alter your javascript to contain an if condition, and to watch for certain responses.
I would recommend modifying your responses to be json, so that you can pass back different information (such as a success status, as well as a redirect url, or other information you might want).
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
var response = $.parseJSON(data);
if (response.redirect) {
window.location = response.redirect_url;
} else {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
}
});
});
As for your add.php file, you'll want to change this to be something more like so:
$json = array(
'redirect' => 0,
'url' => '',
}
if (...condition for redirect...) {
$row = mysqli_fetch_array($result);
$id = $row['id'];
$json['redirect'] = 1;
$json['redirect_url'] = "Location: http://localhost/manage/card.php?id=$id";
}
echo json_encode($json);
die();
You seem to have a miss understanding of how AJAX works. Introduction to Ajax.
The reason why your redirect appears not to working is because an Ajax call doesn't directly affect your browser. It's a behind the scenes call.
To get the data out from the AJAX call you need to do something with the returned data.
success: function (data) {
$("input").val('Company Name');
$("form").hide();
//You need to do something with data here.
$("#myDiv").html(data); //This would update a div with the id myDiv with the response from the ajax call.
getInfo();
}

Categories

Resources