Is there a way to make a form submit twice? - php

I'm loading values from an XML file and then updating the XML with a form on a php page. My problem is this - I have a query running a count on nodes, which works perfectly fine, but I also want to update nodes with the count and get accurate values back. When I submit my form, it submits the values as they are when I load the file, but in order to update the count properly (because I need the updated node count) I need to have it submit twice. I've tried to have it submit the form on a body onload function but from what I can ascertain when you hit the submit button it doesn't do a true full page refresh. It reloads the page but I've been unable to have it actually run any scripts or onload functions. The alternative that I thought of but can't figure out how to implement is having the count go down if I change the option value to closed.
<!DOCTYPE html>
<?php
$xml->load('test.xml');
$xpath = new DOMXpath($xml);
$liftsopen = $xpath->query("//node/Lifts-Open")->item(0);
$lift1status = $xpath->query("//areas/area[#name='Lift1']/lifts/lift[#name='Lift1']/#status")->item(0);
$lift2status = $xpath->query("//areas/area[#name='Lift2']/lifts/lift[#name='Lift2']/#status")->item(0);
$liftcount = 0;
foreach ( $xpath->query('//lifts/lift[#status="OPEN"]') as $count1 ) {
$liftcount++;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$lift1->nodeValue = $_POST['lift1statusform'];
$lift2->nodeValue = $_POST['lift2statusform'];
$liftsopen->nodeValue = $liftcount;
$xml->save('test.xml');
}
?>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h4>Lift1</h4>
<select name="lift1statusform" >
<option selected value="<?= htmlspecialchars($lift1status->nodeValue) ?>"><?= htmlspecialchars($lift1status->nodeValue) ?></option>
<option value="OPEN">OPEN</option>
<option value="CLOSED">CLOSED</option>
</select>
<h4>Gondola</h4>
<select name="lift2statusform" >
<option selected value="<?= htmlspecialchars($lift2status->nodeValue) ?>"><?= htmlspecialchars($lift2status->nodeValue) ?></option>
<option value="OPEN">OPEN</option>
<option value="CLOSED">CLOSED</option>
</select>
<input name="submit" type="button" value="Save"/>
</form>
</body>
</html>
used the following Ajax function to submit the form twice:
function Test() {
var form = $('form');
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
location.reload(true);
}
});
}
});
}

Would AJAX be a valid solution to your problem?
If you need to perform multiple "form submits", you should check out the capabilities of AJAX. Ajax allows you to send exchange data with a back-end PHP file without leaving (or even refreshing) the current page. Perhaps it is your solution.
As with most js actions, it can be event-driven (that is, triggered one-or-more-times by some event), or repeated inside a loop, etc.
AJAX is most implemented using the jQuery library:
$(document).ready(function(){
$.ajax({
type: 'post',
url: 'my_backend_file.php',
data: {varname:value}
}).done(function(recd){
console.log('data recd from PHP side, if needed: ' + recd);
});
});
although it is equally well handled in vanilla js also.
References and Other Examples:
https://stackoverflow.com/a/54332971/1447509
Should I have one form or two separate forms
https://www.html5rocks.com/en/tutorials/file/xhr2

Related

my ajax submit onchange select is working on the first row only

I have an HTML table that has a column with select options that submits using onchange event using ajax.
the code works perfectly for the first row of each page (since pagination is applied on the table) but any other row is useless.
I had submitted a question related to this matter earlier and I stumbled on this question by chance that thankfully helped me a lot but not for the entire table.
this is the original Q&A link:
Submit form on select change via AJAX
my customized HTML code
<td>
<form action="" method="POST">
<select class="changeStatus" name="changeStatus" style="margin-bottom:10px;">
<option value="<?php echo $row["STATUS"]; ?>" > <?php echo $row["STATUS"]; ?></option>
<option value="new">new</option>
<option value="checking">checking</option>
<option value="processing">processing</option>
<option value="done">done</option>
</select>
<input class="order_Id" type="hidden" name="order_Id" value="<?php echo $row["ORDER_ID"];?>"/>
</form>
</td>
ajax code
<script>
$(document).ready(function() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'post',
url: 'test2.php',
data: {selectFieldValue: $('select.changeStatus').val(), order_Id: $('input[name$="order_Id"]').val()},
success: function(html){alert('Select field value has changed to' + $('select.changeStatus').val()); },
dataType: 'html'
});
});
});
</script>
note:the alert is only echoing the first row vlue as well.
php code
<?php
$connection = mysqli_connect('localhost' , 'root' ,'' ,'project_name');
$changeStatus=$_POST['selectFieldValue'];
$id=$_POST['order_Id'];
$sql='UPDATE new_order SET STATUS="'.$changeStatus.'" WHERE ORDER_ID ="'.$id.'"';
$result = mysqli_query($connection, $sql);
?>
I have searched for days and this was my one and only successful code so far.
thanks in advance
When handling an event for multiple objects, you need to be careful to handle only the object the event was fired on.
In your case you have an event callback on every select with the class .changeStatus. When any of those are changed, you post with the data
selectFieldValue: $('select.changeStatus').val()
Since $('select.changeStatus') gives you an array of all objects matching the selector, and .val() only returns the value for the first object in the array, you're effectively handling the first row only no matter which row was changed. Instead you need to use
selectFieldValue: $(this).val()
with this referring to the object the event was fired on.
Same goes for your alert; change $('select.changeStatus').val() to $(this).val().
Final script with those changes would be:
<script>
$(document).ready(function() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'post',
url: 'test2.php',
data: {selectFieldValue: $(this).val(), order_Id: $(this).siblings(".order_Id").val()},
//***only select that rows .order_Id by using $.siblings() with selector
success: function(html){alert('Select field value has changed to' + $(this).val()); },
dataType: 'html'
});
});
});
</script>

Pass JQuery variables to PHP variable [Simple]

I've read lots of threads on passing Jquery variables to PHP, however almost all of the posts were on the "Expert" level, and i couldn't understand a single thing (PHP/Jquery beginner here). Hopefully I can get some help.
Once the user selects from the drop down list, the script function will run. I want to get the user's selection from jquery to a php variable. From then, I want to use the user's selection to retrieve data from the database and display values on the same page itself.
I'm not getting any output.
EDITED: So this is what I did after looking at the ajax function
AFile.php
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#company').change(function(){
$.ajax({
type: 'GET',
url: '<?php echo url_mgt::getTest(); ?>',
data: 'company_name=' + $('#company').val(),
success: function(msg) {
$('#other').html(msg);
}
});
});
});
</script>
</head>
<body>
<select id="company" name="company">
<option value="Company_A">A</option>
<option value="Company_B">B</option>
<option value="Company_C">C</option>
<option value="Company_D">D</option>
</select>
<div id="other"></div>
</body>
companyArray.php
<?php
require('protect.php');
require_once(dirname(__FILE__) . '\..\controller\company_controller.php');
require_once(dirname(__FILE__) . '\..\controller\url.php');
$companyCtrl = new company_controller();
$compArray = $companyCtrl->retrieveAllCompany();
if($_GET['company_name']) {
$get_comp = $_GET['company_name'];
$inSpace = str_replace("_"," ", $get_comp);
foreach($compArray as $company) {
$comp_name = $company->getCompanyName();
if($get_comp == $company) {
$comp_add = $company->getCompanyAddress();
echo $comp_add;
}//end if
}//end foreach
} //end if
?>
I inspected element, but when i click on the drop down list nothing happens, i doubt its going to the companyArray.php. I also don't think its the url_mgt::getTest() link because ive been using this url pattern throughout the project.
use Ajax request on change and then populate the received values from the server on success and you can do what you are asking for.
note: you can't pass a variable from client side (js) to server side (php) without sending it as a request.
You aren't concatenating your data.
'company_name=' $('#company').val(),
should be
'company_name=' + $('#company').val(),

How to write PHP code inside jquery for retrieving values from mysql database?

I am trying to get the values for the next drop-down from a database, which will be dependent on two previous drop-downs. The values for first two drop-downs are listed in the file itself. I want the second drop-down to be enable after selecting values from first, and similarly for third after second. Kindly help.
HTML code below:
<form>
<select id="branch" name="branch" class="form-control" onchange="showUser(this.value)">
<option value="">Select</option>
<option value="1">Civil</option>
<option value="2">Computer</option>
<option value="3">Mechanical</option>
<option value="4">Electronics and Telecommunications</option>
<option value="5">Electrical and Electronics</option>
<option value="6">Information Technology</option>
</select>
<select id="semester" name="semester" class="form-control" disabled>
<option value="1">I</option>
<option value="2">II</option>
<option value="3">III</option>
<option value="4">IV</option>
<option value="5">V</option>
<option value="6">VI</option>
<option value="7">VII</option>
<option value="8">VII</option>
</select>
</form>
jquery is:
<script>
$(document).ready(function(){
document.cookie = "s =hello" ;
console.log('hello');
$("#semester").attr("disabled", true);
$("#branch").change(function(){
$("#semester").attr("disabled", false);
$b = $('#branch').val();
$("#semester").change(function(){
$s = $('#semester').val();
$("#sub_code").attr("disabled", false);
console.log($s);
if($s!=1||$s!=2)
$s = $b+$s;
<?php
$s= $_COOKIE['s'];
$sql = "SELECT * FROM subjects WHERE sem_code=`$s`";
?>
});
});
});
</script>
I did not run the query since it is not assigned properly yet.
You can't include php code in javascript , the first is executed on the server side, the second is executed on the client side which means that you can't re-execute only if you resend a request to the server, obviously this is usually done by submitting forms, BUT sometimes -like in your case- we don't want to reload the whole page for each request ! and for this purpose we use AJAX
ajax sends post/get request to a specified php page which does the desired server-side tasks (updating data in the database, selecting some results from database, dealing with sessions maybe, etc...)
try something like this:
var pathurl='/path/to/your/php/file';
var params={}; //the parameters you want to send
params['semester']=$s;
var requestData= $.ajax({
type: 'POST',
url: pathurl,
cache: 'false',
data: params,
dataType: "json",
beforeSend: function () {
//here you can begin an animation or anything...
},
complete: function () {
//here you can stop animations ...
},
success: function (response) {
console.log(response); //check your console to verify the response
//loop other elements inside response
$.each(response, function (index, resultArray) {
//do something : in your case append to dropdown a new option
});
}
});
requestData.error(function () {
alert("error");
});
you should create a php file with the path specified in the above code, and there you can extract what you need from the database table, store values in an array and finally use:
echo json_encode($resultArray);
hope this was helpful

Send data in Ajax response

hey I am trying to populate one select dropdown on the basis of another one using ajax. I have one select populated with portfolios and the 2nd one is empty. when I select an option from the 1st select box. I call an ajax function in which I send the selected portfolio id, In the ajax method I find the groups for the selected id, how can I populate the 2nd select with the groups I found. My code is
The form which contains two selects
<form name="portfolios" action="{{ path('v2_pm_portfolio_switch') }}" method="post" >
<select id="portfolios" name="portfolio" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio</option>
{% for portfolio in portfolios %}
<option get-groups="{{ path('v2_pm_patents_getgroups') }}" value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
{% endfor %}
</select><br/><br/>
<select id="portfolio-groups" name="portfolio-groups" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio Group</option>
</select><br/>
</form>
The JS
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//want to populate the 2nd select box here
}
});
});
});
</script>
Controller method where I find the groups for the selected portfolio
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
return $portfolio_groups;
}
}
Any idea how can i send the portfolio groups and populate the 2nd select
thanks in advance
Use getJson instead of ajax();
Json (JavaScript Object Notation) , is the most easiest way to send structured data between php and javascript.
I Assuming here that the controller respond directly to the ajax query and that $portfolio_groups is an associative array with "id" and "name" as keys or an object with this same properties.
In your PHP controller send json data:
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
echo json_encode($portfolio_groups);
}
}
Then use getJson to retrieve data and iterate over it :
$.getJSON(url, data, function(result) {
var options = $("#portfolio-groups");
$.each(result, function(item) {
options.append($("<option />").val(item.id).text(item.name));
});
});
Have a look to the getjson documentation for more detail about it
Check out this XML tutorial (someone out there is going to flame me for linking to w3schools) it's a good start.
AJAX requests are, in VERY broad terms, calls which make a browser open a window that only it can see (not the user). A request is made to the server, the server returns a page, the script that made the request can view that page. This means that anything which can be expressed in text can be transmitted via AJAX, including XML (for which the X in AJAX stands for).
How is this helpful? Consider, if you are trying to populate a drop down list, you need to return a list of items to populate it with. You COULD make an ajax call to a page http://www.mysite.com/mypage.php?d=select1 (if you are unfamiliar with GET and POST requests, or are a little in the dark regarding the more utilitarian aspects of AJAX, another full tutorial is available here) and have it return a list of items as follows:
item1
item2
item3
...
And scan the text for line breaks. While this certainly would work for most cases, it's not ideal, and certainly won't be useful in all other cases where AJAX may be used. Instead consider formatting the return in your PHP (.NET, ASP, whatever) in XML:
<drop>
<item>item1</item>
<item>item2</item>
<item>item3</item>
</drop>
And use Javascripts built in parser (outlined here) to grab the data.
What I would do is to use the $.load() function.
To do this, your getgroupsAction should return the options html.
The JS:
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
// Perhaps you want your select to show "Loading" while loading the data?
$('#portfolio-groups').html('<option selected="selected" value="default">Loading...</option>');
$('#portfolio-groups').load(url, data);
});
});
</script>
I don't know how $portfolio_groups stores the data, but let's say you'd do something like this in your response:
<?php foreach($portfolio_groups as $p) : ?>
<option value="<?php echo $p->value ?>"><?php echo $p->name ?></option>
<?php endforeach ?>
This way, the select will be filled with the options outputted by getgroupsAction.
The easiest way would be to return json string from your controller and then process it in the 'success' call of the $.ajax.
Lets assume, that your $portfolio_groups variable is an array:
$portfolio_groups = array('1'=>'Portfolio 1', '2' => 'Portfolio 2');
then you can return it from controller as json string like this:
echo json_encode($portfolio_groups);
Then in your jQuery ajax call you can catch this string in the response (the 'success' setting of the $.ajax). Don't forget to add setting dataType: 'json'
Roughly, your $.ajax call will look like this:
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
dataType: 'json', // don't forget to add this setting
success: function(data) {
$.each(data, function(id, title){
var node = $('<option>').attr('value', id).html(title);
// this will simply add options to the existing list of options
// you might need to clear this list before adding new options
$('#portfolio-groups').append(node);
});
}
});
Of course, you will also need to add the checks if the data is not empty, etc.
Supposing that the function getgroupsAction stays in a flat php controller ( not inside a class ) you should tell the server to execute the function
so at the end of file being called by ajax you should barely call the function first ( probably you did it! )
For your patents group result set, you can generate the select by php or by javascript
In first case you should do this:
//php
$options = getgroupsAction($_REQUEST);
$return = "<select name =\"name\" id=\"id\"><option value=\"\"></option>";
foreach( $options as $option){
$return.= "<option value=\"$option\">$option</option>";
}
$return .= "</select>";
echo $return;
Then in Javascript:
// javascript
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//inside data you have the select html code so just:
$('#divWhereToappend').append(data);
},
error: function(data) {
//ALWAYS print the error string when it returns error for a more easily debug
alert(data.responseText);
}
});

Get MySQL Record using Php & JQuery

Here's my scenario:
I have a drop down menu, with different values. When option 'A' is chosen, I want it to use JQuery to call a Php script. That Php script will make a database query which returns a record ID. When that record ID is returned to the javascript, javascript will direct the browser to a particular URL based on the returned ID (i.e. /products/$ID)
Right now, I have it so that the dropdown menu triggers a javascript function. I also have the Php script that does the database work. Im just not sure what should go in the javascript function, or how to make it connect with he Php script, and how I get the returned data (and how to deal it with the return type -- xml, html, etc)
Im using JQuery library, and Php 5.x.
A simple example would be to take a form like
Example.php
<form id="form" name="form">
<select name="dropdown" id="dropdown">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<input type="submit" id="submit" name="submit" value="Submit!" />
</form>
Then link it with some JQuery to intercept the form, and send it to a PHP file
JQuery.js
$(document).ready(function(){
$("#dropdown").change(function(event) {
$.ajax({
type: "POST",
url: "query.php",
data: $('#form').serialize(),
datatype: "json",
success: function(data){
var ret = jQuery.parseJSON(data);
// Redirect to ret.link
}
});
event.preventDefault();
});
});
Then, create the PHP file to interpret it
query.php
$stmt = $sql->dbh->prepare("SELECT `Link` FROM `Links` WHERE `ID` = :id");
$stmt->bindValue(':id', $_POST['dropdown']);
$stmt->execute();
$link = $stmt->fetch()['Link'];
echo json_encode(array('link' => "{$link}"));
die();
$("#menu-item").click(function() {
jQuery.ajax({
type: "POST",
url: "yourScript.php",
data: "data=foo",
success: function(response){
//redirect to id using response
window.location.replace("http://yoursite.com/products/" + response);
}
});
});
Of course, this will need to be customized to your unique situation.

Categories