Jump to content

set request action in Javascript


Mahngiel

Recommended Posts

How would you add $_REQUEST['action'] in pure JS akin to how you'd do it with jQ? I looked through here and didn't see anything.

 

jQ

$.ajax({
url: 'register/verify_registration',
data: 'action=check_registration'

 

JS

xhr.open("POST", 'register/verify_registration', true);  

Link to comment
Share on other sites

It depends on if you want it to be sent as POST data or GET data.  For GET data you'd just append it to the URL as part of the query string:

xhr.open("POST", 'register/verify_registration?action=check_registration', true); 

(Just because your using the POST method doesn't mean you can't have GET variables.)

 

 

Or to send it as post data you pass it to the .send method, but you also have to set some additional headers

var data='action=check_registration';

xhr.open("POST", 'register/verify_registration', true); 
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', data.length);
xhr.send(data);

Link to comment
Share on other sites

Thanks, kicken.  I am sending via POST, and I do have all of the additional code you posted.  However, I have a 'catching' function for all my ajax requests and kicks them out according to the action:

 

<?php
// --------------------------------------------------------------------
function verify_registration()
{
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']))
{
	if (@$_REQUEST['action'] == 'check_username') 
	{
		echo json_encode($this->check_username($_REQUEST['username']));
	}
	elseif (@$_REQUEST['action'] == 'check_email') 
	{
		echo json_encode($this->check_email($_REQUEST['email']));
	}
...

 

Looking back at my OP, you can see the jQ ajax request is pushing to the main function which gets sorted according to the action.  I'd like to accomplish the same thing with regular ol' javascript - but in order to do so, I need to be able to set the action

Link to comment
Share on other sites

My bad, I didn't read your post thoroughly:

 

 

var data='action=check_registration';
...
xhr.send(data);

 

can you send multiple data through the .send() method? 

 

I suppose this question requires more elaboration, so here's the deal.  I'm using parts and concepts of a script I found here.  This makes uploading images a snap and not requiring iframes or flash. 

 

(function() {
$('.ajaxUpload').change(function(e) {
	e.preventDefault();

	var files = e.target.files || e.dataTransfer.files;
	var file = files[0];

	if (file.type.indexOf("image") == 0 && file.size <= 1048576 ) { UploadFile(file); }			
});

function UploadFile(file) {		
	var xhr = new XMLHttpRequest();
	if( xhr.upload ) {

		// Action layover
		xhr.onreadystatechange = function() {
			if( xhr.readyState == 1 ) { 
				$('.loading').show(); 
			} 
			else if( xhr.readyState == 4 && xhr.status == 200 ) 
			{
				$('.loading').hide();
				newAvatar(file);
			}
		}

		// Send file
		xhr.open("POST", 'account/avatar', true);
		xhr.setRequestHeader("X_FILENAME", file.name);
		xhr.setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest");
		xhr.send(file);

		// Retrieve file
		function newAvatar(file) {
			$.ajax({
				url: 'account/get_avatar',
				cache: false,
				success: function(newA){
					$('#thumb').attr('src', 'images/avatars/' + newA);
				}
			});
		}
	}
}
})();

 

So, in essence, I'd like to expand the script to be able to use it on various pages, which have various image requirements.  This requires that I pass extra data so my scripts can figure out which path it needs to go to.  For instance, avatars may be resized to 100x100, but gallery items not at all. 

Link to comment
Share on other sites

I don't think there is a way to send both a file and form-data through the .send method at the same time.  You'll have to send your action through the query string like the first example in my previous post.  Since $_REQUEST in php contains both get and post variables your php script should still work the same.

 

 

Link to comment
Share on other sites

Ok, I tried to go the route of using query strings to set the action this morning - but no avail.

 

var param = $('.imageAjax').attr('data-param');
xhr.open("POST", 'http://example.com/test?action=' + param, true);

http://example.com/test?action=headlines

 

Simple testing lib

library DropImage()

<?php
function catch_image()
{		
// Prep return data
$response = array();

// Begin formalities
if( !isset($_SERVER['HTTP_X_REQUESTED_WITH']) )
{
	$response = array(
	'status' 	=>	0,
	'msg'		=>'improper path or request',
	);
}
else
{
	$response = array(
	'status' 	=>	1,
	'msg'		=>'good to go',
	);	
}

return $response;
}

 

Basic testing works just fine.

 

controller

<?php
function index()
{
$this->load->library('DropImage');

$response = $this->dropimage->catch_image();		

echo json_encode($response);
}

 

{"status":1,"msg":"good to go"}

 

Since $_REQUEST in php contains both get and post variables your php script should still work the same.

However, it's not setting the $_REQUEST like we thought it would.

 

controller

<?php
function index()
{
$this->load->library('DropImage');

$response = array();

if (@$_REQUEST['action'] == 'headlines') 
{
	$response = $this->dropimage->catch_image();		
}

print_r( $_REQUEST );
print_r( $_GET );
echo json_encode($response);
}

 

Produces

Array
(
    [/test] => 
)
Array
(
    [action] => headlines
)
[]

 

For the record, I have tried this on a method instead of the default, but it changes nothing.  What are your thoughts on this?  Am I doing it wrong? Should I go forward with filtering though $_GET instead of $_REQUEST ?

Link to comment
Share on other sites

Since $_REQUEST in php contains both get and post variables your php script should still work the same.

However, it's not setting the $_REQUEST like we thought it would.

 

The only reasons why $_REQUEST wouldn't have the same keys as $_GET is because either

1) Your php.ini has a non-standard configuration causing get to be excluded or

2) Your code is doing something to change it at some point

 

That said,

 

Should I go forward with filtering though $_GET instead of $_REQUEST ?

It's generally considered a good idea to be more explicit about where you get your variables from and use $_POST or $_GET and not use $_REQUEST.  That way it is clear how they are being delivered and reduces the chances of someone passing stuff in ways they shouldn't.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.