Posting form with AJAX, CSHTML - javascript

trying to understand all this about AJAX, first of all I wanted to know how to refresh a page and keep my position on the page, which was possible, however, that was not the case on form post, that just jumped me right back to the top.
So after searching around on how to solve that, posting with AJAX seems to be my solution, I just can't seem to get all of it.
<form method="post" action="~/getAJAX.cshtml" id="ajaxform">
<input type="text" name="kg" id="kg" />
<input type="submit" />
</form>
<script type="text/javascript">
$(function () {
$('#ajaxform').submit(function (event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function (data) {
// Optionally alert the user of success here...
}).fail(function (data) {
// Optionally alert the user of an error here...
});
});
});
</script>
This is the code I have so far.
The thing I do not understand is what exactly should be on my "action" page?
At the moment I put this on my action page.
var db = Database.Open("Database");
var getKG = Request.Form["kg"];
var query = "SELECT * FROM Test WHERE kg = #0";
db.Execute(query, getKG);
This is just a test, I don't really know what to expect or anything, I would like to show the results on the page I post from, any guiding for this please?
Note that this is not a MVC project, therefore my problems with finding any good solutions or help, it's just normal CSHTML files.

Related

Need to grab input from a form, process it with php, having the option the reload the page depending on the answer

this is my problem.
I have a startpage website on this address: http://battlestation.rocks/
It mostly revolves around a search bar in the front page that executes commands. Presently, every command is processed with php, like so:
if (isset($_POST['searchBar'])) {
$originalcommand = $_POST['searchBar'];
processcommand($originalcommand);
return;
}
With this, every command reloads the page, which is a waste as most of the times it just opens some link from the startpage. In other cases, the startpage is changed by the commands, and thus in those cases I would like the page to reload.
I've seen from other questions that you can have the page not reload with AJAX, but none of the answers I've seen send the form input to php for processing, nor do they include the option to reload if necessary.
I'm very much a hobbyist coder and have zero experience with AJAX, please don't get too technical on me. I'm obsessed with this startpage, I just need to get this working as intended. Please help!
If you use PHP directly then the page needs to reload. If you use AJAX then you can send it so without reloading. !-You need a new PHP file in which you process the input-! An example with jquery but works the same:
You normal site:
<form action=''>
<input type='email' id='email' placeholder='E-Mail' required=""/>
<input type='password' id='pwd' placeholder='Passwort' required=""/>
<button id='go_login'>Go</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('#go_login').click(function() {
var bn = $('#email').val();
var pw = $('#pwd').val();
$.post('newphpsite.php', {'bn': bn, 'pw': pw}, function(data) {
alert(data); //send back echo from PHP
});
return false; //The form is not sent and does not reload the page.
});
</script>
newphpsite.php :
<?php
$bn = $_POST['bn'];
$pw = $_POST['pw'];
echo $bn."".$pw;
?>
?>
Yes, you should send the data via AJAX. One popular option is to use jQuery. Below is a simplified example using jQuery.
First, the HTML:
<input id="searchBar" name="searchBar" type="text" />
<button id="submit">Search</button>
<div id="searchResults"></div>
Next the jQuery:
<script type="text/javascript">
$("#submit").click(function() {
$.ajax({
type: "post",
url: "search.php", // Your PHP file
data: {
searchBar: $("#searchBar").val()
},
success:function(results) {
// Do something with your results
$("#searchResults").html(results);
}
});
});
</script>

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

JQuery button takes url and submits php form

I run an application that shortens urls for authenticated users. The form for this application is simply an input for the full url, which then spits out a shortened url.
I would like to build a button that can be added to generated pages (the urls are long and messy) and once clicked would automatically submit the url shortening form.
The url shortening application is run in php. I've read a little bit about using ajax to submit the form. Does this matter if it's on a different website? Does anyone have a good tutorial or starting point for this sort of thing?
Many thanks!
edit to include code:
<form action="" method="post">
<label for="form_url">Which URL do you want to shorten?</label>
<input type="url" id="form_url" name="form[url]" required="required" value="http://">
<input type="hidden" name="form[_token]">
<button type="submit" role="button">Shorten URL</button>
</form>
$(document).ready(function() {
$('a.btn').click(function() {
var pathname = window.location;
$.ajax({
type: "POST",
url: 'http://url',
data: $(pathname).serialize,
success: success,
dataType: text
});
});
});
There isn't much to go on, considering you didn't post any code, but what I think you're asking is:
<form id="myForm" method="post">
<input type="text" name="long_url"/>
<input type="submit" value="Send"/>
</form>
Now in the Javascript, you'd capture the submit event and call and ajax request:
$("#myForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "urlOfPhp",
data: $("#myForm").serialize(),
success: function(returned_data) {
// Handle Success Here.
}
}).error(function(){
// Handle an Error Here.
});
});
And that's the basics of Ajax. I'm also not clear on the Generated pages button thing, but this is a good starting point.

jQuery and Ajax combination confusion

I am a new user and I need help with JQuery and Ajax. I am good at PHP only.
I have a HTML Page which has a newsletter signup section,
<h4>Newsletter</h4>
<form id="main-news-contact-form" class="news-contact-form" name="news-contact-form" method="post" action="/scripts/xnews.php" role="form">
<div class="input-group">
<input type="text" class="form-control" required="required" placeholder="Enter your email" name="email"/>
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">Go!</button>
</span>
</div>
</form>
And the relevant JQuery -
//newsletter form
var form = $('.news-contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(15000).fadeOut();
},'json');
return false;
});
I have a php script, that reads the form data and saves the email address received in the database table, but for some reason the data (email address) is not being received by the PHP Code, the code below is executed.
if(empty($_POST["email"]))
{
echo("failed");
}
I don't know what I am doing wrong, I have a 'contact us' form, which is working absolutely fine, but I don't know why this newsletter form is not working with jquery.
I assure that all the javascript files are included in the html page, the php page is running absolutely fine, it does not return any php or mysql errors, I am setting JSON headers correctly, it's just that I am not getting the email address entered into the form. Earlier it was working but Ajax was not working, now I managed to get Ajax to work but the JavaScript code is not sending the form data.
Can you please help or help me to debug this.
Thanks in advance !
Your code is not sending any data to the server. Try to add the data as a second parameter to the function.
// get the text from the input field with the id "email"
var email = $.("#email").val();
// get the url from the form
var url = $("#newsletter-send").attr('action');
$.post( url, { email: email }, function( data ) {
// The code that you want to execute after sending the ajax call
}, "json");
Please do not copy paste the code but try to find the reasoning behind it. You might need to check the url variable to make sure you are posting to the right place. Also try to add an id attribute to the input field that contains the email.
I hope this will help you.
Try with this:
var form = $('#main-news-contact-form');
form.submit(function(e) {
e.preventDefault(); // Prevent submitting the form
$this = $(this);
$.post($this.attr('action'), $this.serialize()).done(function(data) {
// Do something with data
$this.prev().text(data.message).fadeIn().delay(15000).fadeOut();
}, 'json');
});

Can't use Ajax to Send/Retrieve variables To/From Server

Quite confused with the answers in the StackOverFlow and the whole Internet! I have some problems which seem easy but can't solve them since some days!
In my scenario (Online Booking System), I want to take the entered values in the FORM (Starting Time and Duration of the reservation) and send it to the SERVER (PHP); In the PHP function I will check if they are valid (some SQL queries and PHP functions); Then I'll retrieve the result back to the JQuery (as json encoded array);
The current snippets are as follow:
My HTML form:
<FORM ACTION="add.php" METHOD="post" ID="submitform">
<INPUT type="text" cols="50" id="starting_time" NAME="starting_time" PLACEHOLDER="Starting Time" /><br />
<INPUT type="text" id="duration" NAME="duration" PLACEHOLDER="Duration"/><br />
<P>Suggestions: <span id="txtHint"></SPAN></P>
<INPUT type="button" value='Add Reservation' id="button" />
<DIV ID="ajaxfield"></DIV>
</FORM>
My JQuery and AJAX codes:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(function(){
$('#button').click(function(){
$('#container').append('<img src= "ajax-loader.gif" alt="Currently loading" id="loading" />');
var str = $('#submitform').serializeArray();
$.ajax({
cache: false,
url: 'availability.php',
type: 'POST',
dataType:'JSON',
data: $str,
success: function(response){
resultObj = eval (response);
alert( resultObj );
}
});
});
});
</script>
My PHP:
<?php
header('Content-Type: application/json');
$starting_time = $_POST['starting_time'];
$duration = $_POST['duration'];
availability($starting_time, $duration);
function availability($starting_time, $duration) {
THE FUNCTION STUFF
}
echo json_encode( $arr );
}
?>
Now, the problem is first of all this is not working and the script is being stuck on the loader.gif!
And second how can I manipulate the json array from PHP to do some stuff, like enabling the submit button and/or suggesting a duration which works for the user.
PS: And of course, IN the final scenario I want to check these things instantly and before user presses the submission button.
Thanks!
EDIT
Some part of my problem is solved by the notes from answers, this is the modified code (till now):
var str = $('#submitform').serialize();
$.ajax({
cache: false,
url: 'availability.php',
type: 'POST',
dataType:'JSON',
data: str,
success: function(data){
alert(JSON.stringify(data, null, "\t"))
}
});
Now, obviously I could alert the JSON returned from the PHP function; I'll just need to modify it to manipulate for my purposes.
First of all... I'll try to teach you a bit of fishing instead of just giving you a fish...
You say that your code is just stuck on the loader.gif... you've been several days stuck so I supose you had time enough to detect where your code stops, to detect if there is any error on your javascript code or if your client code execution reachs your server code.
The only info you give us saying that it's stuck on the loader is that this line of code:
$('#container').append('<img src= "ajax-loader.gif" alt="Currently loading" id="loading" />');
Has been executed.
Well... and now?
Ok, you can check things like the following:
Check if str contains what you expect it to contains.
Check if execution reachs availability.php
Check what $str contains (is the data you're trying to pass to your server)
Surely during those checkings you'll see some light through your doubts and you'll be able to post here a more detailed question.

Categories

Resources