Hi I would love to know how can I pass the strings from a form to a php that will test if there is something in it and then post an alert message using this form to try and get data from it and then show if it was passed correctly.
HTML code:
<form action='' method=''>
Name:<input type='text' name='name' id='name'>
Age:<input type='text' name='age' id='age'>
message:<textarea name='message' id='message'></textarea>
<input type='submit' value='Send'>
</form>
Output:
<?php
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['message'])){
$a = $_POST['name'];
$b = $_POST['age'];
$c = $_POST['message'];
if($a != NULL && $b != NULL && $c != NULL)
{
echo "
<script type='text/javascript'>
window.alert('Success'+ a + b + c)
</script>
";
}
};?>
While still in the same page from before but shows what I have typed in there into the alert box.
I would also appreciate if it comes with instruction on how to use it with get and post functions and also with links if it can be done?
For an easy way you can Make following changes to your code:
HTML:
<form action='' method='' id="myform">
Name:<input type='text' name='name' id='name'>
Age:<input type='text' name='age' id='age'>
message:<textarea name='message' id='message'></textarea>
<input type='submit' value='Send'>
</form>
PHP:
(your_page_with_php_script)
<?php
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['message'])){
$a = $_POST['name'];
$b = $_POST['age'];
$c = $_POST['message'];
if($a != NULL && $b != NULL && $c != NULL)
{
echo "Success ".a." ".b." ".c;
}
};
?>
Script: (Include jquery first)
$('#myform').submit(function(){
var name = $('#name').val();
var age = $('#age').val();
var message = $('#message').val();
$.ajax({
type: "POST",
url: "your_page_with_php_script.php",
data: "name="+name+"&age="+age+"&message="+message,
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
edit the following according to the need:
$.ajax({
type: 'POST',
url: 'your_php_page.php',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
The requesting page should have a div with id="ajax-panel"
You must use Jquery with Ajax...
<script>
$("#submit").click(function()
{
var name = $('#name').value();
var age= $('#age').value();
var message= $('#message').value();
$.ajax({
url: "urpage.php",
data: {name : name, age : age, message : message},
type: "POST",
success: function(output) {
alert(output); //This will show ur output in an alert box
} }
})
});
</script>
Hope this works
Related
This is my first post here. Sorry if my English appears to be bad.
I attempted to use the following codes to submit form data to my signup/submit/index.php.
Here is my sample HTML
<form name="signup_form" id="signup_form" action="submit">
<input type="text" class="form-control" placeholder="CreateUsername" name="username" id="username" autocomplete="off">
<input type="password" class="form-control" placeholder="CreatePassword" name="password" id="password"></form>
Here is my Ajax
.on('success.form.fv', function(e) {
e.preventDefault();
loadshow();
var $form = $(e.target),
fv = $form.data('formValidation');
// Use Ajax
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $('#signup_form').serialize(), //or $form.serialize()
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="2")
{
swal({
type: "success",
title: "HiHi!",
text: "GoodLuck",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
functionA(username,password).done(functionB);
});
}
else (result=="agent_na")
{
swal({
type: "error",
title: "ERROR",
text: "N/A",
animation: "slide-from-top",
showConfirmButton: true
});
Here goes my PhP
<?php
$params = array();
$gett = $_POST["username"];
parse_str($gett,$params);
print_r ($gett); // it prints an empty array
print_r ($gett); // it prints an empty array
echo $params["username"] // it shows undefined username index
?>
I have attempted to serialize $gett before parse_str it. It returns me (){}[].
Could please assist me on this?? I spent almost 20 hours on this, google and tried a lot. Am new to JS.
I try to keep it simple
HTML
<!-- Include Jquery Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="signup_form">
<input type="text" name="username" placeholder="Enter the user name" />
<input type="password" name="password" placeholder="Enter password here" />
<input type="submit" value="Login" />
</form>
<script>
/* Page loaded */
$(function(){
/* Trigger when the form submitted */
$("#signup_form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "backend.php",
data: form.serialize(), // Checkout the document - https://api.jquery.com/serialize/
success: function(data) {
// handle the return data from server
console.log(data);
}
});
e.preventDefault();
return false;
})
})
</script>
PHP (backend.php)
<?php
// Always check param exists before accessing it
if(isset($_POST['username']) && isset($_POST['password'])){
// Print all the post params
print_r($_POST);
// or by param
// echo "User Name: " . $_POST['username']. " <br />";
// echo "Password: " . $_POST['username']. " <br />";
}
?>
Hope this helps!
This is a sample of how you can debug an ajax call:
Javascript:
$(function(){
$("#signup_form").submit(function(e) {
var formData = new FormData($(this));
$.ajax({
type: "POST",
url: "backend.php",
data: formData,
success: function(data) {
console.log(data);
// if (data.length > 0) ....
}
});
e.preventDefault();
return false;
});
});
PHP:
<?php
if (isset($_POST['signup_form'])){
$params = array();
$gett = $_POST['username'];
parse_str($gett,$params);
print_r ($gett);
echo $_POST['username'];
}else{
die('No $_POST data.');
}
?>
Your php code had some problems in it, you missed a semi-colon and you tried to print from an empty array, calls through ajax won't show any run time errors, and thus you need to be very careful when you're trying to debug an ajax to php call.
Hope this helps.
so I have a div called #preview which is just a preview of a survey. I want to send the html value of the div and send it to a GET variable valled content so i can use it in php. here's what i've done:
$('#create-button').click(function(event){
event.preventDefault();
$.ajax({
url:'../php/CheckForExistingSurveys.php',
data:{content: $('#preview').html()}
});
});
in my php script:
<?php
if(isset($_GET['content'])){
echo 'content is set';
}
?>
whenever i click the #create-button i dont see the get variable being initialized in the url. All I want to know is how i can get the html value of the #preview div and send it to a get variable so that I can make queries and what not in the CheckForExistingSurveys.php file.
HTML:
<form action='' method='' id="myform">
Name:<input type='text' name='name' id='name'>
<input type='submit' value='Send'>
</form>
Javascript:
$('#myform').submit(function(){
var name = $('#name').val();
$.ajax({
type: "POST",
url: "your_page_with_php_script.php",
data: "name=" + name,
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
PHP:
<?php
if (isset($_POST['name'])) {
$a = $_POST['name'];
if ($a != NULL) {
echo "Success " . a;
}
};
?>
I use this code for get form data in json object. After submit I get this response:
{ user: "asdf", password: "asdfsadf" }
But the problem is i didn't know how to save this in database using php. If any one knows how to save in db please guide me. Any help is appreciated.
HTML code
<form onsubmit='return onSubmit(this)'>
<input name='user' placeholder='user'><br>
<input name='password' type='password' placeholder='password'><br>
<button type='submit'>Try</button>
</form>
Javascript code
function onSubmit( form ){
var data = $(form).serializeArray(); // <-----------
var json = {};
$.each(data, function() {
json[this.name] = this.value || '';
});
$.ajax({
type: "POST",
url: "php/tracker.php",
data: json,
dataType: "json"
});
}
here is html code
<input name='user' placeholder='user'>
<input name='password' type='password' placeholder='password'><br>
<button type='submit'>Try</button>
here is script
<script> $("button").click(function(){
var user = $("input name=user").val();
var password = $("input name=password").val();
var responce_type = "from-1";
$.post('php/tracker.php',{ user:user, password:password,responce_type:responce_type},function(resp){
resp = $.parseJSON(resp);
console.log(resp);
if(resp.status == true)
{
alert("DONE");
}
else
{
alert("error");
}
}) }) </script>
here is php code
that right in
php/tracker.php
this page
<?php
if(isset($_POST['from-1']))
{
$user = $_POST['user'];
$password = $_POST['password'];
//do some thing in php then send back request
echo json_encode(array("Data" => $_POST , "status" => true )) ;
}
else
{
echo json_encode(array("Data" => $_POST , "status" => false)) ;
}
?>
I have an ajax search function that produces a list of names from database. Each name is echoed back as a form button so when user clicks on the name another ajax call will bring up all info related to that name. However, it is not working. I have tried several variations of the ajax function below but either nothing happens at all or the page just gets refreshed with no results.
Any ideas on how to get this to work?
This is the latest ajax (which does nothing)
$(function GetInfo() {
$('form').on('click', function (e) {
var tourName = $('#tourName').val();
var FirstName = $('#FirstName').val();
var LastName = $('#LastName').val();
alert("PLEASE ENTER A NAME" + FirstName + LastName);
$.ajax({
type: "POST",
url: 'process.php',
data: "tourName=" + tourName + "&firstname=" + firstname + "&lastname=" + lastname,
success: function(data){
$("#search_results").html(data);
}
});
e.preventDefault();
});
});
And this is the php loop that produces the forms (names):
$string = '';
if (mysql_num_rows($query)){
while($row = mysql_fetch_assoc($query)){
$FirstName = $row['FirstName'];
$LastName = $row['LastName'];
$Name = $row['FirstName']." ".$row['LastName'];
$string .= "<form method='post' action=''>
<input type='hidden' name='FirstName' value='$FirstName'>
<input type='hidden' name='LastName' value='$LastName'>
<input type='button' class='button' name='person_name' value='$Name' onClick='GetInfo()'></form><br /><br />\n";
}
}else{
$string = "No matches found!";
}
mysql_close($con);
echo $string;
Just incase anyone has the same issue, I got the following code to work:
function GetInfo(form) {
var person_name = form.person_name.value;
var tourName = form.tourName.value;
var firstname = form.FName.value;
var lastname = form.LName.value;
$.ajax({
type: "POST",
url: "process.php",
data: "person_name=" + person_name + "&tourName=" + tourName + "&firstname=" + firstname + "&lastname=" + lastname,
success: function(data){
$("#search_results").html(data);
}
});
return false;
}
And in the form
$string .= "<form method='post' id='$form'>
<input type='hidden' name='tourName' value='$tourneyName'>
<input type='hidden' name='FName' value='$FirstName'>
<input type='hidden' name='LName' value='$LastName'>
<input type='button' class='button' name='person_name' value='$Name' onClick='GetInfo (this.form)'></form><br /><br />\n";
}
}else{
$string = "No matches found!";
}
You should add an ID to you form and target instead of using $('form') use $('#yourformid')
Use this:
$(function GetInfo(el) {
var tourName = $('#tourName').val();
var FirstName = $(el).siblings('[name=FirstName]').val();
var LastName = $(el).siblings('[name=LasstName]').val();
alert("PLEASE ENTER A NAME" + FirstName + LastName);
$.ajax({
type: "POST",
url: 'process.php',
data: { tourName: tourName, firstname: FirstName, lastname: LastName },
success: function(data){
$("#search_results").html(data);
}
});
e.preventDefault();
});
And you need to change the HTML to use:
onclick='GetInfo(this)'
The solution is posted above. It seems rather simple now that it's done.
$('#send_email').click(function() {
$.ajax({
type : 'POST',
url : '<?php echo base_url()?>contact',
data : $( '#contact_form' ).serialize(),
success : function(msg){
$('#results').html(msg);
if(msg == "Successfully Subscribed"){
$( "#email_news" ).val('');
}
}
});
return false;
});
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.