i'm a little stuck with a jQuery. At the moment my function looks like this.
$(function(){
$(".url2").keyup(validNum).blur(validNum);
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(https?:\/\/)?(www.)?[0-9A-Za-z-]{2,50}\.[a-zA-Z]{2,4}([\/\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#]){0,250}(\s){1}$/
,"http://my.site/ref.php?id=<?php $code = unqiue-ref-id(); echo $unqiue-ref-id;?>");
if (initVal != outputVal) {
$(this).val(outputVal);
return false;
}}
});
So right now it rewrites a user typed url (in a textarea) to a redirection link with my own url (e.g. my.site?ref.php?id=unique12. What I need exactly is a POST Request to a php file (code below) where the valid user-url is given to the php file as a var and then the php file should give back a var with the generated unique unique-ref-id. I do of course know that the code above isn't working like that, it only shows how the final result should look like. The php file wich generates the unique-ref-id looks like this.
function unqiue-ref-id() {
$unqiue-ref-id = "";
$lenght=4;
$string="abcdefghijklmnopqrstuvwxyz123456789";
mt_srand((double)microtime()*1000000);
for ($i=1; $i <= $lenght; $i++) {
$shorturl .= substr($string, mt_rand(0,strlen($string)-1), 1);
}
return $unqiue-ref-id;
}
$user-url = // var send from jquery
do{
$unqiue-ref-id = unqiue-ref-id();
} while(in_array($unqiue-ref-id, $result));
// var send back to jquery function => final results of do function above
// Here i add the $user-url and $unique-ref-id to datebase (Dont need code for that)
?>
Would be so great if someone can help me out with that. Thanks a lot :)
Use the POST jQuery's method. Here's an example
$.post('URL-TO-POST-DATA', {'parameter1': 'value', 'parameter2': 'value'}, function(data_received){
/** Here goes your callback function **/ alert(data_received);
});
More information about POST method
Don't forget one thing. jQuery will not receive nothing if you don't use echo on PHP (instead of return). You MUST use echo in PHP, don't forget it.
Related
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
I have actually read all related answers to my question but I need a clear and simple example on how to properly implement my code below.
myHome.php
jquery
var url = "computeArea.php";
var data = $('thisForm').serialize();
$.post(url,data,function(response)); // how do i get the area being returned from
computeArea function? i need to save the
return value to a javascript variable
computeArea.php
function computeArea ($data){ // do i need to parse $data to make it an array?
return $area;
}
im new to jquery and your help is very helpful. thank you!
You can do:
$.post(url,data,function(response){
alert(response)
});
ps: you are missing the . between $ and post.
In your php code you could do that:
echo json_encode($area);
Do a simple teste.
jQuery:
$.post("url/to/file.php",{variable_name: "hello"/*(we'll give this value to variable_name*/)},
function(response){
if(response>0)
alert('Something went wrong');
else
alert(response);
});
Now, on server side:
<?php
if(isset($_POST['variable_name']) && $_POST['variable_name']!=="")
echo $_POST['variable_name'];
else
echo 1;
?>
You are misunderstanding the use of post requests. This will not call the computeArea function in computeArea.php and pass data as its parameter:
var data = $('thisForm').serialize();
$.post(url,data,function(response));
You can do this instead for computeArea.php:
$data = $_POST['watever_you_are_serializing'];
// Do computations, etc.
$area = 123; // Contains computed area
echo $area; // Or json_encode($area);
If you need to call that function from computeArea.php, then you can create a new file for $.post request (eg. computeArea2.php) and include computeArea.php from there. It would be something like this:
include 'computeArea.php';
$data = $_POST['watever_you_are_serializing'];
echo computeArea($data);
Something along the lines of:
var url = "computeArea.php",
data = $('thisForm').serialize(),
new_variable;
$.post(url, data, function(response) {
new_variable = response;
});
Though I presume there's a bit more to your PHP script, as otherwise $area isn't defined anywhere.
Does anyone have experience with ajax in drupal 7?
I'm a little stuck.
So, with my module, I output a link and map the path to a callback function with hook_menu()
In the callback function I used ajax_command_replace() and ajax_deliver() to update content.
Well, so far, so good. It all works. But turns out, for complicated reasons, that using links won't work.
So instead I decided to try the jQuery ajax way. So I attach a click event to a div so when it gets clicked something like this runs in a JavaScript file that I load:
jQuery.ajax({
type: 'POST',
url: 'http://path/etc',
});
Then, in my module, I use hook menu to map the path to a callback function that looks like this:
function the_callback($var) {
// a lot of code that gets the right nid to load. This all works...
// and eventually I end up here:
$node = node_load($nid, NULL, false);
if ($node) {
$node_view = node_view($node);
$output = theme("node",$node_view);
$commands = array();
$commands = ajax_command_replace('#content','<div id = "content">' . $output . '</div>';
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);
}
This is the exact same code that was sucessfully replacing content when I had the links. But for some reason this doesn't work when I try to invoke the ajax call with jQuery. The callback function gets called, the correct stuff gets loaded in $output, but the page isn't updating.
Does anyone know what is going on here?
Are you missing a closing parenthesis?
$c = ajax_command_replace('#content','<div id = "content">' .$output. '</div>';
Should be:
$c = ajax_command_replace('#content','<div id = "content">' .$output. '</div>');
probably there is some javascript code inside the $output returned by theme('node', $node_view) , which you need to strip(remove).
here's some code from my ajax function returning the node rendered content:
$n = node_load($nid, NULL, FALSE);
$output = drupal_render(node_view($n));
$output = preg_replace('~<script\s+type="text/javascript">.+</script>~is', '', $output);
How can I go about accomplishing the following behavior.
upon getting an input from a knockout.js form send the variable to a page to be handled. The page uses PHP
The PHP page receives the input from the knockout.js form and runs some calculations and then returns the result
The variable is then received back on the original page and is then displayed via knockout
For example, say I have the following
//knockout_form.js
self.addItem = function() {
var itemNum = self.newItem; //variable received from knockout form
var returnedVariable = ???? **send itemNum to processing.php which will then return it**
self.itemNumbers.push(new ItemEntry(retunredVariable, "$20.00")); //
}
I know that jQuery/Ajax can be used to post to processing.php, but how do I return the calculated data from processing.php back to the javascript page?
edit below. The data appears to be sent to processing.php (shows up in the network tab) but the alert isn't showing.
// Operations
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum),function(data) {
alert(data); //this does not appear
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
}
}
Here's the php
//$result = $_GET['itemNum'];
$result = "test"; //set it just to be sure it's working
echo json_encode(array("result" => $result));
Knockout doesn't have any special way of doing ajax calls itself, typically you would use jQuery. See http://knockoutjs.com/documentation/json-data.html.
So something like:
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum,function(data) {
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
});
}
This assume that your PHP script is outputting valid JSON. Something like:
<?php
$result = doCalculations($_GET['itemNum']);
echo json_encode(array("result" => $result));
?>
This is untested, but you get the idea.
First off, I am very bad at flash/actionscript, it is not my main programming language.
I have created my own file upload flash app that has been working great for me up until this point. It uses PHP to upload the files and sends back a status message which gets displayed in a status box to the user.
Now I have run into a situation where I need the HTML to pass a parameter to the Actionscript, and then to the PHP file using POST. I have tried to set this up just like adobe has it on http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html without success.
Here is my Actionscript code
import fl.controls.TextArea;
//Set filters
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
var textTypes:FileFilter = new FileFilter("Documents (*.txt, *.rtf, *.pdf, *.doc)", "*.txt; *.rtf; *.pdf; *.doc");
var allTypes:Array = new Array(textTypes, imageTypes);
var fileRefList:FileReferenceList = new FileReferenceList();
//Add event listeners for its various fileRefList functions below
upload_buttn.addEventListener(MouseEvent.CLICK, browseBox);
fileRefList.addEventListener(Event.SELECT, selectHandler);
function browseBox(event:MouseEvent):void {
fileRefList.browse(allTypes);
}
function selectHandler(event:Event):void {
var phpRequest:URLRequest = new URLRequest("ajax/upload.ajax.php");
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
phpRequest.method = URLRequestMethod.POST;
phpRequest.data = flashVars;
var file:FileReference;
var files:FileReferenceList = FileReferenceList(event.target);
var selectedFileArray:Array = files.fileList;
var listener:Object = new Object();
for (var i:uint = 0; i < selectedFileArray.length; i++) {
file = FileReference(selectedFileArray[i]);
try {
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, phpResponse);
file.upload(phpRequest);
}
catch (error:Error) {
status_txt.text = file.name + " Was not uploaded correctly (" + error.message + ")";
}
}
}
function phpResponse(event:DataEvent):void {
var file:FileReference = FileReference(event.target);
status_txt.htmlText += event.data;
}
function objectToURLVariables(parameters:Object):URLVariables {
var paramsToSend:URLVariables = new URLVariables();
for(var i:String in parameters) {
if(i!=null) {
if(parameters[i] is Array) paramsToSend[i] = parameters[i];
else paramsToSend[i] = parameters[i].toString();
}
}
return paramsToSend;
}
The flashVars variable is the one that should contain the values from the HTML file. But whenever I run the program and output the variables in the PHP file I receive the following.
//Using this command on the PHP page
print_r($_POST);
//I get this for output
Array
(
[Filename] => testfile.txt
[Upload] => Submit Query
)
Its almost like the parameters are getting over written or are just not working at all.
Thanks for any help,
Metropolis
Try...
print_r($_FILES);
Like I said in my comment: Do you successfully receive the variable in Flash from the flashvars?
I haven't done Flash in a while but maybe, instead of your objectToURLVariables function, just referencing each variable directly is a better way. At least to figure out if you have those variables from your HTML page. So maybe do something like this:
var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myVar;
var flashVars:URLVariables = objectToURLVariables(myVar);
Ok, I have fixed the issue somehow.....I kept changing things back and forth and realized that the cache had not been cleared in awhile. I cleared the cache and it started working for some reason.
I did change one line back to the way I had it before.
I changed
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
To
var flashVars:URLVariables = objectToURLVariables(root.loaderInfo.parameters);
Im not positive that this was causing the problem. It may have been that I just needed to clear the cache the whole time. Anyway, thanks for your help guys.