I was using a self submitting form to process the data but I now need to process it separately so now I need to submit a form, return the results and place it in a div. It seems using AJAX is a good way to do this to have the data return to the original page where the form is. I have had a look at alot of examples and I don't really understand how to do it or really how its working.
Say I wanted to send this form data from index.php to my process page twitterprocess.php what do I need to do and get it to return to display the data processed.
<form method="POST" action="twitterprocess.php">
Hashtag:<input type="text" name="hashtag" /><br />
<input type="submit" value="Submit hashtag!" />
</form>
This is what I have been using to display the results.
<?php foreach($results as $result) {
$tweet_time = strtotime($result->created_at);?>
<div>
<div class="tweet"> <?php echo displayTweet($result->text),"\r\n"; ?>
<div class="user"><?php echo "<strong>Posted </strong>" . date('j/n/y H:i:s ',$tweet_time) ?><strong> By </strong><a rel="nofollow" href="http://twitter.com/<?php echo $result->from_user ?>"><?php echo $result->from_user ?></a></div>
</div>
<br />
<? } ?>
I'm new to AJAX but any guidance would be greatly appreciated
*When you use AJAX the output generated on other page is the result for this page.
*Now when you want to post data and retrieve results through the use of AJAX then in form part of your html don't use type="submit" for button, but simply go for type="button".
*action attribute should be left blank as you are going to trigger the action through your AJAX code.
*Well rest all your solution in the code snippet below:
Below is the HTML code along with AJAX
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Form Handling Through AJAX</title>
<script type="text/javascript">
function loadXmlDoc(fname, lname){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=" + fname + "&" + "lname=" + lname);
}
</script>
</head>
<body>
<p>
<span id="ajaxify"> </span>
</p>
<form id="frm" action="#">
<input type="text" name="fn" />
<input type="text" name="ln" />
<input type="button" name="submit" value="submit" onclick="loadXmlDoc(fn.value, ln.value)" />
</form>
</body>
</html>
Below is the PHP code that is used in above code
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
echo "Hello " . $fname . " " . $lname;
?>
Assign some id to your submit button, i'd use id="submit" and some id for your text field (i use id="text");
Client-side js:
$("#submit").click(function () {
var postData = new Object(); //for complex-form
postData.hashTag = $("#text").val();
$.ajax({
type: 'POST', //or 'GET' if you need
contentType: "application/json; charset=UTF-8", //i use json here
dataType: "json",
url: "some_url",
data: JSON.stringify(postData), //or smth like param1=...¶m2=... etc... if you don't want json
success: function (response) {
//handle response here, do all page updates or show error message due to server-side validation
},
error: function () {
//handle http errors here
}
});
return false; //we don't want browser to do submit
});
So, if user has js enabled = your code will do ajax request, otherwise - regular post request will be made;
On a server-side you have to handle ajax and regular submit different to make it work correct in both cases. I'm not good in php so can't do any advise here
You can use jQuery, for example,
function doPost(formdata){
var url="/twitterprocess.php";
var senddata={'data':formdata};
$.post(url,senddata,function(receiveddata){
dosomethingwithreceiveddata(receiveddata);
}
your php will get senddata in JSON form. You can process and send appropriate response. That response can be handled by dosomethingwithreceiveddata.
I find the Ajax Form plugin a good tool for the job.
http://www.malsup.com/jquery/form/#tab4
A basic code example could be:
$(document).ready(function() { // On Document Ready
var options = {
target: '#output1', // ID of the DOM elment where you want to show the results
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
// the callback function
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
All your PHP file have to do is echo the html (or text) back that you want to show in your DIV after the form has been submitted.
If you do not want to use jquery try this in pure javascript
function SendData(Arg) {
xmlhttp=null;
var uri = "/twitterprocess.php";
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null) {
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
if(xmlhttp.status==200) {
var xmlDoc = xmlhttp.responseXML;
var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue;
var Xml2String;
if(xmlDoc.xml) {
Xml2String = xmlDoc.xml
} else {
Xml2String = new XMLSerializer().serializeToString(xmlDoc);
}
document.getElementById("CellData").value=Xml2String;
} else {
alert("statusText: " + xmlhttp.statusText + "\nHTTP status code: " + xmlhttp.status);
}
}
}
}
Related
I have simple, form which works with Jquery Ajax, but I don't know how can I get my Errors from php.
My Form
<form action="customer.php" method="post" class="addForm">
<input name="username" type="text" placeholder="username"> <br>
<input name="name" type="text" placeholder="name"> <br>
<button type="submit" name="btnAdd">Add New Customer</button>
</form>
My Script
<script>
$(document).ready(function() {
$("form.addForm").submit(function(e) {
e.preventDefault();
// form's url and method
var addForm_URL = $("form.addForm").attr("action");
var addForm_Method = $("form.addForm").attr("method");
var username_Val = $("input[name='username']").val();
var name_Val = $("input[name='name']").val();
var btnAdd_Val = $("button[name='btnAdd']").val();
$.ajax({
url: addForm_URL,
method: addForm_Method,
data: {
username_Post: username_Val,
name_Post: name_Val,
btnAdd_Post: btnAdd_Val
},
success: function(data) {
if (data) {
console.log(data);
$("input[name='username']").val("");
$("input[name='name']").val("");
} else {
console.log(data); // here should be my errors
}
}
});
});
});
</script>
My php
if (isset($_POST['btnAdd_Post']) && empty($_POST['username_Post'])) {
//some stuff
echo 'Error 1';
}
if (isset($_POST['btnAdd_Post']) && $_POST['name_Post'] == "my1") {
//some stuff
echo 'Error 2';
}
if (isset($_POST['btnAdd_Post']) && !empty($_POST['name_Post'])) {
//some stuff
echo 'Error 3';
}
As I use e.preventDefault(), I can't use any exit() or headers in my php.
How can I get my echo Error 1,2,3 from php put in my Ajax and priant some stuff or redirect ?
Thanks
The problem is that you dont allow the post so the you cant get the $_POST info, so ether you have to let it go through with the post and catch the errors with php or log the errors with jQuery.
As far as I'm aware the you do the ajax call to prevent to reload the page and thus not accessing the PHP, but this means you'll have to catch the errors with jQuery as well.
Completely flummoxed after going over and over this problem for hours. Have tried a large number of approaches, without success.
Intent is to send login form data to PHP and have PHP return the result of an API call.
My latest approach is to have form onSubmit in login.html call myFunction() which performs POST call to n_authorise.php for some server side processing. In future the PHP will return API secrets. For my testing I stripped back the PHP to echo back the user input extracted from the $_POST global.
No matter what combinations of form ACTION / SUBMIT or XMLHttpRequest structures I try, I can't seem to pass the $_POST from the HTML to the PHP. I repeatedly get "Undefined index" from the PHP suggesting the $_POST is not populated.
I have tried action="n_authorise.php" directly in the form (avoiding myFunction() ) but this either fails or when it does work loads the PHP file to the browser NOT just returning the result.
I am so frustrated as it has to be possible and I can see from other postings that they have had (and resolved) similar problems... I just can't crack it, so asking the experts! Thanks in advance.
My HTML in file login.html :
<html>
<head>
<script>
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
</head>
<body>
<form name="loginform" onsubmit="myFunction()" method="post">
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
My minimal PHP in file n_authorise.php
<?php
$email = $_POST["t_username"];
$password = $_POST["t_password"];
echo $email . " " . $password;
?>
Expected result is for alert box to display entered email & password (this would be replaced in final version).
Note: I have tried with and without xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");. In fact, I think I've tried nearly every possible combination of code without success... yet.
This is a most simple answer:
you are not adding any parameters to your request, you could do it with native js like this:
var form = document.querySelector('form'); // <-- extend this to select your form, maybe add an id to select
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data); // <----- this way the form data is appended
Based on the above - sharing working code with humble thanks. FYI only:
<html>
<head>
<script>
function myFunction() {
var form = document.querySelector('form.loginform'); // <-------- extended to select new class ID for form
var data = new FormData(form); // <-------- 'data' extracts form content
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.send(data); // <-------- 'data' sent to PHP!
}
</script>
</head>
<body>
<form name="loginform" class="loginform" onsubmit="myFunction()" method="post">. // <-------- new class added
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>
I am trying to get the file progress working with the new session.upload_progress.name functionality in PHP 5.4.
So far my code is this:
<?
session_start();
?>
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$("#jimbo").submit(function () {
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data + Math.random(999));
}
});
//$("#feedback").html("hello " + Math.random(999));
},500);
//return false;
});
});
</script>
</head>
<body>
<h1>Upload</h1>
<br/>
<form action="test.php" method="POST" enctype="multipart/form-data" id='jimbo'>
<input type="hidden" name="<?=ini_get('session.upload_progress.name'); ?>" value="myupload" />
<input type="file" name="file1" />
<input type="submit" id='submitme' />
</form>
<div id="feedback">Hello</div>
</body>
</html>
And then the ajx.php file:
<? session_start(); ?>
<pre>
<?
echo "SESSIONVAR<br/>";
var_dump($_SESSION);
?>
</pre>
Now. When I click the submit button (after selecting a file), The file starts uploading, but the setinterval doesnt start. However, If I have the return false; in there, I get the setInterval results, but the file doesnt start uploading. If I submit the file without returning false, and in a seperate window view the contents of ajx.php, I can see that the variable is working fine and updating. So how do I get the #feedback div to update once the form has been clicked?
note the session array is populated, the problem here is with the jquery and nothing else.
You can achieve similar functionality using javascript XMLHttpRequest objects 'upload' property. It has a couple of events you can hook into, 'progress' is one of them.
here's a sample I've used. It will add a row with the progression (in %) to a <div class="progression"> for each file from a <input type="file"> field:
function startUpload() {
var fileInput = document.getElementById("file1");
$('.progression').show();
for(var i = 0;i<fileInput.files.length;i++) {
doFileUpload(fileInput.files[i]);
}
}
function doFileUpload(file) {
var xhr = new XMLHttpRequest();
var data = new FormData();
var $progress = $('<div class=\"progress\"><p>' + file.name + ':</p><span>0</span>%</div>');
$('div.progression').append($progress);
data.append("file", file);
data.append("album", $("#album").val());
xhr.upload.onprogress = function(e) {
var percentComplete = (e.loaded / e.total) * 100;
$progress.find('span').text(Math.ceil(percentComplete));
};
xhr.onload = function() {
if (xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
if(result.success == "true") {
console.log("Great success!");
}
else {
console.log("Error! Upload failed");
}
};
xhr.onerror = function() {
console.log("Error! Upload failed.");
};
xhr.open("POST", "/_admin/_inc/upload.php", true);
xhr.send(data);
}
I am writing a form, where user can send info, and attach a file, which sends via email to certain users.
I've built a HTML form, and because I don't wanna to refresh the page I sent it via a hidden iframe.
Everything was working, until I added captcha to my form. Now I've got a problem. I store a generated string for captcha in the session on the main form page. But because the form is sending from an iframe I think PHP is creating a new session, which is empty.
Can anyone have suggest how can I connect iframe and my form page to same the session? I would like to mention, that the iframe is created dynamically by JavaScript when the user clicks to send the form.
thanks for advice!
edit:
my code
HTML form page:
<input type="text" name="name"/><br />
<input type="text" name="email"/><br />
<textarea name="message"></textarea><br />
<input type="file" name="file"/><img id="captchaimg" src="http://xxx/mailsend.php?application=xxx&image=get"/><input type="text" name="captcha"/>
<input type="button" id="send" value="send"/>
my JS file:
function sendFromIframe() {
if ($('#hiddeniframe').length == 0) {
var iframe = ('<iframe name="hiddeniframe" id="hiddeniframe" src="" border="0" height="0" width="0" style="display:none"></iframe>');
$("body").append(iframe);
}
setTimeout(function() {
var form = $('#feedback');
form.attr('target', 'hiddeniframe');
form.attr('method', 'POST');
form.attr('action', 'http://xxx/mailsend.php');
form.attr("enctype", "multipart/form-data");
form.attr("encoding", "multipart/form-data");
form.submit();
wait4refresh();
}, 550);
}
function wait4refresh(counter){
var counter = counter || 0;
var bolean = false;
var request = $.ajax({
async: false,
url: 'http://xxx/mailsend.php',
type: 'GET',
data: 'application=' + $('input[name="application"]').val() + '&issend'
});
request.done(function(msg){
if (msg == 'true'){
bolean = true;
}
});
if (bolean){
refreshCaptcha();
}
else if (counter > 10){
return false;
}
else{
setTimeout(function(){
counter++
wait4refresh(counter);
},500);
}
}
function refreshCaptcha() {
var application = $('input[name="application"]').val();
d = Math.round(Math.random() * 100);
$('#captchaimg').attr('src', 'http://xxx/mailsend.php?application=' + application + '&image=get' + '&' + d);
}
and the PHP file:
i get error "connection reset by peer" when I'm trying to add my PHP code here. what can I do?
CouldnĀ“t you just create a <div id='htmlform'> </div> and just make it visible/invisible with jquery?