I am building a management system in which the admin can select an item from the database table and update the details. To achieve this I have two forms on two pages. The first form is to select the item from table and pass it's ID to the second page where I will use the ID to fetch the details from the table using php. I want to do this with javascript so it will not refresh the page. My question is how to pass this value? I am using the following code, but it is not working.
HTML
<div id="result"></div>
<form action="update_item.php" id="update" method="post" >
<select name="selected" class="form-control" id="myItem" required>
<option>Select item</option>
<?php
<!-- PHP script to select the item -->
?>
</select>
<button id="submit">Select</button>
</form>
JAVASCRIPT
$(document).ready(function() {
$("#submit").click(function() {
var chat = $('#myItem').val();
if(chat=='')
{
alert("Please select an item!");
}
else{
$.ajax({
type: "POST",
url:"update_item.php",
data:{
data:chat,
},
success: function (msg) {
//alert(msg):
$('#result').html(msg);
},
error: function(){
alert('error');
}
});
}
});
});
PHP
Second page
$item_id = $_POST['data'];
$get_item = "select * from items where item_id='$item_id'";
<--PHP script continues-->
You can add a hidden field and send this input back to your server:
<input type="hidden" name="something" value="<?= $_SERVER['id'] ?>" />
And then access it with via:
$_SERVER['id']
If you are not changing the page between forms you should be able to just create a variable on the client side that stores the necessary data. Since the second form is loading into the same environment, any variables you have from the first form will still exist.
From your example, I'm guessing chat is the data you're trying to use in the second form. Right now it is local to the click function (once that function completes the variable disappears). You could either move the declaration of that variable into the global scope (outside of document.ready), or use it as intended inside the success callback. (From your example it is unclear what you are trying to do with this data)
Related
I have a table from which I am successfully passing values into the textfields in modal. However, I need to create the select dropdown within modal, which will be based on value passed from the row.
Table
edit | ref. number |
.edit_record button | AAA01 |
js
$(document).ready(function () {
$('.edit_record').on('click', function() {
$('#edit_record_modal').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
$('#ref').val(data[1]);
});
});
modal
<div class="form-group">
<input id="ref" type="text" name="ref" class="form-control">
</div>
<div class="form-group">
<select name="selectDate" id="selectDate" onchange="">
<?php
$ref_list_result= mysqli_query($db_conn,"SELECT ref_no FROM record WHERE
caller_number= /*the value of row*/");
while ($row = mysqli_fetch_array($ref_list_result)) {
$ref_no = $row['ref_no'];
?>
<option value=<?php echo $ref_no ?>><?php echo $ref_no ?></option>
<?php } ?>
</select>
</div>
Is it possible to pass that value from #ref textfield into the php variable, so I can compare it against condition in SQL's WHERE clause? Perhaps, maybe there is a different way to do this?
Short Answer: You cant pass variables in PHP and JavaScript unless you are using an API to transfer data
Long Answer:
If you only know how PHP works, it is what is called a "Pre-templater" which means that in the server, or somewhere it is deployed, the server translates PHP codes into HTML and JavaScript depending on your echo. This means that by the moment the code you've written gets sent to the browser, it is all HTML, JS and CSS.
Alternative Approach: You could try building an API using PHP, and use AJAX to modify the dropdown. Search the following in google "PHP API" and "AJAX Call On PHP".
I have the following HTML code:
<html>
<!-- assume jquery is loaded -->
<body>
<form id="sform" method="get" style="display:none;">
<input type="hidden" name="eid" />
<input type="hidden" name="returnURL" />
<input type="hidden" name="returnID" value="ieid" />
<select id="dropdownlist" name="ieid">
<option selected="selected"></option>
</select>
</form>
</body>
</html>
What happens is the user enters an email address, it checks (server-side with PHP) the credentials and if valid, returns the following JSON object (in this case, assume that the values are valid urls (ie. http://sitehere.com/somethingelse):
{
"get_action" : "geturl",
"eid" : "eidurl",
"return_url" : "returnurl",
"option_url" : "optionurl"
}
This is retrieved when the user hits the login button on the home page. This button triggers a POST request which retrieves the results and parses the JSON into the form above. I then change the values of the form from the original code and the action of the form itself before submitting the form. This is shown below.
$.post('/?c=controller&a=method', {'email' : $('input[name="email"]').val() }, function(data){
var result = $.parseJSON(data);
$('#sform').change_action(result.get_action);
$('input[name="eid"]').change_val(result.eid);
$('input[name="returnURL"]').change_val(result.return_url);
$('select[name="ieid"]').find('option:selected').change_val(result.option_url);
$('#sform').submit();
};
Where change_val() and change_action() are defined like this:
$.fn.change_val = function(v){
return $(this).val(v).trigger("change");
}
$.fn.change_action = function(v){
return $(this).attr('action', v).trigger("change");
}
The reason why I defined these functions was because originally, I had just been calling val('new value'); and the form seemed to not be updating at all. I read that I had to trigger a change when using jQuery to update the form before submitting it.
However, even after triggering a change, it seems like the HTML still isn't updated (at least in Chrome) and the form is not being submitted correctly because none of the values are actually changing.
So, I need to be able to take a parsed result, update the values in the form (with specific id's), and then submit the form so that it re-directs somewhere. Is there a way to do this correctly?
I need to get the value of a post variable from a form and transform this to a PHP variable to use it on the same page without reloading it
Actually I got this :
$(function() {
$("#submit_post").click(function() {
var select = $("select").val();
$.post("process.php",{select:select},function(result){
$('#result').append(result);
});
});
})
And
<form method="post">
<select name="select" id="select">
<option value="1">Test</option>
</select>
<input type="submit" id="submit_post" value="Envoyer" onclick="return false;"/>
</form>
<div id="result"></div>
When I do :
<?php var_dump($_POST["select"]); ?>
I got : null
But on div result I got : 1
...
I need to lake this "1" a php variable
Your code runs fine on my server. Maybe you aren't totally clear on the function of the superglobals.
If the "result" div contains "1" after you press the button, then that means process.php is correctly receiving your POST request and echoing back the value of $_POST["select"]. You will get "NULL" if you try to just navigate your browser to process.php, because when you do so you are making a separate request which doesn't contain any POST variables. The superglobal arrays don't persist between different calls to process.php unless you create that functionality using $_SESSION, a DB, or some kind of text/json/xml storage system. The following changes to your PHP will allow you to click your button and then separately navigate to process.php and see your data:
<?php
session_start();
if ($_POST["select"]) {
$_SESSION["data"] = ($_POST["select"]);
}
var_dump($_SESSION);
?>
Please correct me if I have made the wrong assumptions and this is not helpful.
-Ben
I'm new to Laravel and I'm trying to learn how to create a dynamic drop down box where the 2nd drop down box will change depending on what is selected in the 1st one.
Here is my form code inside my blade file:
{!! Form::open(array('url'=>'', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
#for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
#endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}
Here is my AJAX code (also inside the blade file but in <script> tags:
<script>
$('#cinema').on('change', function(e){
console.log(e)
window.alert("On Change");
var cinema_id = e.target.value;
//ajax
$.get('/ajax-subcat?cinema_id=' + cinema_id, function(data){
//success data
console.log(data);
window.alert("On Success");
$('#sesh').empty();
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value=""' + subcatObj.id +'">'+subcatObj.name+'</option>');
});
});
});
</script>
And finally here is my route:
Route::get('/ajax-subcat', function(){
$cinema_id = Input::get('cinema_id');
$sessions = Session::where('cinema_id', '=', $cinema_id)->get();
return Response::json($sessions);
});
So this code is not generating any data and is instead giving me a 404 error.
I have verified that the AJAX code does go inside the "change" function, through alerts, however it is not showing the 2nd alert. In my limited understanding, I feel like there may be an issue in my routes file? As if the route file is returning data, the next function in AJAX should be running.
One thing I don't understand in the routes code is what Input::get('cinema_id') is doing. I think it's grabbing what the user input in the drop down box?
Since it's giving 404 error, I hope using full url will solve this. Use
//ajax
$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
//success data
Add header in your ajax call
headers : {
'csrftoken' : '{{ csrf_token() }}'
}
Seems like theres a few things going on here. It's important to separate what is happening on the on the server with Laravel, and in the client with your Javascript.
SERVER
Sends the form with data in it. Any blade syntax you use like this.
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
Is rendered on the server before it is sent to the client. That is how the first drop down is being populated with data when you load the page.
CLIENT
Looks like your using AJAX to make request based on users selection from the first drop down. This line:
$.get('/ajax-subcat?cinema_id=' + cinema_id, ...
Is going build request to your Route::get('/ajax-subcat', ... along with a query string. ?cinema_id=1. Input::get('cinema_id'); should take the value of the query string (1).
It looks like you've set up the the route correctly so I'm thinking its a problem with var cinema_id = e.target.value;. I'd check it's value before the request is made and make sure it lines up with the value that your query on the server is going to need.
The value of var cinema_id on the client, is going to be the value of $cinema_id on the server for your query.
Hope this helps,
Matt
Change
uploadUrl: '{{route("product/create")}}',
to
uploadUrl: '{{url("product/create")}}',
and add this in ajax
headers: {
'X-CSRF-Token':{{ csrf_token() }},
},
I currently have a simple php/html page with only one form, where the user inputs a number, then the page loads itself (but this time with parameters).
Some key codelines :
<form action="index.php" method="get">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (!isset ($_GET["name"])) {
echo "<div> Adding some content related to the input </div>";
}
?>
Now i'm looking forward adding 3 more fields, and split my page for each form.
The user should be free to use the 4 forms separately, I don't want to have the page reload every time. I'm unsure how to design this page - should i rework my page and work with JS ?
I have basic knowledge with PHP, a little with JS. I will be able to google up most things i need but first i need a proper direction :) thanks !
you can use AJAX for this purpose...
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
AJAX is a must if you don't want the page to reload between each interaction.
If you have trouble with it and want to opt for just PHP (with page reloads) you can handle multiple forms on one page easily enough - my preferred method is to set a hidden value in the form called 'action' settings its value & reading this in again when the page loads for example:
<?php if(isset($_POST['action']))
{
$action = $_POST['action'];
switch ($action)
{
case 'hello':
echo 'hello';
break;
case 'bye':
echo 'bye';
break;
}
}
?>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="hello"/>
<input type="submit" value="hello"/>
</form>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="bye"/>
<input type="submit" value="bye"/>
</form>
You could then save and echo out the values for each form each time keeping them updated as the user interacts with each of the forms.
AJAX is the nicer solution however
If you do not want to reload the page every time you submit each form then you should use Ajax for calling your api. You write the separate api in PHP, and then call that api in Jquery's Ajax.
Here the page won't be reloaded. Also you can call the ajax on each of the button click.