How to make a search form using jquery and razor - javascript

I have made an CRUD application using webmatrix. I am using jquery and razor syntax. As I am still learning, took me long to figure out how to use jquery and implement it in my asp.net.
Below is the code I have done:
$('#grid').click({
function () {
$.ajax({
type: "POST",
//javascript code here
</script>
</head>
<body>
input type="text" name="fname"><<input type="button" value="Submit form">
<div id="grid" class="ui-widget">
#RenderPage("~/Partials/Recipient.cshtml")
</div>
I am interested in a way where when I click the submit button the value in my text box is posted to my Recpient.cshtml and executed, Then it is rendered underneath the search.
I am stuck here where I need to post the input value to Partials/Recipient.cshtml.

First you configure your ajax call (which would send the value of your fname input field as a POST parameter to your Recipient.cshtml script), then process Recipient.cshtml output on success.
It should look like:
$.ajax({
url: "Partials/Recipient.cshtml",
type: "POST",
data: { fname: $('input[name$="fname"]').val() }
success: function(ajaxoutput)
{
//dosomething();
}
});
More info: http://api.jquery.com/jQuery.ajax/

Related

How to get the HTML select option in AJAX and pass to PHP

On a dropdown option, I would like to listen in and get the value of the option selected by the user.
Then I would like to pass this value to a PHP variable for use in the later part of the blade view PHP script.
I do not want to reload the page hence from the online look, I found ajax to be the only possible way.
I tried to implement as shown below but hitting a snag as the page loads on submit.
Even better is it possible to have a select option drop down that you get the selected value without submit?
My HTML code:
<form id="myForm">
<div class="button dropdown">
<select name="languageSelected" required="required" id="languageselector">
<option value="">Select the language</option>
#foreach($reviewForm_language as $lang)
<option value="{{$lang->id}}">{{$lang->name}}</option>
#endforeach
</select>
</div>
<input id="ajaxSubmit" type="submit" value="Select"/>
</form>
The JavaScript code:
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
jQuery('#languageselector').on('change', function(){
jQuery.ajax({
url: "{{ url('/selected/id') }}",
method: 'post',
data: {
id: $(this).val(),
},
success: function(result){
jQuery('.alert').show();
jQuery('.alert').html(result.success);
}
});
});
The PHP code to pick the selected language id
<?php
$langId = request()->get('languageSelected');
?>
My route code;
Route::post('/selected/languageId', 'ProfileController#selectedLangId');
My controller Code;
public function selectedLangId(Request $request)
{
return response()->json(['success'=> $request->id]);
}
I am learning AJAX, and for some reasons the page loads. Anyone kindly guide me?
Try changing the request parameter from id to languageSelected :
<script>
jQuery('#languageselector').on('change', function(){
jQuery.ajax({
url: "{{ url('/selected/languageId') }}",
method: 'post',
data: {
languageSelected: $(this).val(),
},
success: function(result){
jQuery('.alert').show();
jQuery('.alert').html(result.success);
}
});
});
</script>
And get to input (since you sent a post, not a get) :
<?php
$langId = request()->input('languageSelected');
?>
Reloading the page is normal behavior for an input of type submit. If you do not want this default behavior, you can change your input type to button like so: <input type="button"/>, or just use a button element like so: <button type="button"></button>.
If I understand it correctly, then it's not possible, what you're trying to achieve. PHP is rendered server-side, - which means that if you're fetching a variable through AJAX, - that you can't 'put that into a PHP-variable', since that PHP-variable can only be populated on the server.
So once you've fetched the value using AJAX, then you would have to do the rest using JavaScript/jQuery, - or having to reload the page.
It looks like that you're trying to make an on-page language-selector. Even though it would be a neat feature to be able to change the language of a page without reloading the page, then I wouldn't recommend you of doing it. The reason being, that that would slow your page down significantly, since all languages would have to be loaded on all pages.
... And also; as a developer, a language-switcher is something that is being toggled and played with, since we (developers) have to check all languages and features on a page. But regular users never even touch it. They only use it, if your site incorrectly identifies which language the visitor prefers (a malfunction, if you will). Ideally, your site should show the same language that the visitors browser uses or based on geo-location.
So it sounds like you're spending time on a feature, that I wouldn't, if I were you.
If you do insist on continuing what you've started, then I would modify my jQuery-code, so it doesn't only do something on success, but also if it hits and error, so you can see if you actually receives a value from your AJAX-request. This answer does it nicely.
Remember that you shouldn't need to press 'Submit' in order get the AJAX-response. Pressing 'Submit' will always submit the form (and reload the page), unless you unregister/unbind that function; and in that case, then you might as well not use a form at all.
If you replace your submit-button with a regular-button and bind that to the jQuery-function, that would be a good way of doing it:
<form id="myForm">
<div class="button dropdown">
<select name="languageSelected" required="required" id="languageselector">
<option value="">Select the language</option>
#foreach($reviewForm_language as $lang)
<option value="{{$lang->id}}">{{$lang->name}}</option>
#endforeach
</select>
</div>
<buttom id="ajaxSubmit" type="submit" value="Select" />
</form>
$(function(){
$('#ajaxSubmit').click(function() {
jQuery.ajax({
url: "{{ url('/selected/id') }}",
method: 'post',
data: {
id: $(this).val(),
},
success: function(result){
jQuery('.alert').show();
jQuery('.alert').html(result.success);
}
});
});
});

jQuery Ajax loop on form submit

New to Ajax, however, I can't figure out what is wrong, and I assume its the Javascript. My php page is working just fine, however, with this code my login Html simply refreshes over and over with the end of the url changing to ?username=whatIenter&password=whatIenter
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('#login_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/lib/login.php',
data: $(this).serialize(),
success: function(data)
{
alert("WORKED");
}
});
});
});
</script>
HTML
<form id="login_form" action="" method="POST">
<input type="text" id="user" name="username">
<input type="password" id="pass" name="password">
<button id="loginButton" class="login_submit" type="submit" >Login</button>
</form>
First of all, which jQuery version are you using?
Your code is working fine with jQuery 3.3.1
Always keep in mind this good practices:
Disable the cache on your browser while you develop
Each time you wanna check your site, open the browser console and then press F5
Javascript code always needs to stay at bottom inside body tag (just before </body>)
This also apply in the case you put it on a separated file (recommended)
Set the action parameter on your form, this can prevent unexpected errors
Even if you are gonna call the same file or url
Try:
var header = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
};
var request = $.ajax({
url: '/lib/login.php'
,data: $(this).serialize(),
,headers: header
});
request.done(function(response) {
alert("WORKED "+response);
});
The thing is, some/most API's will require you to explicitly specify the content type, before they return the "standard" HTTP response that your Javascript will read.
Resources:
https://web.archive.org/web/20210816145541/https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

Post Method to URL from a onclick function

I need help on something that sounds easy but is difficult for me.
So when someone clicks on this div:
<div onclick="<go to url sending data using the post method>">Click Me</div>
I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.
If you need to use div you can do it like this but I suggest that you use button or input of type submit.
<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>
Also you may use jQuery or some other JS library.
NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.
Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.
//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="someInput">
<div onclick="sendData()">Click Me</div>
<script>
function sendData(){
//get the input value
$someInput = $('#someInput').val();
$.ajax({
//the url to send the data to
url: "ajax/url.ajax.php",
//the data to send to
data: {someInput : $someInput},
//type. for eg: GET, POST
type: "POST",
//datatype expected to get in reply form server
dataType: "json",
//on success
success: function(data){
//do something after something is recieved from php
},
//on error
error: function(){
//bad request
}
});
}
</script>
You can use <form> to send data
<form action="yourpage.php" method="post">
//form contents
<input type="submit" value="Submit">
</form>
The action URL specifies the URL of the page to which your data has to be send.

Get the return value of a HTML Form Post method

I have a HTML form in a Mason component(A.m) that uses the post method to call another Mason component(B.m). I want this Mason component(B.m) to return a value to the HTML form in the Mason component(A.m). Then I want to pass this returned value to a Javascript function.
How can I do this? I'm new to web development.
You need to make an AJAX request. Although not strictly necessary, I would suggest you to use jQuery, it will make things a lot easier. Please also have a look at this question: jQuery AJAX submit form
Here's a little example in Mason, it's very simplified of course, you should add some error checking and some escaping also, but I think it could be a good start. Your A.mc component could look like this:
<html>
<head>
<title>This is A</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#myform").submit(function() { // intercepts the submit event
$.ajax({ // make an AJAX request
type: "POST",
url: "B", // it's the URL of your component B
data: $("#myform").serialize(), // serializes the form's elements
success: function(data)
{
// show the data you got from B in result div
$("#result").html(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form
});
});
</script>
</head>
<body>
<form id="myform">
<input type="text" name="mytext" />
<input type="submit" />
</form>
<div id="result"></div>
</body>
</html>
it's just an HTML page that loads jQuery library and that contains your form, and that contains some code to instruct the form to make an AJAX request to B component when the user clicks the Submit button and then to show the contents returned by B component in your result div.
And this could be your B.mc component:
<%class>
has 'mytext';
</%class>
I got this text <strong><% $.mytext %></strong> from your form,
and its length is <strong><% length($.mytext) %></strong>.
Result will be like this:

Execute a python script on button click

I have an HTML page with one button, and I need to execute a python script when we click on the button and return to the same HTML page with the result.
So I need do some validation on return value and perform some action.
Here is my code:
HTML:
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue"></button>
JS:
function validate(){
if (returnvalue=="test") alert(test)
else alert ("unsuccessful")
}
What my python code is doing is some validation on the name entered in the text box and gives the return status.
But I need the result back on the same page, so I can do the form submission later with all the details. Any help will be appreciated
You can use Ajax, which is easier with jQuery
$.ajax({
url: "/path/to/your/script",
success: function(response) {
// here you do whatever you want with the response variable
}
});
and you should read the jQuery.ajax page since it has too many options.
Make a page(or a service) in python, which can accept post or get request and process the info and return back a response. It is better if the response is in json format. Then you can use this code to make a call on the button click.
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){
$.ajax({
type:'get',
url:<YOUR SERVERSIDE PAGE URL>,
cache:false,
data:<if any arguments>,
async:asynchronous,
dataType:json, //if you want json
success: function(data) {
<put your custom validation here using the response from data structure >
},
error: function(request, status, error) {
<put your custom code here to handle the call failure>
}
});
});
</script>
I hope this helps

Categories