How to pass on a form through Ajax, and PHP - javascript

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>

The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>

Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>

You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.

change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}

<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>

Related

Ajax value with redirect and echo to page

I have developed the website using jquery & PHP, I have created a page using HTML, / PHP so what I want is if I click on submit, item ajax should send value to PHP variable and then execute index.php and get that value to another page.
Please help me to resolve the issues.
So far, I have tried the following:
index.php
my Javascript Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = $("#number").val();
$.ajax ({
type: "POST",
url: "ajax.php",
data: { val : val },
dataType:'text',
success: function( result ) {
// window.location.href = 'ajax.php';
// alert(result);
}
});
});
});
</script>
my HTML Code
<form name="numbers" id="numbers">
<input type="text" name="number" id="number" >
<button type="button" id="btn">Submit</button>
</form>
ajax.php
<?php
session_start();
$_SESSION['val'] = $_POST['val'];
print_r($_SESSION);
?>
You can store the value in session and redirect the user to other page and get data from session at other pages.
<?php
session_start();
$_SESSION['data'] = $_GET['val'];
?>
Your HTML code must be like that
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
<button type="button" id="btn">Submit</button>
</form>
For redirect to other page you can use like
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
window.location.href = 'url';
}
});
});
});
</script>
in this if you click button its refresh the page because you using input type="submit" on button , so just change it to input type="button"
<input type="button" id="btn" value="submit">
and if you want to keep input type="submit" as you already did then just add prevent default to jquery
$(document).ready(function(){
$("#btn").click(function(event) {
event.preventDefault();
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
}
});
});
});
you can use session
in ajax.php you have to add:
<?php
session_start();
echo $_GET['val'];
$_SESSION['val'] = $_GET['val'];
?>
and use variable $_SESSION['val'] to any page

Why isnt jquery setting my display css value?

There is my script and the function:
<script>
function post()
{
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
var sub = document.getElementById("sub").value;
if(name && email && message && sub)
{
$.ajax
({
type: 'post',
url: 'email.php',
data:
{
user_name:name,
user_email:email,
user_message:message,
user_sub:sub
},
success: function (response)
{
}
});
}
return false;
}
$(document).ready(function(){
$(document).ajaxStart(function(){
$("#mailalert").css("display", "");
});
});
</script>
And there is what should it change:
<div class="mailalert" id="mailalert" style="display: none">
<strong>Thank you for your letter.</strong>
</div>
Why it isnt chaning the display value to " "? It sends the email successfully, so it runs well.
You seem to have omitted part of the code which may contain the actual error. I've tested the following code and it works as expected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
</head>
<body>
<form id="mail_form" action="email.php">
Name:<br>
<input type="text" id="name" name="name">
<br>
Email:<br>
<input type="text" id="email" name="email">
<br>
Message:<br>
<textarea rows="3" id="message" name="message"></textarea>
<br>
<br><br>
<input type="submit" value="Submit">
</form>
<div class="mailalert" id="mailalert" style="display: none">
<strong>Thank you for your letter.</strong>
</div>
<script>
$("#mail_form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
if(name && email && message) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (data) {
// alert(data); // show response from the php script.
// I'd put $("#mailalert").css("display", ""); here, otherwise it doesn't make sense to display a thank you msg.
}
});
}
});
$(document).ready(function(){
$(document).ajaxStart(function(){
console.log("I'm here")
$("#mailalert").css("display", "");
});
});
</script>
</body>
</html>
Tip:
I'd move $("#mailalert").css("display", ""); to the ajax success function instead.
From the jquery docs
These methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery.ajaxSetup() is true, which it is by default. Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.
so in your ajax setup to enable global events, just add global: true. This should solve your problem.
...
$.ajax
({
type: 'post',
url: 'email.php',
global: true,
data:
{
user_name:name,
user_email:email,
user_message:message,
user_sub:sub
},
success: function (response)
{
}
});
...

how to clear form after submit the form and pass the data to php file without reloading page

how to clear form after submit the form and pass the data to php file without reloading page...the form data is pass the php file and it stored the data base.but i was unable to clear the form data after submit the form.if i reset the form using javascrip but data not pass the data base.if i pass the data to php the form is not clear.is there a way for me achive both target?thank you..
here my snipt code...
<iframe name="votar" style="display:none;"></iframe>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
Using AJAX you can do this.
$('#submitBtn').click(function () {
$.ajax({
url: 'confirm.php',
data: $('#sfm').serialize(),
type: "post",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
you can try this
in index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'ajax.php',
data: $('form').serialize(),
success: function (data) {
$('#name').val('');
alert('data');
//your return value in data
}
});
});
});
</script>
</head>
<body>
<form action="ajax.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" id="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
</body>
</html>
and in ajax.php
<?php
$name = $_GET['name'];
//do what you want to do using name
echo "what you need to return";
Have you thought about to use Ajax to handle the form submit?
Form submit with AJAX passing form data to PHP without page refresh
try making $_POST array empty after submitting and saving the form
$_POST='';
After getting success response you can clear form input
$('#sfm').submit(function () {
var form = $(this);
$.ajax({
url: 'phpfile.php',
data: form.serialize(),
type: "POST",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
You can do like this, first get form inputs value and then reset
You can also able to reset after success response
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var that = $(this);
var params = that.serialize();
that.get(0).reset();
console.log(params);
$.ajax({
type: 'GET',
url: 'submit.php',
data: params,
success: function (data) {
console.log(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
SERVER SIDE
<?php
$name = $_GET['name'];
echo 'success';
exit();
?>

Send Form Data to Controller (Codeigniter)

I have a pop up menu and inside that I have a form and a text box. I want to retrieve that value and submit it to my controller. Once submitted I want my pop up to close and go back to the other page. I tried with AJAX but I might be doing something wrong.
<form onsubmit="return(testing());" method="POST">
<input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
<input type="submit" name="Redeem" value="Redeem">
</form>
Now My Javascript
function testing() {
$test = document.getElementById("vip").value;
var url = base_url + '/index.php/home/redeeming_form_value';
$.ajax({
type : 'POST',
url : url,
data : {'myvalue':test},
success: function(data){
alert(data);
}
});
};
In my controller
function redeeming_form_value() {
$amount = $this->input->post('myvalue');
return $amount;
In the AJAQ I have a success, and want to alert my data(the value) to make sure it even works but it does nothing. When i click submit my pop up view just goes away.
Try adding dataType: "json", to your Ajax
dataType: "json",
Then in your controller use json_encode to return your data
$arr = array('amount' => $amount);
return json_encode($arr);
Test the response in success
console.log(data.amount);
Try it..
HTML
<form action="" method="POST">
<input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
<input type="submit" name="Redeem" id="submit" value="Redeem">
</form>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var test = $("#vip").val();
var base_url= 'http://localhost/shop';
var url = base_url + '/index.php/home/redeeming_form_value';
$.ajax({
type : 'POST',
dataType: 'json',
url : url,
data :'myvalue='+test,
success: function(data){
msg= eval(data);
amount= msg.amount;
alert(amount);
}
});
});
});
</script>
At your Controller
function redeeming_form_value()
{
$amount = $this->input->post('myvalue');
echo json_encode(array('amount'=>$amount));
}

php ajax form submit ..nothing happens

I have a PHP Ajax form that I'm trying to submit a Zendesk API call. Whenever I use the ajax part, in order to keep the user on the same page, it doesn't work. When I remove the <script> part, it works fine, but obviously redirects to contact.php from contact.html so I'm thinking the problem is in the Ajax part, not in the PHP part.
Here is my HTML form:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="box_form">
<form id="zFormer" method="POST" action="contact.php" name="former">
<p>
Your Name:<input type="text" value="James Duh" name="z_name">
</p>
<p>
Your Email Address: <input type="text" value="duh#domain.com" name="z_requester">
</p>
<p>
Subject: <input type="text" value="My Subject Here" name="z_subject">
</p>
<p>
Description: <textarea name="z_description">My Description Here</textarea>
</p>
<p>
<input type="submit" value="submit" id="submitter" name="submit">
</p>
</form>
</div>
<div class="success-message-subscribe"></div>
<div class="error-message-subscribe"></div>
<script>
jQuery(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('.box_form form').submit(function() {
var postdata = $('.box_form form').serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>
</body>
</html>
And the PHP Part:
You can probably ignore most of this since it works when I don't use the Ajax. Only the last few lines gives the response $array['valid'] = 1; which should then be catched by if(json.valid == 1) above.
<?php
( REMOVED API CALL CODE FROM ABOVE HERE )
if (isset($_POST['submit'])) {
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array(
'subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']),
'requester' => array('name' => $arr['z_name'],
'email' => $arr['z_requester'])
)));
$return = curlWrap("/tickets.json", $create, "POST");
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thank you!';
echo json_encode($array);
?>
Any ideas why this isn't working?
I expect your use of contact.php as a relative URL isn't resolving properly. Check your JavaScript console and you should see an error that shows the post failing. Change contact.php to www.your_domain.com/contact.php and it should work fine
Replace jQuery(document).ready(function() { by
$(document).ready(function() {
Secondly from Jquery documentation:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Therefore submit button won't serialize through jQuery.serialize() function.
A solution below:
<script>
$(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('#submitter').click(function(e) {
e.preventDefault();
$myform = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');
var postdata = $myform.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>

Categories

Resources