PHPSESSID= not carried in ajax jquery - javascript

I'm trying to use $.ajax (jquery) to make an api call to my server (php). I'm successfully pinging the server, however, it's not validating that the user is logged in ( which is stored in PHPSESSID). This is a cross-domain request.
When I use PHP to make the api call from the front end, it works because the cURL request assigns the PHPSESSID to the CURLOPT_COOKIE.
Here is the $.ajax code on my site, www.foo.com
$(document).on('click','#pickup_now', function(){
//testing ajax function for 'cpr.php'
$.ajax({
url: "https://app.foo.com/CPR.php",
data: {
PickupLatitude: PickupLatitude,
PickupLongitude: PickupLongitude,
PickupAddress: PickupAddress,
PickupAddress2: '',
PickupCity: PickupCity,
PickupState: PickupState,
PickupZipCode: PickupZipCode,
DropOffLatitude: '34.0335328',
DropOffLongitude: '-118.48099309999998',
DropOffAddress: '2227 Wilshire Boulevard',
DropOffAddress2: '',
DropOffCity: 'Santa Monica',
DropOffState: '5',
DropOffZipCode: '90403',
ShipmentDescription: document.getElementById('description').value,
ShipmentImage: document.getElementById('ShipmentImage').value,
EstimatedTime: '180',
EstimatedDistance: '1'
},
type: "POST",
success: function(data,status){
console.log("Data: " + data + "\nStatus: " + status);
console.log(userSession);
} //ends success function
});
});
It's returning:
Data: {"LoginValid":false}
Status: success
So we know it's successfully pinging the server. Here is the code on https://app.foo.com/CPR.php
public static function CPR($pickupLatitude, $pickupLongitude, $pickupAddress, $pickupAddress2, $pickupCity, $pickupState, $pickupZipCode,
$dropOffLatitude, $dropOffLongitude, $dropOffAddress, $dropOffAddress2, $dropOffCity, $dropOffState, $dropOffZipCode,
$shipmentDescription, $shipmentImage, $estimatedTime, $estimatedDistance)
{
$results = new fooCommon\Results();
if ($results->LoginValid = SessionInfo::GetInstance()->LoggedIn())
$results->AddMembers(fooCommon\SHELPER::CPR(SessionInfo::GetInstance()->UserID(), $pickupLatitude, $pickupLongitude, $pickupAddress, $pickupAddress2, $pickupCity, $pickupState, $pickupZipCode,
$dropOffLatitude, $dropOffLongitude, $dropOffAddress, $dropOffAddress2, $dropOffCity, $dropOffState, $dropOffZipCode,
$shipmentDescription, $shipmentImage, $estimatedTime, $estimatedDistance));
return $results;
}
The $results->LoginValid = SessionInfo::GetInstance()->LoggedIn() uses the users SESSION info to validate that they are logged in and grabs their information as well.
Here is that code, found on SessionInfo.php
public function LoggedIn()
{
if (!isset($_SESSION["LoggedIn"]))
$this->SetLoggedIn(false);
return $_SESSION["LoggedIn"];
}
How can I pass that PHPSESSID information properly so that the SessionInfo::GetInstance()->LoggedIn() knows to grab it and validate the user info?
TL;DR -> Is there a $.ajax equivalent to cURLs CURLOPT_COOKIE? That seems to be what's bringing that information over through the proper channel when doing this through a cURL.
Thanks in advance everyone!

When the page renders, embed the session ID in a hidden input element, i.e.
<input type=hidden name=sessionid value='<? inject here ?>'/>
When you make your ajax call, read the value out of the hidden input element, and include it in your data that you're posting back.

Related

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );

PHP not reciving data with AJAX's POST

I have to say I saw a dozens of topics similar to my problem, but most of them were typos or spelling.
My PHP file does not seem to receive any data from AJAX POST function (I'm getting Undefined Index). Here is my code:
var login = $("#log_l").val();
var pwd = $("#pwd_l").val();
alert(login);
alert(pwd);
$.ajax({
type: "POST",
url: 'app/menu/login.php',
data: {
login1: login,
pwd1: pwd,
},
cache: false,
success: function (data) {
if (data == 'fail') {
alert('test2');
$('#failure_log').show();
}
else {
document.location = " {$conf->action_root}postlogin";
}
}
});
return false;
And the login.php:
$login = $_POST['login1'];
$haslo = $_POST['pwd1'];
...
I tried with both:
login1:login,
pwd1:pwd,
And:
'login1':login,
'pwd1':pwd,
But in both ways I receive "Undefined index" error in .php file on 'login1' and 'pwd1' variables.
I checked that ajax 'reaches' file and it even receives the echos from .php file, but the variables are not sent/received.
Do you have any ideas what might be wrong?
You need to use file_get_contents to capture ajax calls or you need to define. Check this
How to get JSON data in php ?
Or
you need to set the ajax call as form_encoded_url
contentType: "application/x-www-form-urlencoded",
refer this link
Submitting HTML form using Jquery AJAX

how can i get name from javascript to code behind from following

this is the method to get userinfo from gmail. i dont know how to pass username values to code behind can any one help ..
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken/acToken,
data: null,
success: function (resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
I think you need the response you got from ajax call in the code behind. For that you have to set the value to a hidden field. So that you can access the values in code behind using its ID.
You can use this code if you are working with ASP .net
HTML code --
<asp:hiddenfield ID="user" runat="server"></asp:hiddenfield>
Jquery
$("#user").val(user); // Add data to html field
CodeBehind
Object user = user.Value;

Pass a value to multiple PHP pages at once with JQuery

My inexperience has me here asking this question.
Can I pass a value to multiple PHP pages in JQuery?
Here is an example of what I am trying to do.
$(function() {
$("#account").change(function() {
$("#facilities").load("displayfacilities.php?q=" + $("#account").val());
$("#facilities").load("updatefacilities.php?f=" + $("#account").val());
});
});
When the user changes a selection within a drop down list, a unique ID will be sent over to displayfacilities.php. I also need that ID in updatefacilities.php which is called from displayfacilities.php.
Is this a bad idea, or is there a better way?
Try to make use of $_SESSION and example of the usage.
This object allows you to store and retrieve data and a usual use case is to share this data across multiple pages within a session.
ex.
$(function() {
$("#account").change(function() {
// store value in superglobal variable and retrieved
// by session_start() in php script, see usage examples above
<?php $_SESSION['some_key'] = *some_value* ?>
// the following value however needs to be sent to server
// either via AJAX or some request.
$("#account").val();
});
});
Hope this helps.
Check this out,
First call ajax, when the response is received, make the second ajax call.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#account").change(function() {
var dataString1 = "q="+$("#account").val();
$.ajax
({
url: "displayfacilities.php",
type : "POST",
cache : false,
data : dataString1,
success: function(result1)
{
alert("Response from PHP file 1");
var dataString2 = "f=" + $("#account").val();
$.ajax
({
url: "updatefacilities.php",
type : "POST",
cache : false,
data : dataString2,
success: function(result2)
{
alert("Response from PHP file 2");
}
}
});
});
});
});
</script>

Codeigniter ajax CSRF problem

I've made a simple autoload function that loads content when you scroll down on a website. However, there seems to be a few problems when i enable CSRF protection in Codeigniter.
I'm not using a form, so i don't know how i can send the token from A to B when i'm doing my post request as you scroll.
My JavaScript
if (location.href == baseurl) {
$(window).scroll(function(){
if ($(window).scrollTop() > $('body').height() / 2) {
if(doScroll == 1) {
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
$("#wrapper_content").append(data);
if(data == 'Det finnes ikke flere bilder i databasen, WTF!? Send inn forslag ASAP!') {
doScroll = 0;
}
ID++;
});
}
}
});
}
Since Codeigniter expects a TOKEN on all POST request i can't get this to work when CSRF i enabled. Any suggestions?
Error when CSRF is Enabled
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
If i turn CSRF off, everything works great...
You might like to try this code I've used. It works great:
<script type="text/javascript">
$(function(){
$('.answerlist').each(function(e){
$(this).click(function(){
var valrad = $("input[#name=answer]:checked").val();
var post_data = {
'ansid': valrad,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>online/checkanswer",
data: post_data,
success: function(msg){
/// do something
}
});
});
});
});
</script>
As others say - you have to post the CSFR token name and its value with the AJAX request parameters. Here is a simple solution to append it automatically to every AJAX request.
Here is what I put on my main view, so this code is on every page before loading the other javascript files:
<script>
var csfrData = {};
csfrData['<?php echo $this->security->get_csrf_token_name(); ?>']
= '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<!-- ... include other javascript files -->
</body>
</html>
And here is a part of a javascript file that I include on every page:
$(function() {
// Attach csfr data token
$.ajaxSetup({
data: csfrData
});
});
If you want, you can echo both the token name and the hash somewhere appropriate. Something like this.
echo $this->security->get_csrf_token_name()
and
echo $this->security->get_csrf_hash()
Or, you could use form_open() as usual and use the hidden input that is generated for you from your javascript. Disabling the CSRF-functionality is the wrong way to go.
Having reviewed my situation I believe the best option is to use CSRF but reset the token on each attempt. Otherwise the ideas expressed earlier about re-using the cookie token would allow an attacker to resubmit data hundreds of times using the same token which defeats the object of the point.
As such I have created the following function:
public function resetCSRF(){
$this->security = null;
$_COOKIE[$this->config->item('csrf_cookie_name')] = null;
load_class('Security', 'core');
$this->security->csrf_set_cookie();
return $this->security->get_csrf_hash();
}
If for example an ajax based login form fails - call this function in your PHP and then on the javascript side that receives the failure (this solution uses Jquery and a getCookie function from w3schools) would then simply call:
$('input[name="csrf_test_name"]').val(getCookie('csrf_cookie_name'));
Basically what you need to do is get the expected csrf value from the cookie (named 'ci_csrf_token' by default), then post it along with your other data.
You would need to modify this line:
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
to:
$.post(baseurl + 'ajax/images',{'id' : ID,'ci_csrf_token' : $.cookie('ci_csrf_token')}, function(data) {
Might need to install the cookie addon (I'm not really sure; I use mootools). Here is more information: http://aymsystems.com/ajax-csrf-protection-codeigniter-20.
Previous suggestions work great, but rather than using a variable that you can apply in every data-post, I find it simpler to use the ajax-setting to automatically apply this token to every post:
$(document).ajaxSend(function(elm, xhr, s){
if(s.data){
s.data += '&';
}
s.data += '<?php echo $this->security->get_csrf_token_name(); ?>=<?php echo $this->security->get_csrf_hash(); ?>';
});
(works with jquery-1.9.1. I'm not sure about other jquery-versions)
The only problem with a few of the above answers is that a csrf token is only valid for one request, so if you make a post request via ajax and do not refresh the page you will not have the current csrf token for your next ajax post request. This is my solution:
In your CodeIgniter Controller:
$data = array('data'=> 'data to send back to browser');
$csrf = $this->security->get_csrf_hash();
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));
$data = the data to return to the browser
$csrf = new csrf token to be used by the browser for next ajax post request
Obviously you can output this in other ways but JSON is used mostly with ajax calls. Also include this token in every post response to be used for the next post request
Then in your next ajax request (javascript):
var token = data.csrf;
$.ajax({
url: '/next/ajax/request/url',
type: 'POST',
data: { new_data: 'new data to send via post', csrf_token:token },
cache: false,
success: function(data, textStatus, jqXHR) {
// Get new csrf token for next ajax post
var new_csrf_token = data.csrf
//Do something with data returned from post request
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );
}
});
Also remember that where I've got csrf_token:token replace crf_token with the name of your token found in application/config/config.php on line that states $config['csrf_token_name'] = 'csrf_token';

Categories

Resources