Hiding arguments in http call - php

I use this to pass an argument (fullname).
<script type="text/javascript">
function listbox_update(){
var fullname = document.getElementById("listboxid").value;
document.location.href="{$_SERVER["PHP_SELF"]}?fullname="+fullname;}
</script>
Is there a way to pass the argument such that it can NOT be seen in the http URL?
I know about POST.
$listboxselected = $_POST['listbox'];
I would use POST instead, so that the argument is not present in the URL, but I can't, because I'm using the javascript as an On Click event.
<select id="listboxid" name=listbox onChange="listbox_update()"></br>
The On Click event works perfectly. But I don't like seeing all my variables in the URL.

If you want to do that only by JS then you can go with Ajax.
function listbox_update(){
var fullname = document.getElementById("listboxid").value;
$.ajax({
data: { fullname: fullname },
url: <?php echo $_SERVER["PHP_SELF"]; ?>,
type: "POST",
success: function(msg){
//some function here
}
});
}

Wrap the <select> in a <form> and then in onchange submit the form.
<form id="form" method="post" action="<?=$_SERVER["PHP_SELF"]?>">
<select id="listboxid" name="fullname" onChange="listbox_update()">
<option>here the options</option>
</select>
</form>
and the listbox_update
function listbox_update () {
document.getElementById('form').submit();
}
Another option would be to use Ajax, but since your original script reloads the page, then the first approach follows this way.

You have only 2 solutions for this:
1) Either you must implement AJAX like below:
function listbox_update()
{
var fullname = $("#listboxid").val();
$.ajax({
data: "fullname="+fullname,
url: <?php echo $_SERVER["PHP_SELF"]; ?>,
type: "POST",
success: function(msg){
console.log("Message :"+msg);
}
});
}
2) Or go with form submission.
function listbox_update()
{
$('#your_form_id').attr('action', <?php echo $_SERVER["PHP_SELF"]; ?>);
$('#your_form_id').submit();
}

Related

pass variable from js to php using POST

Whay I can't pass a variable from js to php
$("#btnpage").click(function(){
path = $('#spantwrap').html();
$.ajax({
url: 'plus-page.php',
type: 'post',
data: {'path': path},
success: function() {
console.log(path);
}
});
location.href = 'plus-page.php';
});
plus-page.php
<form id="form1" action="?" method="post">
<input type="hidden" name="path" value="<?php echo $_POST['path'];?>" // line 46
</form>
Error: Undefined index: path on line 46...
Have you tried this?
$("#btnpage").click(function(){
path = $('#spantwrap').html();
$.ajax({
url: 'plus-page.php',
type: 'post',
success: function() {
location.href = 'plus-page.php?path=' + path;
}
});
});
so that you can use this?
<input type="hidden" name="path" value="<?php echo $_POST['path'];?>">
What would be the value of your path?
Why don't you use form post method with this solution ??? ?
First Ajax post it completed when success: function called... In new window you doesn't have any post data, I don't know any solution post data by javascript to new window.. only one you can send data by GET request ..
You can see variable posted by ajax and open url by new window.. please use
With out using ajax ,to achieve what you required.
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
window.open('plus-page.php?my_data='+my_data);
});
plus-page.php
<?php
if(isset($_GET['my_data'])){
$data=$_GET['my_data'];
echo $data;
}
?>

Using AJAX to retrieve values from <select> dropdown?

I want to retrieve the value of my dropdown on change, and post it to my PHP (at the moment, the PHP is just var_dump, for debugging purposes)
I'm stuck at posting the selected value to my AJAX, seemingly there no change.
I Using WP framework to load scripts and run them through admin-ajax.php -- I've been
using this approach for others AJAX functions, and it is working.
I have a dropdown list, like this:
HTML
<form action="" method="post">
<select name="count" class="count">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
<input class="koordinator_id" type="hidden" name="koordinator_id" value="<?php echo $_SESSION['coordinator_id'] ?>">
</form>
AJAX
$(document).ready(function () {
$('select.count').change(function () {
alert("Whyunoalert?");
$.ajax({
type: "POST",
url: (my_ajax_script.ajaxurl),
data: ({
action: 'generate',
koordinator_id: $('input[name=$"koordinator_id"]').val(),
id: $('select.count').val()
}),
success: function (msg) {
alert("Data changed:" + msg);
}
});
});
});
PHP
function generate() {
$count = $_POST['id'];
var_dump($count);
$koordinator_id = $_POST['koordinator_id'];
var_dump($koordinator_id);
}
EDIT
I've changed the code accordingly to the first three comments. Now my code executes the AJAX but still no var_dump are made in the php file. Thanks for the help so far, hope you can do a bit more. Also i've added the functions.php code , where the php function is bound and the redirect to ajax-admin.php is setup.
functions.php
function load_scripts() {
wp_enqueue_script('local_jquery', '/wp-content/themes/tutorial_theme/scripts/scripts.js');
wp_enqueue_script('ajax_func', get_template_directory_uri() . '/scripts/ajax_implementation.js');
}
if (!is_admin())
add_action('wp_enqueue_scripts', 'load_scripts');
add_action('template_redirect', 'load_scripts');
$dirName = dirname(__FILE__);
$baseName = basename(realpath($dirName));
require_once ("$dirName/ajax_functions.php");
add_action("wp_ajax_nopriv_approve", "generate");
add_action("wp_ajax_approve", "generate");
2nd EDIT
removed this from the ajax: (was from old copy-paste)
dataType: 'html',
The selector $('input[name=$"koordinator_id"]') is wrong in your data line. The syntax for input name ending with some string is $('input[name$=somestring]'].
Use this instead:
$('input[name$="koordinator_id"]') // '$' needs to be before '='
^
First of all if you are firing ajax onchange event why did you wrap them in the form tag? remove it if no use other than onchange event.
Second is you're using action: 'generate' in your ajax function but you're not hooking the right action in your functions file of php
add_action("wp_ajax_nopriv_YOUR_ACTION", "METHOD");
add_action("wp_ajax_YOUR_ACTION", "METHOD");
So it would be
add_action("wp_ajax_nopriv_generate", "generate");
add_action("wp_ajax_generate", "generate");
Last but not least always exit your ajax method call, so make sure it won't fall below.
function generate() {
$count = $_POST['id'];
var_dump($count);
$koordinator_id = $_POST['koordinator_id'];
var_dump($koordinator_id);
exit;
}
Also as #Krishna answer remove the $ sign unexpected expression
koordinator_id: jQuery('input[name=$"koordinator_id"]').val(),
Need to be:
koordinator_id: jQuery('input[name="koordinator_id"]').val(),
You're missing the { after the .ready(function(). Fix it like this:
$(document).ready(function () {
$('select.count').change(function () {
alert("Whyunoalert?");
$.ajax({
type: "POST",
url: 'my_ajax_script.ajaxurl',
data: ({
action: 'generate',
koordinator_id: $('input[name=$"koordinator_id"]').val(),
id: $('select.count').val()
}),
dataType: 'html',
success: function (msg) {
alert("Data changed:" + msg);
}
});
});
});
Try like this
$(document).ready(function()
$('.count').change(function() {
$.ajax({
type: "POST",
url: 'my_ajax_script.ajaxurl',
data: {'action': 'generate', 'koordinator_id': $('input[name=koordinator_id]').val(), 'id': $('.count').val()}),
dataType: 'html',
success: function(msg) {
alert("Data changed:" + msg);
}
});
});
});
Also avoid using of php short tags.Sometimes it cause problems if your php version doesnt support short tags.So change this
<input class="koordinator_id" type="hidden" name="koordinator_id" value="<?php echo $_SESSION['coordinator_id'] ?>">

Trouble POSTing form with AJAX

edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});

Pass variable from Javascript/JQuery to PHP

I'm still new to JQuery and trying to learn how to submit form without page refresh...
What I want is, when the form is submitted, the value of what I type on "headline" and "subheadline" can be passed into php variable (So I can echo/insert data to database, etc)
So, I put
"<? echo $_POST['headline']; ?>"
on
<span class="save-notice">Your change has been saved! <? echo $_POST['headline']; ?></span>
but when I fill the form and click the submit button, it only shows "Your change has been saved!". Which means, the variable can't be passed to PHP.
The HTML and the JS is combined into 1 file. I left the URL method on .ajax because it is processed in the same file.
HTML FORM
<div id="submit-form">
<form action="" id="select-block" class="general-form">
<div class="input-wrap">
<input class="clearme" name="Headline" value="Your headline here" id="headline"/>
</div>
<div class="input-wrap">
<textarea class="clearme" name="Sub-Headline" id="subheadline">Sub Headline Here</textarea>
</div>
<input type="submit" class="submit-btn" value="SAVE" />
<span class="save-notice">Your change has been saved! <? echo $_POST['headline']; ?></span>
</form>
</div>
And the JQUERY CODE
<script type="text/javascript">
$(function() {
$(".save-notice").hide();
$(".submit-btn").click(function() {
var headline = $("input#headline").val();
var subheadline = $("textarea#subheadline").val();
var dataString = 'headline='+ headline + '&subheadline=' + subheadline;
alert(dataString)
$(".save-notice").hide();
$.ajax({
type: "POST",
url: "",
data: dataString,
success: function() {
$(".save-notice").show();
}
});
return false;
});
});
</script>
I saw on several example/tutorial on the internet if it can be done like that. Can you advise?
See
http://api.jquery.com/serialize/
Instead of adding code to click handler
$(".submit-btn").click(function() { ... }
use submit handler
$("#select-block").submit(function() {
// your code
var dataString = $(this).serialize();
});
The $_POST['headline'] in your save-notice was generated when the page was loaded. The PHP ran, and output an HTML file.
When you make your AJAX request, the page returned to the AJAX call would contain your new value, but your current page does not.
You can either post to a different page, have that page return a value, then use JavaScript to change the value of the div.
Or, you can try to extract the data from the returned HTML page.
$(".save-notice").hide();
$.ajax({
type: "POST",
url: "",
data: dataString,
dataType: 'html', // the page returned
success: function(data) {
// get the data from the returned page
$(".save-notice").html($('.save-notice', data).html());
$(".save-notice").show();
}
});
Using Firebug's console feature, you can see the server's response to your AJAX call. The response is evaluating the $_POST var like you want it to, but since the AJAX call happens behind the scenes, you don't see it.
To get your script working without much modification, try this (no PHP is necessary):
Replace <? echo $_POST['headline']; ?> with <span id="yourheadline"><span>
Insert $('#yourheadline').html(headline); on the line before $(".save-notice").show();
Another thing I would suggest is serializing your form to create the dataString var, instead of doing it input by input. If your inputs were named headline and subheadline instead of Headline and Sub-Headline...
var dataString = $("#select-block").serialize();
...would accomplish the same thing as:
var headline = $("input#headline").val();
var subheadline = $("textarea#subheadline").val();
var dataString = 'headline='+ headline + '&subheadline=' + subheadline;
You already have the values in the javascript variables:
var headline = $("input#headline").val();
var subheadline = $("textarea#subheadline").val();
You can do something like this:
$.ajax({
type: "POST",
url: "foo.php",
data: {headline: headline, subheadline: subheadline},
success: function() {
$(".save-notice").show();
}
});
or like this:
$.post("foo.php", { headline: headline, subheadline: subheadline },
function(data) {
$(".save-notice").show();
}
);
You can see that, data is passed in the key value pair:
{ headline: headline, subheadline: subheadline }
You can access it using $_POST like $_POST['headline'] and $_POST['subheadline']

Submitting form with jQuery

Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.

Categories