The following script sends data with ajax for login
I want to format the data returned by using, in essence, a session variable ($ _SESSION)
I can do it
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "inc/login.inc.php",
data: "username="+username+"&password="+password,
success: function(msg){
if(msg!='false')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
//valori menù
if(tipo=='1')
{$("#admin").css('display','none')}
}
else
{
$("#add_err").html("Username o password errata");
}
},
beforeSend:function()
{
$("#add_err").html("<img hspace='84' src='img/loading.gif' alt='Loading...' width='32' height='32'>" )
}
});
return false;
});
especially this is possible, in this way would print the name of the user just logged. otherwise I would not know how to do
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
You can't insert PHP code after the script has already been processed.
Either pull it in via ajax, or include the actual PHP output into your javascript.
ie, in page.php
<script>
var sessionName = '<?php echo $_SESSION['name']; ?>';
</script>
then when you need it later
$("#profile").html(sessionName + " Logout k2");
JavaScript is client-side, it simply can't execute your php code.
You have to return something (eg. the username) in the php file you use in your ajax request and use that in your JS.
See the jQuery ajax docs for examples.
You'll need to serve the php code:
$("#profile").load("inc/login-header.inc.php");
login-header.inc.php
<?php
print($_SESSION['name'] . " <a href='inc/logout.inc.php' id='logout'>Logout k2</a>");
?>
The easiest way to send information back from the php script to the javascript, is by using the msg variable in
success: function(msg){
If you just want to send back one string, you just echo that one string in your php file and you will have its value in msg. If there are multiple variables you want to send back, you can package the result in a json object.
So assuming that everything you want to send back is contained in the php array named $output, you do a echo json_encode($output); at the end of your php script to get the whole thing in msg.
that won't work, as the PHP code is never processed.
In login.inc.php try something like this
<?php
if (!loginOK()){
echo "{login:false}";
} else {
echo "{login:true, name:'".$_SESSION['name']."'}";
}
and then on the client
success: function(msg){
if (msg.login){
// stuff
} else {
$("#profile").html(msg.name + $('<a>').attr('href', 'logout.php').html('logout'));
}
}
Related
I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.
I have the following extremely simple PHP tester:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<button id="button">send request</button>
<script>
$("#button").click(function(){
$.ajax({
type: "POST",
url: "ajaxTest.php",
data: {userresponse: "hi"},
success: function(data){
alert(data)
analyse()
}
})
})
var analyse = function () {
<?php
if(isset($_POST["userresponse"])){
$variable = $_POST["userresponse"];
switch($variable){
case "hi":
echo 'alert("' . $variable . '")';
break;
default:
echo 'alert("LOGIC")';
}
}
?>
}
</script>
What's supposed to happen is that when I click the button, it sends the data userresponse: "hi" to the server, and then PHP receives it and alerts the value (i.e. "hi")
However, despite the fact that the file paths are correct, the AJAX send is OK in XHR, the PHP does not receive the value of the data, and the alert(data) returns the entire HTML document.
What is going on and how do I fix this?
Remove analyze() and put your php code in external file called ajaxTest.php, your code works perfect just remove your php code fron analyze and request for external this is bad practice having both in same file(header problems).
Proof:
Im creating a validation form in Ajax and PHP. But i don't have a clue how i should get the value from PHP??
For example:
The validation form is in index.php And the page with the function is checkUser.php.
In checkUser i have a global file included with my classes initialized. The checkUser.php look like this:
<?php
$requser = false;
require "core/rules/glb.php";
$user->checkUser($_GET['username']);
The get function comes from the Ajax call i do in the index file. But how do i know that PHP said that the username already exist så that i can make a if statement and paus the script?
Im a beginner, thanks.
And sorry for my english
$.ajax({
type: "GET",
url: "user_add.php",
data: 'username='+$("#jusername").val()+'&email='+$("#jemail").val()+'&password='+$("#jpassword").val()+'&secureSession=23265s"',
success: function()
{
location.href='register.php';
}
});
Jus print out the data, for better help also post the ajax script
<?php
$requser = false;
require "core/rules/glb.php";
print $user->checkUser($_GET['username']);
If you are trying to give a response to the ajax call from php, then you can do it via normal output. Just like
echo json_encode(array("status"=>"FAIL"));
exit();
will send a json response to the ajax call from the php script. like
{"status":"FAIL"}
which you can parse it at the ajax callback and check the status. like
var data = JSON.parse(response);
if(data.status == "FAIL") {
alert("Ajax call returned failed");
}
I am very new to PHP and Javascript.
Now I am running a PHP Script by using but it redirect to another page.
the code is
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
How do I execute this code without redirecting to another page and get a popup of success and fail alert message.
My script code is -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
Thanks in advance.
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple link, like you have in the question. However I'm going to modify the structure a bit to keep it a bit cleaner:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
I'm assuming here that this code is a double-quoted string with interpolated variables.
JavaScript
Since you tagged jQuery... I'll use jQuery :)
The browser will listen for a click event on the link and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
As you can see, I'm using .data() to get the GET parameters.
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
PHP
Looks like you know what you're doing here. The important thing is to output the appropriate data type.
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
Instead of <a href>, use ajax to pass the values to your php and get the result back-
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});
i know this question was probably asked 1 million times, but for the 1.000.001 time :)
i need to call a php function from JavaScript. And i am having a bit of an argument on if ajax will do it.
i don't want to send any data just a ajax call that will call and run that function.
here is what i have so far:
$.post('functions/test.php', function() {
console.log("Hooray, it worked!");
});
is this gonna run the test.php ?
thanks
It definitely runs the test.php, to check it you may do sth. on succes
$.ajax({
type: "POST",
url: "ajax/test.php",
success: function(data) {
alert(data);
}
});
But what's the purpose of sending if no data is send?
Most likely, yes. I can't guarantee it because I don't do jQuery.
This, however, will definitely run it no problems (except versions of IE so old you shouldn't care about them):
var a = new XMLHttpRequest();
a.open("GET","functions/test.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
console.log("Hooray, it worked!");
// optionally, do stuff with a.responseText here
// a.responseText is the content the PHP file outputs, if any
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
Yes the test.php script will run, and you can grab the output from the test.php script like this (if you want to):
$.post('functions/test.php', function(data) {
//the `data` variable now stores the server response (whatever you output in `test.php`)
console.log("Hooray, it worked!");
});
In JQuery you can do:
$.post('functions/test.php', function(data) {
alert(data);
});
Whatever is returned in test.php will be put into the variable "data"
So you can do any php functions you need to in test.php and send the output back.
I always use
jQuery.ajax("url.php");