Ajax jquery php post beginner - php

I am have a hard time learning how to use ajax and jquery to post a button without reloading the page. Specificly: The form is still reloading the page and no variables are being updated.
Here is the code I am stumbling through.
What I used before I tried Jquery/AJAX. Just php
// $_POST['selected_dir'] is set when you click on a folder or link within the explore(r).php
if (isset($_POST['selected_dir']))
{
// last selected folder/directory
$current_dir = $_POST['selected_dir'];
// current_dir is the folder we are looking inside of.
// we make it a $session so that if we click a different submit (RELOAD)
// within the page it will remember $current_dir;
$_SESSION['selected_dir'] = $current_dir; //
}
else // if $_post isint set but $_session is
if (isset($_SESSION['selected_dir']))
{
$current_dir = $_SESSION['selected_dir'];
}
else
{
// default folder/directory
$current_dir = "$root"; //'D:\Hosting\538\html';
}
<form action='explore.php' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
value='submit'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
class='submit_into_link'/>
</form>
so that worked great except everytime you click the image or the link the page reloads.
I finally came to the conclusion i need to use jquery and ajax and I never even used javascript up till now. Ive been reading through tutorials and i cant really connect the dots to make this work
I have this in my header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
I have this at the top of my page within the body
$.ajax
({
type: 'POST',
url: 'explore_be.php',
data: data, success:
success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
});
I have a few questions about the code above. I'm not sure how to use it.
Do I need to put this ajax code inside an onclick function? seems like some examples ive looked through in jquery use something like this..
$(document).ready(function()
{
$(".flip").click(function() // this is a piece of code i got from w3schools.com
});
.flip above is a class. I have seen them use button when talking about
<button>
but what about a button within a form with a specific input id? Or should i just add to the form input
onclick="clicked()" then put the ajax in that function? Does the ajax need be in the $(document).ready(function()) as well?
What should i put for datatype?
I put my php code in the explore_be.php file.
explore_be.php
// $_POST['selected_dir'] is set when you click on a folder or link within the explore(r).php
if (isset($_POST['selected_dir']))
{
// last selected folder/directory
$current_dir = $_POST['selected_dir'];
// current_dir is the folder we are looking inside of.
// we make it a $session so that if we click a different submit (RELOAD)
// within the page it will remember $current_dir;
$_SESSION['selected_dir'] = $current_dir; //
}
else // if $_post isint set but $_session is
if (isset($_SESSION['selected_dir']))
{
$current_dir = $_SESSION['selected_dir'];
}
else
{
// default folder/directory
$current_dir = "$root"; //'D:\Hosting\538\html';
}
Is that all there is to the code behind page?
I changed my forms to have no action but added an onclick They are still reloading the page. What do I need to do to the form inputs to stop that?
My new form looks like this
<form action='' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
onclick='clickity()'
value='submit'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
onclick='clickity()'
class='submit_into_link'/>
</form>
Any help is greatly appreciated.

you can do it like this:
html
<form action='explore.php' method='post' id='myForm'>
jquery
$('#myForm').submit(function(event){ //added event
event.preventDefault(); //added to prevent submit
$.ajax
({
type: 'POST',
url: 'explore_be.php',
data: data, success:
success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
});
});
edit: remove the onclick events you added in your edit

<form action='javascript:;' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
onclick='clickity();'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
onclick='clickity();'
class='submit_into_link'/>
</form>
Firstly change this and tell me if it's ok and also tell me why you need 2 submits on the same form?

You are trying three things at a time. which will make things complex to find where the error lies. Just use ajax without jquery with a small example. Then extend it.
<html>
<head>
<script type="text/javascript">
function getdata(str)
{
if (str.length==0)
{
document.getElementById("result").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","response.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<input type='submit' onclick='getdata(input)'>
<div id='result'>
</div>
<body>

Related

Having Issues with ajax submit reloading, the anonymous function is not executing

I spent quite a bit of time looking for this and maybe I'm not approaching this correctly, but I'm trying to .submit and .post after clicking a submit. In other instances I have been able to get the ajax submit to work properly without the refresh, but when I do it in this manner it just doesn't work. I'm curious to know why.
Form
<form id="search" action="process.php" method="post">
Name: <input id="search_text" type="text" name="name" />
<input type="submit" value="Submit" />
</form>
Ajax
$('#search').submit(function() {
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
$('#page_nav').html(data.html_page_nav);
$('#results').html(data.table_html);
},
"json"
);
return false;
});
This works and it will submit without reloading just fine
Below is where I have the problem.
On the php server side I am sending back html that I want to be able to submit, which the initial search will put into the original html page.
$html_page_nav = "
<ul>
";
for($i=1; $i <= get_query_pages(get_query_count($query), 50); $i++) {
$html_page_nav .= "
<li>
<form id='page_".$i."' action='process.php' method='post'>
<input type='hidden' name='action' value='change_page'/>
<input type='hidden' name='page' value='".$i."'/>
<input type='submit' value='".$i."'>
</form>
</li>
";
}
$html_page_nav .= "
</ul>
";
I try to do the same thing as above, but the submit does not work properly
$(document).ready(function() {
$('#page_1').submit(function() {
console.log("this will not display");
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
},
"json"
);
return false;
})
...other jquery
});
This submit will not work properly, the function() will not execute and it will submit like the regular submit and go to the url rather then execute without refreshing the entire page.
Any suggestions or approaches would be much appreciated.
Thanks in advance!
Delegate the submit action to execute on content which will be loaded in future. By default the normal event handlers attached to the content loaded on DOM but not the one which will gets loaded in future, say through Ajax. You can use jQuery "on" function to delegate the action on content which will load in future.
eg.
$('body').on('submit', '#page_1', function() {
// do it here
});
I had a similar problem using ajaxForm n all. I jus used $("#Form").validate();
for it and the page doesnt get refresh

Why my simple ajax code does not work?

Can anyone help me understand why the code does not work?
Its not change the text in the div to the text that the member write.
And sorry in advance for my English, my English teacher apparently did't do a good job... =/
the first page:
<script>
function showUser()
{
var str = document.forms["myForm"]["users"].value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","act2.php?q="+str,true);
xmlhttp.send();
}
</script>
<form name="myForm" onsubmit="return showUser()" method="post">
First name: <input type="text" name="users">
<input type="submit" value="Submit">
</form>
<div id="txtHint"><b>Person info will be listed here.</b></div>
the second page (act2.php): (corrected the name)
<?php
$q=$_GET["q"];
echo "$q";
?>
The file specified in this line
xmlhttp.open("GET","act2.php?q="+str,true);
is act2.php, but according to your post, you're looking for ajax2.php, could that be it?
You have simply forgotten to "return false" in the showUser method, the form will post as usual before the Ajax call is made
edit:
To clarify, in the onsubmit you have return showUser(), the the showUser method never returns a value, to stop the browser from posting the form. Also, as suggested by other posters, you imply the php file is named ajax2.php but the code actually tries to hit act2.php.
Also, using some sort of framework (jQuery is highly popular) is recommended.
Your function needs to return false to prevent the default action of the form, otherwise your form will be submitted (which is the default action).
simply add a return false at the end of your code.
function showUser(){
// ...
xmlhttp.send();
// prevents the default action (the submit from your form)
return false;
}
or:
<form name="myForm" onsubmit="showUser();return false;" method="post">
Also you can safely drop the IE5/6 compat code.
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
simply becomes:
var xmlhttp=new XMLHttpRequest();
The var in front is pretty important, otherwise xmlhttp will become a member of the global object instead of a scoped variable.
Just to show how you can do the same with less pain and jQuery.
<form name="myForm" action="/act2.php">
<input type="text" name="q">
<input type="submit">
</form>
<div id="txtHint"></div>
<script type="text/javascript">
$(document)
// Link handler for submiting form
.on('submit', 'form[name="myForm"]', function(e) {
// Preventing original form submition
e.preventDefault();
// Send all data from form, to url from form's action attribute (/act2.php) and set received data to div with id txtHint
$.get($(this).attr('action'), $(this).serialize(), function(data, status, xhr) {
$('#txtHint').html(data);
});
});
</script>

How do I use a submit button to activate an AJAX function?

I have the following form and javascript function on my web page. This is a dummy function that I am using to test whether what I would like to do is possible.
What I am attempting to do is have a form send an AJAX request to the server, so that the server can update the database while the page itself continues along it's predetermined path. I am in a tight time crunch, so I unfortunately do not have time to rewrite the entire page to better support this. The problem that I have is the xmlhttp object does not seem to return properly. I get a readyState of 4 but a status of 0. can someone please explain what I need to do?
Here's my code:
ajax.php
<html>
<head>
<script type="text/javascript">
function test(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
document.getElementById("new").innerHTML+="<b>"+xmlhttp.readyState+"</b> "+xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hello").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","response.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
if ($_POST){
echo $_POST['hello'];
}
?>
<form action="ajax.php" method="post">
<input type="text" name="hello" />
<input type="submit" value="submit" onclick="test();" />
</form>
<div id="hello"></div>
<h3>debug</h3>
<div id="new"></div>
</body>
</html>
response.php
<?php
echo "Hello there";
?>
EDIT
Please note that I do not want to prevent the default behavior. In fact, the forn must be submitted as usual. I simply want to add an AJAX request to the process.
You can't trigger an AJAX request and allow the form to submit at the same time. Incomplete AJAX requests are cancelled when the page reloads (as is the case when the form is submitted). You'll either have to not submit the form at all, or wait until your AJAX call has completed before submitting the form. If you wanted to go the second route, you could make the following changes to your code:
<html>
<head>
<script type="text/javascript">
function test(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
document.getElementById("new").innerHTML+="<b>"+xmlhttp.readyState+"</b> "+xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hello").innerHTML=xmlhttp.responseText;
**document.getElementById("ajaxform").submit();**
}
}
xmlhttp.open("GET","response.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
if ($_POST){
echo $_POST['hello'];
}
?>
<form action="ajax.php" method="post" **id="ajaxform"**>
<input type="text" name="hello" />
<input type="submit" value="submit" onclick="test();**return false;**" />
</form>
<div id="hello"></div>
<h3>debug</h3>
<div id="new"></div>
</body>
</html>
Changes/additions are marked with **.
Note that there are a few practices in there I don't like, in particular using the onsubmit, etc attributes of HTML tags to attach Javascript event handlers.
I know this doesn't directly answer your question but if you are strapped for time then I would suggest just using jQuery to handle the AJax.
You can attach it to a button press and then call some code: http://api.jquery.com/jQuery.ajax/
I can dig out some code examples if you need them.
Once the submit button is pressed the browser will submit data to the server and a new page will be loaded. You can bind the submit event of the form and in the event make the ajax call but you will have 2 problems.
The browser may redirect before all ajax data is sent
You have no idea if the ajax call was successful or not
I would try sending the data you are sending via ajax in the same form data using hidden inputs. If both calls are aimed at different urls then try this:
var ajaxSent = false;
$('#myForm').submit(function(e){
if (!ajaxSent){
e.preventDefault();
$.ajax({
url: "ajaxUrl",
// data, method, etc
success: function(){
ajaxSent = true;
$('#myForm').trigger('submit');
}
}
// else submit the form
});

AJAX vs PHP submit of form

I originally had a form set up as such (CSS styles have been removed)
<form name="LoginForm" action="login.php" method="post">
<input name="email" id="email" type="text"></input>
<input name="password" id="password" type="password"></input>
<input name="login" id="login" type="submit" value="Login"></input>
</form>
and it worked fine, and login.php would validate the user creditionals. However, that approach required a page redirect. I am trying to migrate the code to AJAX so I can query the login details and stay within the page. [edit] here is the AJAX object I use
function Ajax(){
this.xmlhttp=null; //code below will assign correct request object
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
this.xmlhttp=new XMLHttpRequest();
}
else{ // code for IE6, IE5
this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
this.stateChangeFunction=function(){}; //user must reimplement this
var that=this;
this.xmlhttp.onreadystatechange=function(){ //executes the appropriate code when the ready state and status are correct
if (this.readyState==4 && this.status==200){
that.stateChangeFunction();
}
else{
dump("Error");
}
}
}
then I have a login.js function, which I am not too sure how to incorporate, currently I add it to the onclick event of the submit button:
function login(email,password){
var ajax=new Ajax();
//ajax.xmlhttp.open("GET","login.php?LoginEmailField="+email+",LoginPasswordField="+password,true);
//ajax.xmlhttp.send();
}
You will notice how those last two lines are commented out, I am not too sure how to send arguments at the moment, but the point is that even with the two commented out, the entire site still reloads. What is the correct way to use AJAX in forms.
Thanks
I havent done enough ajax in raw js to give a tutorial here so Im' going to use jquery. However anything i show can be done in raw javascript so maybe someone else will be kind enough to show you a raw implementation.
First of all you should use POST instead of GET for your login. Secondly as i said in my comment you should use the actual URL to the login page as the action. This way users who dont have JS for whatever reason can still login. Its best to do this by binding to the forms onSubmit event.
<form name="LoginForm" action="login.php" method="post">
<input name="email" id="email" type="text"></input>
<input name="password" id="password" type="password"></input>
<input name="login" id="login" type="submit" value="Login"></input>
</form>
And with jquery:
function doLogin(event){
event.preventDefault(); // stop the form from doing its normal post
var form = $('form[name=LoginForm]');
// post via ajax instead
$.ajax({
url: form.attr('action'), // grab the value of the action attribute "login.php"
data: form.serialize(), // converts input fields to a query string
type: 'post',
dataType: 'text',
success: function(data){
/* callback when status is 200
* you can redirect here ... data is the response from the server,
* send the redirect URL in this response
*/
window.location.href = data;
},
error: function(textStatus){
alert('ERROR');
}
});
}
// bind our function to the onSubmit event of the form
$('form[name=LoginForm]').submit(doLogin);
Then on the serverside you can check if its an ajax based request:
<?php
// do your login stuff
// set $successUrl to the URL you want to redirect to
// check if its ajax
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo $successUrl;
exit(0);
}
else
{
// was a non-ajax request - do a normal redirect
header('Location: '.$successUrl);
}
Your code only shows HTML. AJAX uses javascript to communicate to PHP script.
So, Only on seeing the js code, Debugging is possible.
To avoid the default event you have to use action='javascript: void(null);' instead of removing it.

PHP Post not working with Ajax

I have a simple form:
<form id="formTest" name="formTest" action="" method="get">
<input id="txtPostcode" name="Postcode" type="text" class="txtBoxSmall" />
<input type="button" name="SubmitTheForm" id="btnSubmit" onClick="TestAjax()" value="submit" />
</form>
My Javascript code is:
function TestAjax(){
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
};
xmlhttp.open("GET","autocomplete.php?value1=aaaaa&value2=fffff",true);
xmlhttp.send();
}
My problem is that in the php file autocomplete.php i can not access the txtPostcode element like so:
$postcodetext = $_GET[Postcode];
But if i get rid of the javascript function in the submit button, and add action="autocomplete.php"
to the form tag it will work, but then of course it is not ajaxed. Can someone tell me why I cant get any
values from $_GET[Postcode] when ajaxing?? I know i can just pass the value of the txtPostcode in the URL,
but i dont want to do it that way, is there something i can do so i can access the textbox via the
$_GET[Postcode] call in php??
Thanks.
You need to change this line:
xmlhttp.open("GET","autocomplete.php?value1=aaaaa&value2=fffff",true);
to include all the values you want to get in $_GET[] in PHP. You can do:
var postcode = document.getElementById('txtPostcode').value;
xmlhttp.open("GET","autocomplete.php?value1=aaaaa&value2=fffff&Postcode=" + postcode,true);
and similar for any additional things you want to access in PHP.
I totally agree with the comments below - take a look at jQuery, it will make your life much easier. Start here for example:
http://docs.jquery.com/How_jQuery_Works

Categories