How to make button to post data with jQuery - php

Using Google and this site, I've made a simple form to send data with jQuery.
My HTML code:
ADD
<div class="area"></div>
And jQuery:
function AddPoke(id, action){
var response = $('#dle-poke').val()
$.post(dle_root + 'engine/ajax/poke.php', {id: id, text: response, action: action},
function(data){
if (data == 'ok') {DLEalert(dle_p_send_ok, dle_info);}
else {DLEalert(data, dle_info);}
});
$('.area').append("<div id='dlepopup'><textarea name='dle-poke' id='dle-poke'></textarea></div>");
$("#dlepopup").slideDown(700);
};
The problem is that I don't know how to make a send or submit button to post this data! I am very inexperienced with jQuery and I would appreciate any help!

HTML CODE:
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
<a href="javascript:void(0);" onclick="javascript:submit_value();" >Add </a>
Javascript Code:
<script>
function submit_value()
{
alert($('#first_name').val());
alert($('#last_name').val());
}
</script>
When you have enter any text in textfields then click on ADD link to display the alert message here display the text as you have write in textfileds.
Note: Please include the latest jQuery file in head tag.

Related

How to get result from php to html use ajax?

Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.

AJAX code not working on button click

Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});

work around for javascript php login system

Im building a login/register system using javascript to show particular divs for the system e.g
1st div = menu option to either login or register
2nd div = depending on what was clicked (login or register) shows login form or register form
3rd div = shows when user has successfully registered/logged in
the script looks like this:
html:
<article id="container">
<div id="load-new" class="game_menu">
<h1>LOAD/NEW</h1>
<button id="new_but" type="button">New Game</button>
<button id="load_but" type="button">Load Game</button>
</div>
<div id="reg" class="game_menu">
<h1>REGISTER</h1>
<form name="register" method="post" action="">
<label for="usernamesignup" class="uname">Your username</label>
<input id="usernamesignup" name="usernamesignup" required="required" type="text" placeholder="Username" />
<label for="emailsignup" class="youmail"> Your email</label>
<input id="emailsignup" name="emailsignup" required="required" type="email" placeholder="domain#mydomain.com"/>
<label for="passwordsignup" class="youpasswd">Your password </label>
<input id="passwordsignup" name="passwordsignup" required="required" type="password"/>
<label for="passwordsignup_confirm" class="youpasswd">Please confirm your password </label>
<input id="passwordsignup_confirm" name="passwordsignup_confirm" required="required" type="password"/>
<button id="reg_submit" type="button">Register</button>
</form>
</div>
<div id="login" class="game_menu">
<h1>LOGIN</h1>
<form name="login" method="post" action="">
<label for="username" id="username_label">Username:</label>
<input type="text" name="username" id="username" value=""/>
<label for="password" id="password_label">Password:</label>
<input type="password" name="password" id="password" value=""/>
<button id="login_submit" type="button">Login</button>
</form>
</div>
<div id="access" class="game_menu">
<h1>ACCESS</h1>
<button id="login_but" type="button">Login</button>
<button id="reg_but" type="button">Register</button>
</div>
<canvas id="TBG" width="640" height="416">
Please use a more up to date browser
</canvas>
the javascript looks like this
main.js:
//----------Login/Register Gui --------------
$('#load-new').hide();
$('#reg').hide();
$('#login').hide();
//create new instance of gui class
var ui = new Gui();
//if login_but is clicked do ui.login function
$('#login_but').click(ui.login);
//if reg_but is clicked do ui.register function
$('#reg_but').click(ui.register);
//if login_sumbit button is clicked do ui.login_ajax function
$("#login_submit").click(ui.login_ajax);
$("#reg_submit").click(ui.register_ajax);
gui.js:
function Gui (){
var valid = 'true';
var invalid = 'false';
//hide access div, show login div
this.login = function()
{
$('#access').hide();
$('#login').show();
};
//hide access div, show register div
this.register = function()
{
$('#access').hide();
$('#reg').show();
};
//function to send login data to php script login.php
this.login_ajax = function()
{
//username user inputted
var username = $("#username").val();
//password user inputted
var password = $("#password").val();
//inputted data made into JSON string
var dataString = {"reg":invalid, "login":valid, "username":username ,
"password":password};
//AJAX Request to login.php
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
alert("Your are logged in");
if(success == 'true'){
$('#login').hide();
$('#load-new').show();
}
},
error: function(){
alert("ERROR in AJAX");
}
});
};
this.register_ajax = function()
{
var username_signup = $("#usernamesignup").val();
var email_signup = $("#emailsignup").val();
var password_signup = $("#passwordsignup").val();
var password_signup_confirm = $('#passwordsignup_confirm').val();
var dataString = {"reg":valid, "login":invalid, "username_signup":username_signup,
"email_signup":email_signup,
"password_signup":password_signup, "password_signup_confirm":password_signup_confirm};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
alert("You are registered");
if(success == 'true'){
$('#reg').hide();
$()
$('#load-new').show();
}
},
error: function(){
alert("ERROR in AJAX");
}
});
}
}
i use ajax to send requests to php scripts to process login or register.
the script that the ajax requests is simple a go between so i can select specific functions in either the login php or register php.
i would like to have an are in my html to show if a user is logged in or not a bit like the are in the top right on the runescape website : here.
now i tried this php in my header.php file:
if(isset($_POST['username'])){
$is_logged_in = '<div id = "user_box">Welcome '.$_POST['username'].'</div>';
}
else
{
$is_logged_in = '<div id = "welcome_box">Welcome friend!</div>';
}
but obviously this wouldnt work because the page doesnt refresh where im using javascript to show different parts of the menu.
MY QUESTION:
What would be the most pratical way to achieving this effect with the javascript/php system i have in place?
Would i use javascript to hide/show divs like i have with the menu divs? or is there a function i can use to refresh the page without it sending me back to the first menu div?
Thanks for your time
Tom
Right now you are only sending back one value from the php scripts that you are calling using ajax, you are only using true for a successful login or registration.
What you could do, is modify these scripts to return multiple values. So apart from the true value for a successful login, you also send the username and then in your javascript you use that username to build a html block to show in the top area where you want to show the username.
You are already using json, so you only have to generate an array with return values in your php script and use echo json_encode($your_return_values); to send it to your javascript success variable.
By the way, you can use jquery / javascript to replace and build whole sections of your html, you don't need to put everything in at the start just to hide it.
If I'm understanding your question correctly your wanting to indicate to the user that they are logged in without reloading the page and by displaying a div in the top right corner.
That being the case you could create a hidden div with an absolute top right position which would be something like:
<div id="welcome" style="display:none; postion:absolute; top:0; float:right;">...</div>
In the 'success:' portion of the ajax request above, add a call to a new js function that makes a separate ajax request to retrieve a json object containing the logged in users display name and any other information that you want to show. Using that json data you could then populate 'welcome' div accordingly and change it's display to block.

submit form on click of a link and send to multiple email ids

I have formatted my form using uniform jquery plugin. Also for submitting the form i am using a link as i have added some effect to it and if I use input type submit for this it will get formatted with uniform .
<form>
<ul>
<li><label>Your Name:</label><input type="text" name="name" size="40"/></li>
<li><label>Your Email:</label><input type="email" name="email" size="40"/></li>
<li>
<label>Gender:</label>
<select name="gender">
<option>Male</option>
<option>Female</option>
</select>
</li>
<li><label>Subject:</label><input type="text" name="subject" size="40"/></li>
<li><label>Write your letter here:</label><textarea name="message" cols="60" rows="15"></textarea></li>
OR ELSE<br/><br/>
<li>
<label>Upload your letter:</label>
<input type="file" />
</li>
<li>
<a id="mylink" class="button" href="#">
<img src="button.png" alt="" />Send</a>
</li>
</ul>
</form>
Now i want to submit this form using the link and also want to email it to two email ids simultaneously. What javascript code can i use. I am using the following code to submit the form and then in send.php I am sending the mail.
a.onclick = function() {
$(this).parents('form:first').submit();
send.php;
return false;
}​
Is it possible to call send.php like this?
Do you mean:
If you have action="send.php" in your form, then
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
$(this).closest('form').submit();
});
});
Or, you can set action for the form and submit, like
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
var myFrm = $(this).closest('form');
myFrm.get(0).setAttribute('action', 'send.php');
myFrm.submit();
});
});
OR, using ajax
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "send.php",
data: {your data to post here},
succes: function(resp) {
//your response here
}
});
});
});
Is it possible to call send.php like this?
Like this? No, you need to use ajax request:
$.ajax({
url :"send.php"
});
Extra tip: change:
$(this).parents('form:first').submit();
To:
$(this).closest('form').submit();

Update text field border using Jquery and Ajax

I'm trying to build a nice contact form, from where a user can send an e-mail. I have 3 input fields (1. name, 2. e-mail address, 3. telephone number).
<p>
<label for="name"><?php echo $label_name; ?></label>
<input type="text" name="name" id="name" size="30" />
</p>
<p>
<label for="email"><?php echo $label_email; ?></label>
<input type="text" name="email" id="email" size="30" />
</p>
<p>
<label for="tel"><?php echo $label_tel; ?></label>
<input type="text" name="tel" id="tel" size="30" />
</p>
The styling of the fields is made with the following JQUERY script:
$(document).ready(function() {
$('input[type="text"]').addClass("idle");
$('input[type="text"]').focus(function() {
$(this).removeClass("idle").addClass("focus");
this.select();
});
$('input[type="text"]').blur(function() {
$(this).removeClass("focus").addClass("idle");
});
});
Basically what I want is to style the fields with RED border, if the server would return false (using AJAX and PHP). For this, I searched the net and tried to implement a few scripts, but none worked. Here's what I tried:
$(document).ready(function() {
$('input[type="text"]').blur(function() {
$.ajax({url:"php/verify_field.php", success:function(result){
$(this).removeClass("idle").addClass(result);
}});
});
});
Thank you all for answering!
The reply of Omid Amraei seems to suit my project so far. But could we add some spice to all this script: I would like to transmit 2 parameters with the Jquery-Ajax script to the server-side PHP file:
the ID of the text input
the value of the text input.
All this with POST method!
This way I could parse the information in the PHP file using $_POST method and check first the ID, then run the verification criteria on the value of the input.
Many thanks for all!
Happy Saturday :)
Because using this in Ajax callback does not point to your input, so try this :
$(document).ready(function() {
$('input[type="text"]').blur(function() {
var $input = $(this);
$.ajax({url:"php/verify_field.php", success:function(result){
$input.removeClass("idle").addClass(result);
}});
});
});
this in this case isn't the textbox it's the ajax jquery object
Change the context to this.
$('input[type="text"]').blur(function() {
$.ajax({
url:"php/verify_field.php",
context: this
success:function(result){
$(this).removeClass("idle").addClass(result);
}});
});
docs:
contextObject
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

Categories