Ajax Response as HTML - javascript

When the submit button is clicked on page1.php the response is printed as HTML format for a moment but it gets automatically deleted.
I want to display the response of page2.php in page1 in the id="output" element.
What am I doing wrong?
Here is the content of page1.php
<script type="text/javascript">
function func(tosearch) {
alert("search");
$.ajax({
type: 'post',
url: 'page2.php',
data: {
'tosearch' : tosearch
},
success: function(result) {
print(result);
}
});
}
function print(result) {
document.getElementById("output").innerHTML=result;
}
</script>
<form method="post" action="page1.php">
<input type="text" name="search" placeholder="Search.."><br><br>
<input type="submit" name="submit" onclick="func()">
</form>
<p id="output">table here!!</p>
Content of page2.php
<?php echo "<table align='center'>"
."<tr>"
."<td>"."Mr XYZ"."</td>"
."<td>"."MALE"."</td>"
."<td>"."987558745"."</td>"
."<td>"."xyz#gmail.com"."</td>"
."</tr>";
?>

The response isn't being deleted, the page is refreshing. Since you don't want the page to refresh at all, you don't really need that form element. Just remove the form and make the input a plain button to keep the markup simple:
<script>
// your JavaScript
</script>
<input type="text" name="search" placeholder="Search.."><br><br>
<button onclick="func()">
<p id="output">table here!!</p>

Related

PHP - Post to Self without refreshing (Or another alternative)

Good evening SO community,
I'm trying to build a global chat system for my network of websites. In other words, a staff member can log in to www.myadminswebsite.com and check the live chat systems from all of our other external sites. I have the system working fairly well, except for the fact that the page is refreshing every time a user submits a new message. Is there something I can do to avoid refreshing the page to submit a message? Currently, I'm using an HTML form which posts to itself, then the page checks to see if the $_POST["var"] exists, then writes to the IM log file.
Code From HTML Form
<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'>
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send'>
</form>
Function to Process POST
if (isset($_POST['newMSG'])) {
$wHandle = fopen($lFile, "a");
fwrite($wHandle, "[CUSTOMER] " . $_POST['newMSG'] . "\n");
fclose($wHandle);
}
This does what I need it to do, other than refreshing the page. Please let me know if you need any more information or if you have any ideas!
Thanks in advance,
Tim
<form>
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send' id="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#submit').click(function()
{
var message=$("#lcTextInput").val();
$.ajax({
url: "msg.php",
type:'POST',
data:
{
action: 'addmsg',
message: message
},
success: function(msg)
{
$(".li").append(message);
}
});
return false;
});
</script>
Change your form action to:
<form method='POST' action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send'>
</form>
$('#submit').click(function()
{
var message=$("#lcTextInput").val();
$.ajax({
url: "msg.php",
type:'POST',
data:
{
action: 'addmsg',
message: message
},
success: function(msg)
{
$(".li").append(message);
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send' id="submit">
</form>

jQuery .val() not working on hidden fields added with .html()

I have an html form that loads the main portion of a document, postload an ajax request goes off and gets an xml file that is parsed out to create 'sub' forms which can be updated/submitted. This is the form 'preload'
<html>
<head>
<script src="jquery.js">
<script src="jquery.forms.js">
<script>
$(document).ready(function () {
//Script to execute when form is loaded
loadOrder(unid);
});
</script>
</head>
<body>
<form id="mainform" name="main" method="post" action="whatever">
<input type="hidden" id="unid" name="unid" value="123" />
</form>
<div id="orderForms">
</div>
</body>
</html>
Here is the form post load :
<html>...
<div id="orderForms">
<form id="order_1" name="order" method="post" action="whatever">
<input type="hidden" id="pid_1" name="pid" value="123" />
<input type="hidden" id="unid_1" name="unid" value="456" />
</form>
<form id="order_2" name="order" method="post" action="whatever">
<input type="hidden" id="pid_2" name="pid" value="123" />
<input type="hidden" id="unid_2" name="unid" value="789" />
</form>
</div>
</body>
</html>
JS code:
function loadOrders(unid){
var rUrl = "url";
$.ajax({type: "GET", url: rUrl, async: true, cache: false, dataType: "xml", success: postLoadOrders}) ;
}
function postLoadOrders(xml){
nxtOrder = 1;
var html="";
$('order',xml).each(function() {
// parses the xml and generates the html to be inserted into the <div>
});
$("#orderForms").html(html);
}
This all works, the main form loads, the 'hidden' forms in the <div> are written in. The trouble happens when I put a button on the main form that does this...
function submitOrder(){
$("#pid_1").val('555');
$("#order_1").formSerialize();
$("#order_1").ajaxSubmit();
}
If I alert($("#pid_1").val()) prior to the .val('555') it shows the original value, when I alert after, it shows the new value, however it submits the original value, and if I open the html in firebug the value isn't showing as changing.
If I put a hidden field into the main form, that exists when the document loads and change its value, not only does the new value post, it also shows as being changed when examining the source.
Any ideas?
$('order',xml).each(function() {
});
this is not Object in JQuery
You can edit:
$('[name=order]',xml).each(function() {
});

PHP Form with Button

I have some experience in JAVA GUI programming and I want to achieve the same in a PHP form.
Situation: I want to have a php form with a submit button. When the button is pressed an ActionEvent should be called to update another part of the form.
How to implement such a feature with HTML,PHP,JAVASCRIPT ?
Load latest version of jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
HTML code:
<form>
<button type="button" class="formLoader">Click button</button>
<div id="formContentToLoad"></div>
</form>
jQuery code:
<script type="text/javascript">
$(function(){
$(".formLoader").click(function(){
$("#formContentToLoad").load("scriptToRun.php");
});
});
</script>
Whatever markup you need to update in the form, can be put into scriptToRun.php
Use jQuery
Javascript
$(document).ready(function() {
$(".myForm").submit(function() {
$.ajax({
type: "POST",
url: "myForm.php",
data: $(this).serialize(),
success: function(response) {
// todo...
alert(response);
}
})
})
});
Html
<form method="POST" class="myForm">
<input type="text" id="a_field" name="a_field" placeholder="a field" />
<input type="submit" value="Submit" />
</form>
PHP
<?php
if(isset($_POST)) {
$a_field = $_POST["a_field"];
// todo..
}
If you want to use PHP and HTML to submit a form try this:
HTML Form
<form action="" method="post">
<input type="text" placeholder="Enter Name" name="name" />
<input type="submit" name="sendFormBtn" />
</form>
PHP
<?php
if(isset($_POST["sendFormBtn"]{
$name = isset($_POST["name"]) ? $_POST["name"] : "Error Response Here";
//More Validation Here
}

How to submit form, programatically with jQuery?

I have form, which when is submitted, is making ajax POST request, posting data fetched from form. Form is quite straight forwards.
<form id="form1">
<input type="text" name="domain" id="field1">
<input type="submit" name="my-submit" id="my-submit" value="Submit Form" class="btn btn-info btn-lg">
<!--<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>-->
</form>
Then #response div where returned content is loaded.
# HTML code ...
<div class="modal-body" id="response">
<p>Some text in the modal.</p>
</div>
# HTML code ...
And finally JavaScript...
$('#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'check.php',
data: $(this).serialize(),
success: function (data) {
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
});
But then, I want to check in my index.php script, where all these above is, if is $domain variable passed in URL, like yoursite.com?domain=domain.com, and if is, to call submit(); function programatically with this code:
if(isset($_GET['domain'])) {
$domain = $_GET['domain'];
echo $domain;
echo "
<script>
$('#form1').submit();
</script>
";
//exit();
}
Problem is, that nothing happens. How to achieve desired behaviour?
You should not do that. There is no reason to serve a page to the client, fill a form automatically and post back to the server.
Instead you should check if $_GET['domain'] domain is set and if it is, you should include your check.php file directly. And you should adapt check.php to handle both POST and GET parameters.
This would save you a round-trip to the client and does not rely on the client having javascript enabled.
<form id="form1">
<input type="text" name="domain" id="field1">
<input type="submit" onclick="return call();" value="Submit Form">
</form>
<script type='text/javascript'>
function call()
{
//ajax code;
return true;//are your want form submit
return false;// are your want cannot form submit
}
</script>
Don't forget to put return

How can I open a URL inside a DIV tag using AJAX?

I have the following php files. One that captures a user's text from a simple form, and the other echos this text. The files are shown below..
file1.php:
<form action="output.php" method="post">
Paste text document: <br><br>
<textarea name="doc" rows="5" cols="50" value="">
</textarea><br><br>
<input type="submit" name="submit" value="submit">
<input type="reset" name="reset" value="Clear">
</form>
<br><br>
<div id="output_area">
</div>
</body>
</html>
output.php:
<html lang="en">
<head><title>Output</title></head>
<body>
<?php
$doc = $_POST['doc'];
echo $doc;
?>
</body>
</html>
I want the output to be displayed between the DIV tags, rather than to load and show the output on a new page. I want the text to be output in between the DIV tags on the same page. Maybe the best way is to use AJAX to display output.php within the DIV tags and output the text after the user has clicked on the "submit" button. How can I use AJAX to do this in the most basic way possible?
You can use JQuery ajax function:
JQuery:
$("form").on("submit", function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "output.php",
data: { doc: $('#doc').val()}
})
.done(function( data) {
$("#output_area").html(data);
});
});
Change html:
<textarea name="doc" id="doc" rows="5" cols="50" value=""></textarea>
You can use the function:
$(document).ready(function() {
$( "#output_area" ).load( "output.php" );
});
But remeber!
That the load function from jquery, loads everything on the page you are asking for, so dont use:
<html lang="en">
<head><title>Output</title></head>
<body>
</body>
</html>
Now the load(function), will put in the PHP you made in output.php
if you want to output the answer on a submit i would do it like:
First add:
Show doc
Then add jquery:
$(document).ready(function() {
$('.pressme').on('click', function(){
var yourdata = $(this).parent().find("textarea[name='doc']").val();
$.ajax({
type: "POST",
url: "output.php",
data: {doc: yourdata},
success: function(data) {
$('#output_area').html(data);
});
});
});
I added a <a>, instead of using the <input type="submit"> because the submit, will post the form, thats not what you need, after what i understand, you need to preview the textarea in a div.
Hope it helps!
If you want your $_POST variable to be shown on the same page, then
1.change form's action to it. In your case
action="file1.php" or leave it empty to reload the page on submit (not valid in HTML5)
2.insert echo part directly in your div
<div id="output_area">
<?php
echo $_POST['doc'];
?>
</div>
not in another file
You need not use ajax for this. You can do this by using javascript. It will improve your performance of your code.
Try This:
<script>
function show() {
document.getElementById("output_area").innerHTML=document.getElementById("doc").value;
return false;
}
</script>
<form action="#" method="post">
<textarea name="doc" id="doc" rows="5" cols="50" value="">
</textarea>
<input type="submit" name="submit" value="submit" onclick="return show();">
<input type="reset" name="reset" value="Clear">
</form>
<div id="output_area"></div>
</body>
</html>

Categories

Resources