I'm having a problem with my code. I want to validate my form by creating an array to contain a variable when the form is valid. But to do this I need to use the isset method to know that the information has been posted. Here's a simple example
http://richbaird.net/clregister
<?PHP
if(isset($_POST['username'])) {
$helloworld = array ("hello"=>"world","name"=>"bob");
print json_encode($helloworld);
};
if(!isset($_POST['username'])) {
echo json_encode(array('error' => true, 'message' => 'No username specified'));
?>
Simple enough if username has been posted create array helloworld.
I'm using the following method to get the json
<script>
//document ready
$(document).ready(function(){
var php = "helloworld.php";
//submit form
$("#loginform").ajaxForm
(
//on successful submission
function() {
//getjson
$.getJSON("helloworld.php",function(data) {
alert(data.message)
}) //close get json
.error(function(error) { alert(error.responsetext); })
.complete(function() { alert("complete"); });
} // close success
) // close submit
});
//end document ready
</script>
I'm using the jquery forms plugin to submit the form.
and my form looks like this
<form id="loginform" name="loginform" method="post" action="helloworld.php">
<label for="username">username</label>
<input type="text" name="username" id="username" />
<br />
<label for="password">password</label>
<input name="password" type="password" />
<br />
<input name="submit" type="submit" value="Login" id="subtn" />
</form>
the network console shows the method POST returns {hello:world name:bob} but the GET returns the no username specified which is what I get in my alert. It looks like jquery is trying to get the code before it has a chance to process entirely, how can I prevent this?
You're missing the quotes. Should be:
if(isset($_POST['username']))
You should check your console to see whether username is actually getting posted, as if it's not, you're not returning any data. You could instead consider returning an error if(!isset($_POST['username'])), perhaps something like:
echo json_encode(array('error' => true, 'message' => 'No username specified'));
EDIT
Also, remember it's $_POST, not $_post
Second Edit
Your code will be far more intuitive and readable written like this:
$return = array();
if(isset($_POST['username'])) {
$return = array("hello"=>"world","name"=>"bob");
} else {
$return = array('error' => true, 'message' => 'No username specified');
}
echo json_encode($return);
After a few hours of thinking and a lot of help from juco I realized, I'm making 2 seperate calls in this function. First I'm posting the data which works, then on a successful post I'm trying to make a seperate call, a GET request, that request contains the callback which is supposed to alert me of the result, however because it makes a 2nd call and it sends a GET request the variable POST is never set and therefore there is nothing to get back. I revised my code to only use the post method like so.
<script>
//document ready
$(document).ready(function(){
// bind form using ajaxForm
$('#loginform').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',
// success identifies the function to invoke when the server response
// has been received
success: processJson
}
);
function processJson(data) {
alert(data.hello);
}
});
//end document ready
Related
Trying to implement AJAX using one of JQuery’s functions. I’ve been trying .load(), .ajax() or .post() in various ways, by using some of the examples on Stack Overflow without success.
I have a form, which queries the oracle DB, and returns another form and a results table. I have it working in the traditional way with separate PHP files (reload an entire new page). Now I want to just load the content without the page refresh.
Start Form PHP (checkin_start.php): Enter a barcode and submit…
<div class="content" id="bodyContent">
<form id="usualValidate" class="mainForm" method="post" action="">
<label>Barcode:<span>*</span></label>
<input type="text" class="required" name="startBarcode" id="startBarcode"/>
<input type="submit" value="submit" class="blueBtn" id="startBtn" />
</form>
</div>
Process PHP (checkin_process.php): a new form and the query results from the php function are loaded into id="bodyContent"…
<form id="checkinProcess" class="mainForm" method="post" action="">
<label>Barcode:<span>*</span></label>
<input type="text" class="required" name="processBarocdes" id="processBarcodes"/>
<input type="submit" value="submit" class="blueBtn" id="submitBtn" />
</form>
<!-- Shipment List Table -->
<?php
// Accept a parameter from #usualValidate form and run query.
$barcode = $_POST['startbarcode'];
search_shipped_barcode($barcode);
?>
Functions PHP (functions.php): returns results table…
<?php
function search_shipped_barcode($barcode){
<--! DB connection & query -->
echo "<table>";
<--! echo table results -->
echo "</table>";
}
?>
I think I probably have the same problem no matter which one I choose, so here's my .post() attempt. I don't quite understand how to pass the form data to my php function and return the data back...
$(document).ready(function() {
$("#usualValidate").submit(function(sevt) {
sevt.preventDefault();
var startBC = $("#startBarcode").val();
$.post("checkin_process.php",
{"startBarcode" : "startBC"},
function(data) {$("#bodyContent").html(data)},
"html");
});
});
Thanks for any insight....
When you use $.post, the values should not be quoted unless they are literals.
Try this:
$(document).ready(function() {
$("#usualValidate").submit(function(sevt) {
sevt.preventDefault();
var startBC = $("#startBarcode").val();
$.post("checkin_process.php",
{startBarcode : startBC},
function(data) {
$("#bodyContent").html(data);
// log the returned data to console for debug
console.log(data);
});
});
});
In your javascript file you can use the post method or you can use ajax like in the example below to send your data:
$.ajax({
type : 'post',
url : 'currentphpfile.php',
//Here is where the data is put
data : {
"ajax" : "1",
"otherData" : "abc"
},
success : function(data, textStatus, jqXHR) {
//Do something with the data here like insert it into the document
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//Do something to fix the error
},
dataType : 'text' //Or automatically parse a json response with 'json'
});
For this to work, you would need something in your php file that could handle the request like this:
if (!empty($_POST['ajax']) && $_POST['ajax']==1){
//Do stuff with the other post data
//Here's how to return the data to your script:
//If you chose a text response above:
echo $importantData;
exit;
//If you chose json
echo json_encode(array("title" => $title, "text" => $text /*, etc... */));
}
I haven't tested this code for bugs, but you probably get the idea.
i have this code which ask user to input value and submit.
html
<form id="myForm" method="post" action="saving.php">
<p><label for="input1">Input 1:</label>
<input type="text" size="10" name="input1" id="input1" />
</p>
<input id="save" name="save" type="submit" value="save" />
</form>
<p><span id="thevalue"></span><span id="existornot"></span></p>
js
$("#myForm").submit(function(event) {
event.preventDefault();
$("#myForm").validate(
{ rules: {input1: "required",},
messages: {input1: "message error input"},
});
if( $("#myForm").valid()){
var $form = $("#myForm" ),
url = $form.attr( "action" ),
insertedVal=$("#input1").val();
$.post(url,{input1:insertedVal},
function(){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
});
}
});
saving.php
<?php
if(!empty($_POST['input1']))
{
$inputone= mysql_real_escape_string(trim($_POST['input1']));
$result = mysql_query("SELECT COUNT(*) FROM `test_table` WHERE `name` = '$inputone' ");
if (mysql_result($result, 0, 0) > 0)
{
echo "is duplicate data" ;
}
else
{
mysql_query("INSERT INTO `test_table`(name) VALUES ('$inputone')") ;
echo "is updated to db" ;
}
}
else
{
echo "could not be empty" ;
}
?>
How to pass those message of 'is duplicate data' or ' is updated to db' from the php to the javasript, to tell user that the submit process is fail or success ?
Thanks in advance for any advice.
Change the function call after the jQuery post to accept the data variable and process the results:
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
if (data != 'is updated to db') {
alert(data);
}
});
}
(Data will contain what has been echoed in your save function)
The response from php file is in the ajax callback function. so you should add a parameter to your function like this:
$.post(url,{input1:insertedVal},function(resp)
{
// resp is the callback from php.
console.log(resp);
$("#thevalue").html(insertedVal);
});
For more information that how ajax works, you can follow this link: 5 Ways to Make Ajax Calls with jQuery
hope to help.
Like this:
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
$("#existornot").html(data);
});
}
By adding the "data" variable to the callback function(), that "data" variable will be updated with whatever php echo's as output. You can then insert that "data" into #existornot in the callback function.
Please see the API here: http://api.jquery.com/jQuery.post/
If you want to print the value returned from php please check the jquery $.post
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#somediv_id").html(data);
$("#thevalue").html();
// ... msg from php to be inserted to #existornot
});
The $.post callback function will be passed a argument containing the server response. So your $.post request should look like
$.post(url, {input1: insertedVal}, function(response) {
console.log(response); // should output the server message echoed.
});
It's also usually best to use JSON as a server response.
Here is the form to have ajax check out user existence.
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.fail(function()
{
$('#user').html("This user already exists");
}
);
}
</script>
</html>
And here is the userexists.php module
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username=$_POST('username');
$sql="SELECT username FROM ".TABLENAME." WHERE username=".$username;
$query=mysql_query($sql);
if(0!=mysql_numrows($query))
{
//
}
else
{
}
?>
But I am stuck to really figure out how the ajax function actually works, what should I enter the blank field after I know that the entered username has been used, for example ? I don't understand ajax at all.
[UPDATE]
Thank you, I understand it now, I have got several answers, don't know which one to choose as the best reply. No option to choose all.
You have a lot of mistakes in your code, try codes below:
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax({
type: "POST",
data: {
username: $('#username').val(),
},
url: "userexists.php",
success: function(data)
{
if(data === 'USER_EXISTS')
{
$('#user')
.css('color', 'red')
.html("This user already exists!");
}
else if(data === 'USER_AVAILABLE')
{
$('#user')
.css('color', 'green')
.html("User available.");
}
}
})
}
</script>
</html>
And for your php code:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // $_POST is an array (not a function)
// mysql_real_escape_string is to prevent sql injection
$sql = "SELECT username FROM ".TABLENAME." WHERE username='".$username."'"; // Username must enclosed in two quotations
$query = mysql_query($sql);
if(mysql_num_rows($query) == 0)
{
echo('USER_AVAILABLE');
}
else
{
echo('USER_EXISTS');
}
?>
Since you're new to AJAX, let me try and help you a bit better with some explanations as we go.
AJAX stands for Asynchronous Javascript And XML. Using it, you can make a request to another page and have your original page behave differently according to the results returned by the other page.
So how is this useful? Well; You could set an onblur even on a 'username' field to check a remote script to see if a username is already in use. (Which you are already doing in your current setup. Good work!)
Firstly; the .fail() is telling your current page "If the ajax request fails, lets do this code". This is called a callback. A callback is a function of javascript code to execute when the asynchronous request is finished.
So what you want to actually do is use the .done() method. This tells your jQuery request "Hey, when you're done doing this request, do this chunk of code. While you're doing that, im going to sit here and handle anything else that happens".
So you can see there is a slight difference between using .done() and .fail(), however I can see how you can be easily confused with .fail() being new to ajax.
So lets get back to your current problem. Lets modify the ajax to something more like this:
$("#submit").click(function()
{
$.ajax({
type: "POST",
data: "username="+$("#username").val(),
url: "userexists.php"
})
.done(function(response){
$('#user').html(response);
});
});
What this does is bind an onclick handler for your submit button with the id "submit". So now you can remove onclick="register_user". Secondly, it says, "Hey webpage, go send userexists.php the username textbox value with the parameter name username. When you've finished that request, set the html of #user to the response.
So off it goes and does it.
Now your PHP file, you can do:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn = mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // Stop some MySQL injections
$sql="SELECT username FROM ".TABLENAME." WHERE username='$username'";
$query=mysql_query($sql);
if(mysql_numrows($query) == 0)
{
echo 'Username is available!'
}
else
{
echo 'Sorry, username is in use.';
}
?>
So once your script does its query, if it finds a result it will say in the HTML div "Username is available!". Otherwise, if it finds a match, it says "Sorry, username is unavailable".
Hope this helps you understand ajax a little better!
It's technically up to you. (For example) You could return a "1" for "user exists" and "0" for "user doesn't exist", or return a more detailed XML. The client app (Javascript) will read the returned result and print out an appropriate message to the user.
The .fail method should be used in case your function actually fails (server side error etc). So it doesn't seem appropriate for what you're trying to do. I would put in your ".done()" code a test of the returned values as described above and print out the correct message.
Javascript:
.done(function ( data ) {
if(data == "0")
alert("Your username is OK");
else
alert("Your username is already used");
});
PHP:
if(0!=mysql_numrows($query))
{
echo "0";
}
else
{
echo "1";
}
Function .fail in ajax is used when server return unexpected datas. But your php code dont return anything. Use something like this:
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.done(function(_return)
{
if(_return)
{
if(_return['status']=='yes')
{
$('#user').html(_return['msg']);
}
}
})
.fail(function());
}
And in php:
if(0!=mysql_numrows($query))
{
$return = array('status'=>'yes',
'msg'=>"User alredy exist");
echo json_encode($return);
return true;
}
Now you can add more conditions with many statuses and parse it in javascript.
I have a simple sign up mailing list form. It sends the user's email address to a store-address.php file. I use jQuery's ajax object to send a request to the php file and then receive a response.
The problem is I am not getting a response from the php file. I tried setting the cache to false in the request. I also tried send the information through the URL like so:
http://www.fifthtribe.com/inc/store-address.php?ajax=true&cache=false&email=test4%40gmail.com
When I do it that way it works and gives me a reponse. But when I do it through ajax it doesn't give me a response. This is from Firebug:
And here's snippets from my code:
HTML:
<div id="mlist">
<form id="mlist_form" method="POST" action="">
<input type="text" id="email" name="email" placeholder="Email" />
<input type="submit" id="submit_btn" value="Join" />
</form>
<div id="response"></div>
</div>
JQuery:
/* Add to mailing list */
$("#mlist_form").submit( function(e){
//$('#response').append('<div id="thanks-mce"><div id="mce-arrow"></div>Thanks for signing up!</div>');
var email = escape( $('#email').val() );
e.preventDefault();
data = {
"ajax" : "true",
"email" : email,
"cache" : "false"
}
$.ajax({
type: "POST",
url: 'inc/store-address.php',
data: data,
success: function( msg ){
// successfully signed up
$('#response').html( msg );
$('#email').val('');
},
error: function( err ){
// error while signing up
$('#response').html('Error: Is your email correct?');
}
});
return false;
});
PHP:
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us4');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "xxxxxxxx";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
You realize that your PHP script is using GET method but your jQuery code is using the POST method right?
If the information is being posted to PHP, PHP will need to use $_POST to retrieve it. This explains why the URL method using $_GET works but the jQuery POST doesn't.
Good luck!
It looks like you're using $_GET instead of $_POST. Try echoing out the contents of $_REQUEST to see what that holds.
Debug your script!
Place an alert in the success and error parts of your script and then you will know whether the AJAX is working.
If not, you can then work your way up the document and see where the problem is.
In addition, the error here is quite simple. You are using $_GET in PHP and you are POSTING your data using AJAX, this will not show an error. Although the PHP document will not process your request because it is not being fed any parameters.
When I try to get the response from a php file using Jquery ajax, I just get (an empty string) (Accdg. to Firebug console using console.log(data))
Here's the Html code:
<form action="test.php" method="POST" id="ajax">
<input type="text" name="field" />
<input type="submit" value="submit" name="submit" />
</form>
Here's the Jquery code:
$('#ajax').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'test.php',
cache: false,
success: function(data) {
alert(data);
}
});
return false;
});
And the PHP code:
if ($_POST['submit'] == "submit")
{
echo 'Got your request';
}
Just basic. What frustrates me is that it's straightforward, I've done some research and still it doesn't work. I also want it to be as simple as possible.
Please enlighten me.
Don't check to see if you're in a POST situation by checking for fieldnames. That's incorrect - you might change your client-side form names and forget to update the PHP check.
The 100% reliable method is to use:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Got your request";
}
However, since you just want to see if the server got pinged at all by your ajax call, why not do:
<?php
echo "Got your ", $_SERVER['REQUEST_METHOD'], " request";
Which'd just return Got your POST request or Got your GET request, etc...
As well, check your server log (or use HTTPFOX/Firebug Net tab, etc...) to see if that ajax request is actually going out and being received by the server.
The problem with the serialize() method is that it doesn't include the name of the button parameter which you use in your php script (submit=submit parameter). It doesn't do it because it doesn't know which button was clicked. This parameter is only included by the browser when you submit the form normally.
So one possibility is to manually attach this parameter as query string parameter:
url: 'test.php?submit=submit',
and in your PHP script:
if ($_GET['submit'] == "submit")
{
echo 'Got your request';
}