Two Forms In PHP - php

I have one php file that displays two forms. THe first Form displays data of customers from a table in mysql which also includes a checkbox. The second form contains data from another table and also includes a checkbox this form contains messages. I need to send messages selected with the checkbox to the list of customers selected in the first form.
Can I do that with pure php? or will I need to use javascript? please point me to a tutorial.

you need download Jquery library...and read what is ajax
get value
var value = $("#customer").val();
we get value for selector where id="customer"
get cheked
if($('#customer').is(":checked")) { } else { }
send data on server
var value = $("#customer").val();
$.ajax({
type: "POST",
url: "default.php",
data: "name="+value,
success: function(data){
alert('ok!') ;
}
});
we send data on server post method...we send variable value, value = value in value id="customer"
Good luck! Sorry for my English :)

The initial problem with what you are trying to accomplish is that you cannot natively submit two forms concurrently.
Is it absolutely necessary to have two separate forms? If so, you will need to implement something like this (written by Roatin Marth) in order to copy values over from one form to another when submitting:
function form2form(formA, formB) {
$(':input[name]', formA).each(function() {
$('[name=' + $(this).attr('name') +']', formB).val($(this).val())
})
}
Of course, if your business requirements do not require two separate forms, you can just place all the values into a single form and then process it with PHP. If you require validation of the form prior to submission, you will want to do that with Javascript first.
Once in PHP, you will get the values from the $_POST superglobal. You can then do what you need to do with it.
// With each customer checked, send checked messages
foreach($_POST['customers'] as $customer)
{
// With this customer, send all messages
foreach($_POST['messages'] as $message)
{
// Send $message here
}
}

Related

Send Data From my website to an external page of another website using PHP

all my problem is that I wanna send data from my website to this website's page :
http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw
how I can do this ? and is it possible ? cuz as I have seen this website forms validation's all in javascript and dunno how to handle it ?
thanks.
This is how you can do that, just make a testPosting.html file,
Create your form using all the inputs that are required to send.
See the screenshot for the posted fields.
This data is posted when i submitted the form after filling it.
Now as you can see 14 fields are posted, so you need to make 13 inputs and 1 textarea.
use click function for the button of submit e.g
$('#buttonID').click(function(e){
e.PreventDefault();
//store values of inputs in a variable
var data = {
FirstName = $('#FirstName').val(); // you can more better then that if you know how
//Add the rest of the data
};
});
then you can use jQuery Ajax to send data.
$.ajax({
url: "http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw",
data:data, //this data will be the variable that you create in which all the forms inputs datas are stored.
type: "POST"
}).done(function(result) {
//do stuff if some result has returned
});
i just gave the rough idea.
Oh you must use this line in script on top of you JS scrips
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
My code is not perfect but you get the idea what i am trying to say, you might can start from here, and do stuff of your own..

Update form fields after form submitted

I have no problem with submitting form data through AJAX, and display all that data in a separate div.
But how do I update the form itself with some new info based on server response?
In my case I have:
a form with many inputs, including a group of checkboxes
data from form is collected (with JQuery serialize) and sent to php script through Ajax.
I need to set a specific color for text near a selected checkbox.
I need to set that color not on client side, but based on server side script.
Please explain the correct logical process when need to update a form based on initial form data.
Server side, you can send back a json encoded variable like so.
echo json_encode( array('text_color', 'green') );
Then, on the client side, you can access this variable in the callback function.
$.ajax({
url: 'ajax/test.html',
dataType: 'json',
data: $('yourform').serialize(),
success: function(data) {
var color = data.text_color;
$('yourElement').css('color', color);
}
});
Alternatively you could send back a class and add that class to the element.
If you are using jQuery, you would send the data via AJAX (post/get) and then you would get the response from server script in plain text / json / xml format (your choice). In this case, if you need to return only color code, you can use plain text format. When you get the response, you can manipulate the data.
$.post("test.php", $('#form').serialize(),
function(returned_data_from_server_script) {
$('some dom for color').css('color', returned_data_from_server_script);
});

display html select (from PHP) via jquery?

So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.

How do I intercept a form's values before sending it?

I currently have a large form that gets sent to our payment authorizer (done so by action="paymentautherizerURL" ), however I am not getting all of the information I require back from them when I go to store the transaction in my DB.
I either need to intercept the form data before it submits so that I can store it in the session (we are using PHP / jQuery), or I have also tried sending it to an intermediary scriptlet that grabs the information I need, and then using jQuery's $.post() to re-build and send off the data to the authorizer.
the second approach does not seem to work, however, at least to the best of my efforts. I'm not sure that a $.post properly emulates the form's send action, or at least I have not done it right.
<?php
session_start();
$post = $_POST;
//gets all of the information that beanstream does not return to approved.php, but is still required to make
//a legitimate database entry. gets from the POST and stores in the session array for approved.PHP to access
$_SESSION['approvedArray']['billAddress'] = $_POST['ordAddress1'];
$_SESSION['approvedArray']['billProvince'] = $_POST['ordProvince'];
$_SESSION['approvedArray']['billCountry'] = $_POST['ordCountry'];
$_SESSION['approvedArray']['billPostalCode'] = $_POST['ordPostalCode'];
$_SESSION['approvedArray']['billCity'] = $_POST['ordCity'];
$_SESSION['approvedArray']['shipAddress'] = $_POST['shipAddress1'];
$_SESSION['approvedArray']['shipPostal'] = $_POST['shipPostalCode'];
$_SESSION['approvedArray']['shipCity'] = $_POST['shipCity'];
$_SESSION['approvedArray']['shipProvince'] = $_POST['shipProvince'];
$_SESSION['approvedArray']['shipCountry'] = $_POST['shipCountry'];
session_write_close();
//the javascript below will send what is required to beanstream as though it were sent from the form
<script type='text/javascript'>
$.post(, {
<?php
//rebuild the POST such that "name: value, " except the last name/value will not be followed by a comma
$keys = array_keys($_POST);
for($i = 0; $i < count($_POST); $i++) {
$currentKey = $keys[$i];
$currentPost = $_POST[i];
echo $currentKey . ": " . $currentPost;
if ($i < (count($_POST) - 1)) {
echo ", ";
}
}
?>
});
</script>
?>
normally, the transaction authorizer will re-direct the user to one of 3 pages (approved, declined, error), and our website does the job from there. however, it's currently stuck at this page, which makes me think it's not sending off properly.
i'm open to all forms of criticism, approaches and ideas. thanks very much in advance, and if any other information is needed, please let me know!
How about changing the form tag to include an onSubmit attribute:
<form action="notmal_action.whatever" onSubmit="return save_data_function()">
Where the save_data_function reads the values from the form and sends it to a script on your server to save in a database (or where ever). I use hidden iframes to make this request hidden from the user...
<script>
function save_data_function() {
$('#iframe_id').attr('src', 'data_saving_script.extension?data_1=' + $('form_data_1').val().serialize() + '&data_2=' + $('form_data_2').val().serialize());
}
</script>
You can set a timeout if the data isn't being passed quick enough to the "data_saving_script.extension" file.
Since your existing example already has a dependency on javascript, you could move to saving the data with AJAX and then using a traditional submit to do the "real" POST to the payment gateway.
Assuming that your form has id="foo", you could do something like this:
<script>
$('form#foo').submit(function(event, doRealSubmit) {
// this executes on the second pass
if (doRealSubmit) {
// returning true gets browser to do a real submit
return true;
}
// this executes on the first pass
$.ajax({
url: '/url/to/post/to/your/server',
type: 'POST',
// this serializes the form data in "application/x-www-form-urlencoded"
data: $(this).serialize(),
success: function(data) {
// trigger 'submit' event again, but pass the doRealSubmit flag
$('form#foo').trigger('submit', [true]);
}
});
// returning false prevents browser from processing the real submit
return false;
});
</script>
instead of action="paymentautherizerURL" you should send it to your own page:
<form action='process.php' method='post'>
now in your process.php you can work with the data (validation, filtering ..)
and when you are done you can send the data to the right place using cURL
With curl you can send post data and wait for the response to decide which page to show.
No need to put the data in sessions, on submit of form called a validate function in which done all the validation and then post the data to ur process.php using ajex , then it will retain on that page...
Don't store the data in the session - it's the wrong place to keep transactional data.
Post the stuff to a script you host, write only the stuff you need to keep to your database, generate an order reference for it,
then....
if you are using a payment processor (e.g. Paypal)
redirect to a second script passing the order reference in the URL. On the second script put in a form with hidden fields cotaining only the details required by your payment processor and some javascript to submiot the form automatically and a message to the user like 'Connecting to Paypal...'
If you are using merchant services to authorize the payment
before you generate output from the landing script, send the details to your authorizer using (e.g.) curl and parse the response, record the response against the order in the database and output a suitable message to the customer via the web page

How to retrieve HTML and variables with jQuery/Ajax and PHP

I have an HTML form which uses selections from a drop-down list to populate a mySQL table, but with jQuery / AJAX calling an external php file to update the display of entered lines below the original form.
The purpose of the form is an order entry system, and as such works: select an item, see it added to the list. The problem that I have is that as well as having the entered items displayed, I want to show the total order value updating. I thought that I would be able to use a PHP session variable, but that doesn't seem to work unless the original page is refreshed.
Therefore, my question is: is there a way to get session variables (or any other sort of variable) back from my external php file as well as the HTML that I am appending to the displayed page?
If it helps this is the code that I'm using to call the external php when adding a new row:
$.ajax({
type: "POST",
url: "ajaxInsertOrderLine.php",
data: dataString,
cache: false,
success: function(html){
$("#orderItems").append(html);
document.getElementById('inputStockNo').value='';
document.getElementById('qty').value='';
document.getElementById('totalAmount').value="<?php echo $_SESSION["totalValue"]; ?>";
}});
where "ajaxInsertOrderLine.php" is the external file, 'inputStockNo' and 'qty' are two form variables being sent to the script and zeroed after a successful insertion.
You can pass many values back to your jQuery script in the form of an array. For instance, I could pass the following:
session_start(); // necessary for getting/setting SESSION data
print json_encode(array(
"username" => $_SESSION["username"],
"msgCount" => 0,
"userHTML" => "<p>There are no new messages</p>";
));
Then from your jQuery code, you'll use the JSON method of data-retrieval:
$.post("page.php", {}, function(results) {
alert(results.username + " has " + results.msgCount + " messages.");
$("messages").append(results.userHTML);
}, "json");
Why not just scrap the session variable idea - do the total order value calculation on the server in the php page and just send back the value along with item you're adding to the list?
you could return a Json object (maybe using getJSON) containing the two different variables you want to retrieve, one being the html to append and ther other being the total order value.
I found a script here: Javascript Session Variables which does what I want, and may help anybody else who is looking to use session variables with AJAX.

Categories