In this script, data gets sent, but it does not send the updated value of the variable. Hard-coded data gets sent as expected. How can I solve this or go around it?
username = ''; // supposedly these variables are global
tree_name = ''; // I also tried plugging in- $('#username').data("username") -directly.. same results.
$(function() {
username = $('#username').data("username"); // updating value
tree_name = $('#tree_name').data("tree_name"); // idem....
});
var options = {
type: "POST",
url: "/decision/p_tree2/",
data: {
username: username, // this should send the data
tree_name: tree_nam // ...
},
success: function(response) {
console.log(response);
}
};
$("form").ajaxForm(options);
PHP:
public function p_tree2 (){
$data = Array();
$data['username'] = $_POST['username'];
$data['tree_name'] = $_POST['tree_name'];
echo print_r($data); // result: both $data['username'] and $data['tree_name'] equal ""
}
Reformat your code like following. Also correct the typo you have in tree_name in data. You used tree_nam.
$(function() {
var username, tree_name,options;
username = $('#username').data("username");
tree_name = $('#tree_name').data("tree_name");
console.log(username); //make sure
console.log(tree_name); // console outputs what you need to pass
options = {
type: "POST",
url: "/decision/p_tree2/",
data: {
username: username, // this should send the data
tree_name: tree_name // ***correct this typo***
},
success: function(response) {
console.log(response);
}
};
$("form").ajaxForm(options);
});
Related
php ajax auto login works well in form action, but is it possible to execute without form action?
$email = 'xxx#gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
console.log(email=' + user + ', password=' + pass);
$.ajax({
url: 'http://www.example.com/login',
type: 'POST',
data: JSON.stringify({ email: user, password: pass }),
success: function(data, status) {
// do something after login
console.log('success');
},
error: function() {
console.log('error');
}
});
return false;
</script>
You should use GET method instead.
$email = 'xxx#gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
$.ajax({
url: 'http://www.example.com/login',
type: 'GET', //send it through get method
data: {
email: user,
password: pass
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
</script>
Then check in your login page if email and password parameters have been set by GET or POST methods.
<?php
if (isset($_GET['email']) && isset($_GET['password']) || isset($_POST['email']) && isset($_POST['password'])){
// check your database and take actions.
}else{
// do nothing and show the post from again.
}
?>
Following code may work on page load if the username and password is auto-filled.
I hope this may help you.
<script>
$(document).ready(function(){
var user = $('[name="username"]').val();
var pass = $('[name="password"]').val();
if(user !== '' && pass!== ''){
$.ajax({
url: 'http://www.YourUrl.com/login',
type: 'POST',
data: {
email: user,
password: pass
},
success: function(response) {
//When successfully logged in
},
error: function() {
//If error on server side script
}
});
}
});
As here we have created POST request, you need to handle is by $_POST server side.
I'm to trying make a login using AJAX. AJAX function post data to PHP file but when I try to retrieve data from POST in PHP it's empty.
This is my AJAX posting code:
function validateUser() {
var userR = $("#fldUser").val();
var passwordR = $("#fldPassword").val();
if (userR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"> <b>A user is required.</b></p>");
} else if (passwordR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"><b>A password is required.</b></p>");
} else {
// alert(userR + passwordR)
$.ajax({
type: 'POST',
// url: '/_Controlador/_GSystemLogIn.php/',
url: '/_Controlador/_GSystemLogIn.php',
// data:'user=' + userR +'&password=' + passwordR,
data: {
'user': userR,
'password': passwordR
},
dataType: 'JSON',
beforeSend: function(xhr) {
alert("En before send: " + userR + passwordR);
},
success: function(data) {
alert(data);
if (data.message === "Success") {
// location.href = "main.php";
} else {
$("#divStatusText").html("<p class=\"text-danger\"><b>User or password is incorrect.</b></p>");
$("#fldUser").val("");
$("#fldPassword").val("");
}
},
error: function(data) {
alert("Error in AJAX call.");
}
});
}
}
PHP code retrieving data:
var_dump($_POST);
$user = $_POST['user'];
$password = $_POST['password'];
echo( "PHP user received: ". $user);
echo( "PHP pass received: ".$password);
Alert in AJAX beforeSend prints data correctly but var_dump($_POST) prints:
array(0) { }
I've also tried different ways to send data and URL. I'll really appreciate your help. Thank you!
You have to decode the data first.
Just do -
$_POST = json_decode(file_get_contents('php://input'), true);
Here's the full explanation - https://stackoverflow.com/a/39508364/5400741
In your ajax request,
type: 'POST' has to be method: 'POST'
Look at here
var username = $('#username').val();
var dataString = 'username=' + username;
$.ajax({
type: "POST",
url: "signinout.php",
data: dataString,
success: function() {
$('.user').html('<span>Welcome <span id="loggedUser">' + username + '</span>!</span> <a id="signOut" onclick="window.location.reload()">SIGN OUT</a>');
}
});
using the above code, my username variable is not being passed on correctly, I'm assuming something is wrong with the way I coding the datastring parameter but I'm not sure how to do it correctly.
Below is the php code that I am using in signinout.php to insert the username into the database, the username field is not being entered with each new entry into the database.
$username = protect($_POST['username']);
$time = time();
$sql = "INSERT INTO users
(username, join_date)
VALUES
('$username', '$time')";
$result = mysqli_query($cn, $sql) or
die(mysqli_error($cn));
Your "best" datastring depends on your needs in the server side part. As an example, this jquery-ajax call send a object to a server side action (PHP) :
var mydata = null;
mydata = "hellostring=1";
mydata = { title: "some" , value: "thing" };
mydata = [1,2,3];
$.ajax({
cache: false, type: 'post', async: true,
data: mydata,
url: 'some-script.php',
success: function(resp){
console.log("OK",resp);
},
error: function(e){
console.log(e.responseText);
}
});
As result, in your serve side you may have this script, which will return the same as you send:
// some-script.php
<?php
echo print_r($_POST,true);
?>
The outputs, for each kind of data (see the mydata variable) is:
Case: mydata = "hellostring=1";
Array( [hellostring] => "1" )
this mean, in serverside, you can:
$_123 = $_POST["hellostring"];
Case mydata = { title: "some" , value: "thing" };
As result, you get:
Array
(
[title] => some
[value] => thing
)
So you can:
$title = $_POST['title']; $value = $_POST['value'];
Case mydata = [1,2,3];
Surprise, this doesnt work, :) , you should wrap it, in this form:
mydata = { some : [1,2,3] }
So, you can proceed in your server-side the same as the previous case.
Note:
To avoid get hacked: (PHP CASE example) filter your input using:
http://php.net/manual/es/function.filter-input.php
More
In order to have a more advanced data handling in your server side part, (that is: in the script who receive the ajax request) , you can make usage of json, in this way:
Let start by supposing you are sending a object via javascript:
// in your client part,
mydata = { title: "some" , value: "thing", mydog: "sammy" };
..do your ajax call stuff here..
And, in your server side:
<?php
// some-script.php
$obj = json_decode(file_get_contents('php://input'));
echo $obj->title; // output: "some"
echo $obj->value; // output: "thing"
echo $obj->mydog; // output: "sammy"
?>
try passing it as a regular javascript object
var dataObj = {'username': username};
$.ajax({
type: "POST",
url: "signinout.php",
data: dataObj,
Try using data: "username="+username, instead
var username = $('#username').val();
$.ajax({
type: "POST",
url: "signinout.php",
data: "username=" + username,
success: function() {
$('.user').html('<span>Welcome <span id="loggedUser">' + username + '</span>!</span> <a id="signOut" onclick="window.location.reload()">SIGN OUT</a>');
}
});
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);
My jQuery autosave is running the success function, but not updating the MySQL database. What am I doing incorrectly?
jQuery:
function autosave() {
var t = setTimeout("autosave()", 5000);
var translation = $("#doc-translation").val();
if (translation.length > 0) {
$.ajax({
type: "POST",
url: "update-draft-submission.php",
data: translation,
cache: false,
success: function() {
$(".autosaved").empty().append("saved");
}
});
}
}
PHP:
<?php
session_start();
//retrieve our data
$iddoc = $_GET['iddoc'];
$trans = translation;
$transowner = $_SESSION['userid'];
$true = 1;
include "../dbconnect.php";
$query = "UPDATE translations
SET trans='$trans'
WHERE iddoc='$iddoc'
AND transowner='$transowner'";
mysqli_query($query);
mysqli_close();
echo "Saved";
?>
You are not fetching the data in your PHP correctly:
$iddoc = $_GET['iddoc'];
$trans = translation;
iddoc is not passed as a GET parameter anywhere
"translation" is not a variable (neither do I think it is a constant)
Your SQL will break if it does not get the required values in the query.
Update your javascript so:
$.ajax(
{
type: "POST",
url: "update-draft-submission.php",
data: data: {translation:translation,iddoc:"XXX"},
cache: false,
success: function()
{
$(".autosaved").empty().append("saved");
}
});
Replace XXX with your iddoc value.
Then in PHP fetch them as:
$iddoc = $_POST['iddoc'];
$trans = $_POST['translation'];