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

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.

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>

Posting form with AJAX, CSHTML

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.

How to make a post request processed in the background

I've currently got the following button:
<input class="submitbutton" name="start" type="button" value="start"
onClick="window.location='vservermanage.php?_v=<?=$this->vid;?>'">
This button starts the current state of the 'service' - Either offline/online etc.
The page then loads & using if statements I can read whether it's offline or online. (PHP)
How do I make this post in the background instead - and once the result is returned process a javascript code, The following code also occurs when the page refreshes.
<?php if($this->msgsessuccess) { ?>
<div id="successbox"><?=$_lang[$this->msgsessuccess];?></div>
<?php } ?>
<?php if($this->msgseserror) { ?>
<div id="errorbox"><?=$_lang[$this->msgseserror];?></div>
<?php } ?>
I also have the following code which I want to do the same with HOWEVER I want to make this one automatic instead (every 2 seconds)
<input class="submitbutton" name="refresh" type="button" value="refresh"
onClick=" window.location='vservermanage.php?_v=<?=$this->vid;?>'">
The above code refreshes the state of the service.
There are a few elements to this but all can be achieved quite easily with JQuery. I assume you are including JQuery in your HTML head.
To illustrate you can tap into the click that happens on your submit button and then trigger an AJAX post, then do something with the results. Some example code:
$('.submitbutton').on('click', function(e) {
// Stop the browser from doing anything else
e.preventDefault();
// Do an AJAX post
$.ajax({
type: "POST",
url: "vservermanage.php",
data: {
_id: id_value // various ways to store the ID, you can choose
},
success: function(data) {
// POST was successful - do something with the response
alert('Server sent back: ' + data);
},
error: function(data) {
// Server error, e.g. 404, 500, error
alert(data.responseText);
}
});
});
The id_value parameter needs setting or obtaining, presumably from the original rendered page. You could for example, store the ID in a hidden form field e.g.
<input type="hidden" name="id_value" id="id_value" value="<?php echo $id;?>">
... and then include it like
_id: $("#id_value").val()
Regarding the second query, you could run the above POST within a standard JavaScript timer, e.g.
setInterval(function(){
$.ajax({
...
});
}, 2000);
I hope I've understood your question and that this helps put you on the right track.
You can use $.ajax(), or $.post(), even $.get(), but I wouldn't recommend allowing GET requests to modify data. Something along the lines:
function startProcess() {
$.ajax({
url: "vservermanage.php?_v=<?=$this->vid;?>",
type: "POST",
success: function(data) {
// proces the data if interested
// or just do what you need
}
});
}
, and you set this function as the click handler for your button.

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.

Disable buttons unless button is pressed

I would like to disable some buttons until a button is pressed.
The first button (button1) generates a file. The rest of the buttons have something to do with that file (view, download, etc.)
I tried disabling the buttons until the first button was pressed, but as I'm using a post request the page is refreshed when I hit button1 and everything is reset.
I was thinking along the lines of grep-ing for the file and assigning that to a variable in PHP then disable/enable the buttons based off whether or not that file is there, but I'm unsure how to do the PHP/JS crossover. Any guidance would be appreciated.
You should use asynchronous page loading. Just send a request string to the server and it echoes you an answer back., without reloading page.
var jstring = JSON.stringify(request); //wrap up your specification in an JSON
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://" + window.location.hostname + "/request",
data: jstring,
success: function(response) {
//... enable buttons
},
error: function(response) {
//... file could not be loaded
}
});
In PHP
if ($_GET["type"] === 'request') {
$jsonraw = $decode ? utf8_encode(file_get_contents("php://input")) : file_get_contents("php://input");
$jsonstring = json_encode($jsonraw, true);
$array = json_decode($jsonraw, true);
//... do something with $array
}
You can also do this without an ajax. You can also do this using sessions.
Save it in a session, before any session is saved, disable the buttons view, download, etc., after the file is created, then save a session, that will determine the disabled attribute.
Rough Example:
session_start();
if(isset($_POST['create_file'])) {
$_SESSION['file_exists'] = true;
// generate file blah blah
echo 'File created: stackoverflow.jpg <br/>';
}
// now you decide when to destroy the session for this
// unset($_SESSION['file_exists']);
?>
<form method="POST">
<input type="submit" name="create_file" value="Create File" /><br/><hr/>
<input type="submit" name="view_file" value="View File" <?php echo !isset($_SESSION['file_exists']) ? 'disabled' : ''; ?> /><br/>
<input type="submit" name="download_file" value="Download File" <?php echo !isset($_SESSION['file_exists']) ? 'disabled' : ''; ?> /><br/>
</form>
What you need is called AJAX.
Make an AJAX call on click of the first button to a php file that checks for the above mentioned file. Set the PHP to return true if file is found and false if not.
Finally, in the callback of the ajax make the javascript changes if returned code is success.
I will not write the code for you, but I'll give you a link. It should be more than enough.
http://api.jquery.com/jquery.ajax/
Note that you need jQuery to execute the example.

Categories

Resources