caveat: this would probably be pretty simple with a submit, but because of someone else's #%^$!& code, every submit clears all data on all forms on the page, so i cannot use .submit()
here's what i'm trying to do:
step 1: a link on a page, via Javascript, opens a popup. that popup has a some fields you fill it out, and using window.opener.getElementById('hiddenX').value, various hidden html elements on the original page are then updated, and the popup is closed.
step 2: on unload of the popup, the html elements are modified via Javascript.
step 3: the updated html elements are added back to $_POST on the page
Step 4: a bit of php code runs a php function using the values from $_POST as well as the values produced by earlier php code to create and send an email.
I do not think i can pass the values via a GET-style url since some of the values are very very long text strings, and tehre will probably be some arrays as well. I have tried using .post(window.location, {val1 : "1stvalue"}) in combination with a .load() on the div containing the php code from step 4. i think the div updates, but the POST value remains empty. any ideas?
script:
$(".email1").on('click', function (event) {
var win1 = window.open("../sub1.php","_blank","height=450,width=510, status=yes,toolbar=no,menubar=no,location=no");
$(win1).on('unload', function (event){
if(document.getElementById('hidden1').value != "z"){
$tosend2 = document.getElementById('hidden3').value;
...... // various changes to $tosend2 and other elements on the page
$.post( window.location, { hidden3 : "abc" }); //temporarily use "abc" instead of $tosend2
$( "#emaildiv" ).load(location.href+" #emaildiv2>*","" );
}
});
});
html / php :
<div style="display : hidden" name="emaildiv" id="emaildiv">
<input type="hidden" name="hidden1" id="hidden1" value="z" />
<input type="hidden" name="hidden3" id="hidden3" value="z" />
</div>
<div style="display : hidden" name="emaildiv2" id="emaildiv2">
<?php
echo "<div class='error'> what is the val?: " . $_POST['hidden1'] . " </code></div>";
if( !empty($_POST['hidden1']) ){
if( $_POST['hidden1'] != "z" ){
echo "<div class='error'> what is it now?: " . $_POST['hidden1'] . " </code></div>";
//emailstuff($locnlist, $_POST['hidden1'], $_POST['hidden3']);
//echo "email sent";
}
}
?>
</div>
I solved this by moving the email function and php div to a separate php page, called sub2.php, and then sending the post values to that page via ajax
$.ajax({
type: 'post',
url: '/routing/sub2.php' ,
data: { hidden1 : document.getElementById('hidden1').value ,
hidden2 : document.getElementById('hidden2').value ,
hidden4 : document.getElementById('hidden4').value ,
locnlist : loclist },
success: function () {
alert("Email has been sent!");
}
});
this doesn't actually solve the initial issue, but it works just as well.
if someone has a better solution, i'd be very pleased to know what it is
Related
New to web dev so bear with me. In wordpress I have a functions.php file with a function that generates a chart and would take 2 dates as an input.
In my page-template.php I would take 2 date inputs and click generate to make a chart re-generate without reloading the page. I have a function with no arguments that runs on page load, and the button would load the alternate function that takes the two dates on button click.
Ajax seems to be the answer but most tutorials confuse me as their example require connecting to the DB or is focused on it exclusively. Wouldn't calling my function that does it already via wordpress functions handle that on their own? Is there a simple way to get my function called as it is while passing the two form values date1,date2? Truncated code to be hopefully readable.
Appreciate the help.
page-template.php: The first function is the one on load with default range (from functions.php file), then the date picker and button.
<?php
lineChartAll_Generate();
echo "<form>
Select Date Range:
<input type='date' name='date1'>
<input type='date' name='date2'>
</form>";
?>
functions.php: Using WP database function to run a select into a variable, then run the javascript code that generates the visuals of my chart.
<?php
add_action('wp_enqueue_scripts','enqueue_parent_styles');
function enqueue_parent_styles(){
wp_enqueue_style('parent-style', get_template_directory_uri().'/style.css');
}
function lineChartCustom_Generate($date1,$date2){
//Database queries
global $wpdb;
$overallenergyResults = $wpdb->get_results
(
"SELECT QUERY GOES HERE"
);
// Line chart code
echo "
<div class='lineChartAll'>
<canvas id='myChart' width='400' height='200'></canvas>
<script>
//Chart javascript code goes here using $overallenergyResults variable
</script></div>";
}
?>
Here is a simple and working ajax program, check it to understand the process then customize it in the way you want.
The program gets two dates (date1, date2) from a form with id="my-form" and displays them into a div with id="display".
page-template.php:
<?php
echo "<script> const ajaxurl = '". admin_url('admin-ajax.php') ."' </script>"; // stores the ajaxurl into a js constant to be accissable in front-end page
?>
<form id='my-form'>
Select Dates: <br>
Date1: <input type='date' name='date1'><br>
Date2: <input type='date' name='date2'><br>
<button id='submit'> submit </button>
</form>
<div id='display' style="border: 1px solid; width: 200px; height: 100px;">
<em>submit the form to see dates here: </em>
</div>
<script type="text/javascript">
jQuery('#submit').on('click', function(event) {
event.preventDefault();
let date1 = jQuery('input[name="date1"]').val();
let date2 = jQuery('input[name="date2"]').val();
let formData = [date1, date2]; // prepare the form data as an array
jQuery.ajax({
url: ajaxurl, // ajaxurl defined at the top of the codes
type: 'POST',
data: {
action: 'your_custom_action', // use this action to handle the event
dataForPHP: formData // this is your form's data that is going to be submitted to PHP function by the name of dataForPHP
},
success: function(response) {
// show the response into dispaly div
jQuery('#display').html(response);
},
error: function(error) {
// show an oops! message
alert('oops! request failed.');
}
});
});
</script>
functions.php:
// ajax actions in wordpress must be handled by two actions: one with the prefex 'wp_ajax_' and another with the prefix 'wp_ajax_nopriv_'
add_action('wp_ajax_your_custom_action', 'your_custom_function');
add_action('wp_ajax_nopriv_your_custom_action', 'your_custom_function');
function your_custom_function() {
if ( isset( $_POST['dataForPHP'] ) ) {
// do anything you want with the submitted data, ex: running database query
$date1 = $_POST['dataForPHP'][0];
$date2 = $_POST['dataForPHP'][1];
}
echo "date 1: $date1 <br> date 2: $date2"; // send the response back to the client.
die();
}
Note: This function must have a response for the Ajax. the response can be JSON object or any string, if you would like to return HTML typography, just echo them as a string.
More about WP AJAX here: https://codex.wordpress.org/AJAX_in_Plugins
Yeah, Ajax is the solution for this issue, Here is the Ajax-using version of your code:
Form:
<?php
lineChartAll_Generate();
echo "<form id="my-form">
Select Date Range:
<input type='date' name='date1'>
<input type='date' name='date2'>
<button id='submit'> submit </button>
</form>";
?>
JavaScript/jQuery:
By clicking the submit button the jQuery collects the form data into an array and stores them in the formData variable, then submits it to the PHP with the name of dataForPHP and fires an ajax action hook by the name of your_custom_action
jQuery('#submit').on('click', function() {
let formData = jQuery('#my-form').serializeArray(); // retrieves the form's data as an array
jQuery.ajax({
url: ajaxurl, // default ajax url of wordpress
type: 'POST',
data: {
action: 'your_custom_action', // use this action to handle the event
dataForPHP: formData // this is your form's data that is going to be submitted to PHP by the name of dataForPHP
},
success: function( response ) {
// do what you want with the response echoed from PHP
},
error: function( error ) {
// show an oops! message
}
});
});
});
PHP:
PHP uses the fired ajax action by jQuery to run a function, so, add_action('wp_ajax_your_custom_action', 'your_custom_function'); means when the your_custom_action fired, run the your_custom_function.
add_action('wp_ajax_your_custom_action', 'your_custom_function'); // ajax actions in wordpress must have the prefex 'wp_ajax_'
function your_custom_function() {
if ( isset( $_POST['dataForPHP'] ) ) {
// do staffs with submitted data from the html form...
}
echo 'what you want to receive as a response in jQuery.ajax() success function'; // ignore this line if you don't want to receive any response.
}
I am trying to pass the link's text as a value to the next page so I can use it to search the database for the item and retrieve the information related to the value .I have tried using the POST method but regardless the information is not passed. This is the code I tried .
<form action="DetailedMenu.php" method = "POST" action = "<?php $_PHP_SELF ?>">
<?php
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
echo str_repeat(' ', 4); ?>
<a href="DetailedMenu.php" ><?php echo $array[$i]["Food_Name"];?></a>
<?php echo " " .str_repeat('. ', 25). "€".$array[$i]["Food_Price"]."<br>"; ?>
<input type="hidden" name="name" value="<?php echo $array[$i]["Food_Name"];?>">
<?php
}
}
?>
</form>
You don't need the form.
The easiest way to do what you're trying to do....
In addition to including the text in the content of the link, include it as a query string parameter.
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
I would actually recommend something more like this. I obviously don't know the names of your fields, so I've just taken a guess...
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
You'll be able to access "FoodID" as a parameter within your PHP, just as you would if it had been submitted from a form.
You may be looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without refreshing the page.
In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.
Just build a structure inside a DIV (input fields, labels, etc) and when the user is ready to submit, they can click an ordinary button:
<button id="btnSubmit">Submit</button>
jQuery:
$('#btnSubmit').click(function(){
var fn = $('#firstname').val();
var ln = $('#lastname').val();
$.ajax({
type: 'post',
url: 'ajax_receiver.php',
data: 'fn=' +fn+ '&ln=' +ln,
success: function(d){
if (d.length) alert(d);
}
});
});
ajax_receiver.php:
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
//Do your stuff
Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.
I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
I have several instances where a form is brought into the page in an overlay via ajax. On these forms I have a "math validation" question (I know not the most secure). I am using the following to generate the problem:
<?php
$randomNum = rand(0,9);
$randomNum2 = rand(0,9);
$randomNumTotal = $randomNum + $randomNum2;
?>
the random number is displayed in a text box like so:
<input type="text" name="someName" value="<?= $randomNum ?> + <?= $randomNum2 ?>" readonly>
and validated:
...
SomeName: {
required: true,
equal: <?php echo $randomNumTotal; ?>
}
...
This works fine when the form is on the page, hidden and then displayed with a .click function. I would like to store the files remotely and display them via AJAX. No problem doing that, the problem is when I do this, the numbers generated don't match the value. I've tried putting the PHP $randomeNumTotal function on both the form itself that is brought in via AJAX and on the parent page. Neither works.
So my question is this: Can I store the PHP function in a remote file "random.php", then pass the value to it via .get? If so, how do I make "SomeName" value equal the value from the file?
<script>
$.get( 'random.php', function ( data ) {
$("SomeName").val('random.php')?//I know this isn't right
});
</script>
Thanks!
$.get( 'random.php', function ( data ) {
$("SomeName").val(data);
});
Should work. Alternatively, you could use jQuery's load() if you wanted to load the content in as the HTML of any element.