Pass variables from HTML form -> ajax load() - javascript

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.

Related

Submitting a form for use with php inside content loaded with AJAX

I've been search for a solution to this for a while and haven't been able to find one.
My company has quite a few webtools that we use for our jobs and I have been tasked with combining them all into a dashboard page. One of my coworkers started this project but never finished it before he left, so now I have to figure it out and there are quite a few problems.
The dashboard page is composed of a couple of sidebars, plus a "main" element. The sidebar includes a bunch of links that when clicked load specific php pages into the "main" via a call to jQuery AJAX. Here's a simplified example:
<html>
<head>
<script>
$(function() {
$("#pageToLoad").click(function() {
$.ajax({
url: "some_directory/pageToLoad.php",
success: function(result) {
$("#main").html(result);
}
});
});
});
</script>
</head>
<body>
Load Page
<main id="main"></main>
</body>
</html>
The problem here is that most of our tools use forms that are submitted via POST and then parsed with PHP (has to be php because it connects to our database to get information needed). Here's a simplified example of a tool page:
<?php
$action = htmlspecialchars($_SRVER["PHP_SELF"]);
function getResults() {
if(isset($_POST["infoForQuery"])) {
//Do some sort of query to database and print out results
}
}
?>
<body>
<form action="<?php echo $action;?>" method="post">
<input type="text" name="infoForQuery">
<input type="submit" value="submit" />
</form>
<div>
<?php getResults();?>
</div>
</body>
I need to be able to use these tools inside the dashboard page, but whenever I try to submit a form, it just reloads the entire dashboard page, resulting in the POST data not existing (maybe this is because the PHP code is run before ajax loads the content into the dashboard page? not sure).
I know I can use AJAX to send the POST like so:
$(function() {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});
However, this does not allow me to use the data collected in the form to query a database and print results out on the page.
Is it possible to accomplish this without having to leave the dashboard page, and if so, how?
Edit: I believe I've figured it out! What I wasn't realizing was that when I overrode the submit function and used ajax to send the post instead, I could actually retrieve the result of that post and put it into my page. Here's what I did:
<script>
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'some_directory/pageToLoad.php',
type: 'post',
data: $('form').serialize(),
success: function(result) {
$("#main").html(result);
}
});
});
</script>
Could be because the submit event is not firing. Since your forms are loaded dynamically do it like this:
$(function() {
$(document).on('submit', 'form', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});

Pass Java Script var to PHP $var

How can I pass my javascript variables to my PHP scripts, without reloading webpage or using separated PHP script through AJAX or javascript itself?
Without reloading your browser you can use javascript
put this before the <body> tag
<script>
$(document).ready(function(){
$("#varbtn").click(function(){
var var1 = $("#var").val();
$.ajax({
method: "POST",
url: "post.php",
data: {
var:var1
},
success: function(data){
//#success will be the id of the div you want to put the response of the php file
$("#success").html(data);
}
});
});
});
</script>
in the form, you dont need to create <form> tag
<input type="text id="var" />
<button id="varbtn"> Submit</button>
<!--this div will be the result of the post.php file-->
<div id="success"></div>
in the post.php
//will check if the person will direct visit that post.php, this is not secured enough but hes doing his job actually
<?php
if(isset($_SERVER['HTTP_REFERER'])){
if(!isset($_POST['var'])){
//your codes here
}
}
?>

Load .php site in to div without reloading

I am trying to create the following scenario:
A form in my index file collects input from a user, which is used to do some computation. The results of this computation should be echoed to him in a nice interface on the same page without reloading.
Currently, the results.php page is receiving the inputs correctly. Now, I just want to show it back inside the results div on the main page without reloading the results.php. .load is the wrong command for that. I need something like ".show"... Any ideas?
html:
<form action="results.php" method="post" class="ajaxform">
//all the inputs
<input type="submit" value="see your results" class="button"/>
</form>
<div id="results">
//here he should see the results.php output
</div>
jQuery
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
alert('Form is successfully submitted');
setTimeout(function() {
$('#results').load('results.php');
}, 1000);
},
error : function(){
alert('Something wrong');
}
});
return false;
});});
change this
$('#results').load('results.php');
To
$('#results').html(data);
if the returned results in data variable.
If i understood your problem correctly, results.php recieves the output you would show in the div #result.
To use the return-data from ajax-request you have data as javascript variable. To show the result in the div you need the following statment in the success function from ajax-call.
$("#result").html(data);

Get public function via ajax based on a custom script

I am trying to execute a public function with an ajax script with the following
In the front end, root folder from where I am trying to call the public function I have within the contents of the file
details-page.php
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function () {
$("#formaddtofav").on("submit", function (e) {
$.ajax({
type: "post",
url: "lib/execute-ajax.php",
data: $("#formaddtofav").serialize(),
success: function(){
alert("form was submitted");
}
});
e.preventDefault();
});
});
</script>
and HTML
<form id="#formaddtofav">
<input type="submit" name="addtofav" onclick="displaymessage()" id="addtofavs" class="addtofav" value="">
</form>
the public function is located in lib/details-page.inc and looks like this http://pastebin.com/U5tCxwVc
and in the file lib/execute-ajax.php I am echoing the function like I would if i would have not used ajax
<?php
include_once('detail-page.inc');
echo $objWebUser->addtofavorites();
?>
The problem is that I get a success message just that the data is not inserted in the database, what am I missing here.
Function addtofavorites() works 100%, tested with the old method of inserting data (<form action="" method="post"> and if isset).
EXPECTED OUTPUT
When i click the input submit, function should be run and do all the things I have written:
Add data into dbs, check if data is already there and print the coresponding messages.
Please help me on this. It's my first attempt on integrating ajax. It's much appreciated any help.

Execute script after load input file

I have an input file field to select files to upload, and I use ajax to send these pics to server. For execute all script after a file is selected, I use submit, but I think it could be better not to include the submit button and use jquery to detect when I select the file and process the submit action then.
My code:
<script>
jQuery(document).ready(function () {
jQuery('#form_up').ajaxForm({
dataType: 'json',
success: bol
});
});
function bol(datab) {
if (datab.field_empty == "bad") {
jQuery(".bol_request_fail").fadeIn(3000);
} else {}
}
</script>
<form name="form" method="post" id="form_up" runat="server" action="indexer_upload_user_pic.php" enctype="multipart/form-data" style="margin:0px;">
<input type="file" name="upload[imagen][]" id="logo2" class="file-upload"/>
</form>
I use one plugin for send the fields and all form by this you can see ajaxForm function.
The question is: How I can avoid using submit and instead send the pic when it is selected via file input?
I didnt test it, but this might work:
jQuery(document).ready(function () {
$("#logo2").change(function(){
jQuery('#form_up').ajaxSubmit({
dataType: 'json',
success: bol
});
});
});
Check the Plugin API if this dont work, I just quick checked it, and saw there is a ajaxSubmit...

Categories

Resources