Implement Ajax to load HTML depending on radio button value - php

Hello I am really new to AJAX PHP and JQuery so any suggestion is really apprecciated.
I have an HTML page with a form, in this form I have 3 radio buttons with 3 values. My objective is to print some HTML depeding on this values.
For example if I select the radio button 2 (value=2) so -->
echo <input type="text">
echo <input type="text">
I managed to print the value in a empty div under the buttons but I don't know how to generate code with the $_POST variable (I tried to iclude the action page but it didn't work)
HTML:
<div class="hide">
<input type="radio" name="cat_2" value="1">One
<input type="radio" name="cat_2" value="2">Two
<input type="radio" name="cat_2" value="3">Three
</div>
<div id="response"></div>
<?php include 'gen.php'; ?> //my failed test
JQuery:
<script>
$(document).ready(function () {
$('.hide input[type="radio"]').click(function(){
var value= $(this).val();
$.ajax({
url: "ajax_page.php",
type: 'post',
data: {ajax: 1, value: value},
success: function (response) {
$('#response').text(value);
}
});
});
});
</script>
ajax_page.php just to test the value:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['value'];
} else {
echo "Nothing to Show";
}
?>
I don't know if I was enough clear, any idea would be really helpful I don't even know what to search for :)

gen.php is run before the webpage is sent to the browser. You won't be able to access any return variables or information from the ajax call because the gen.php code will already have run. gen.php will need to have all the information BEFORE it runs/the browser loads the page. If you need code to run AFTER the browser loads the page, you'll have to do that on your ajax_page.php.
Just a hint for your ajax_page. You should avoid using the supervariables directly and filter the input first (to prevent malicious or accidental problems). Something like this:
if($value = filter_input(INPUT_POST, "value", FILTER_VALIDATE_INT)){
echo $value;
} else {
echo "Nothing to Show";
}
You should capture the error from the ajax call as well and log it to the console (or present it to the user). Here is how you can log it to the console.
$(document).ready(function () {
$('.hide input[type="radio"]').click(function(){
var value= $(this).val();
$.ajax({
url: "ajax_page.php",
type: 'post',
data: {ajax: 1, value: value},
success: function (response) {
// Loop to output repeated HTML
var output = "";
for (i = 0; i < response; i++) {
// Put the HTML in here for example you could create the output:
output = output + "<p>test</p>";
}
// and then display it
$('#response').html(output);
},
error: function (response){
console.log(response)
}
});
});
});

Related

Submit Form Without Reloading Page and Get Output [PHP, jQuery]

Hellow,
I've been trying to submit a form without reloading and getting PHP output on the same page. The main objective is to submit the form values to a PHP file and get the output sent by the PHP file.
To understand it better, let's take a look on following code snippet:
HTML & jQuery Code:
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input id="name" name="name"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP Code:
<?php
if (isset($_POST['submit'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
}
else{
echo "I Dont Know You";
}
}
?>
What I Want:
When user enter value in the Input box and submit it, the page should display output value e.g ECHO value without reloading the webpage.
To be more specific on my first comment, you have to put an exit statement after you echo the response so the rest of the code doesn't execute, also to check whether the form was sent or not you can add a hidden input in your form with the value "1" (<input name="formSent" type="hidden" value="1">) that gets checked in your PHP :
<?php
if (isset($_POST['formSent'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
exit;
}
else{
echo "I Dont Know You";
exit;
}
}
?>
and then get the response from the ajax request in the success's callback parameter, also specify the method: 'POST' because jQuery's $.ajax function uses the method GET by default:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
method: 'POST',
data: $('form').serialize(),
success: function (message) {
alert(message);
}
});
});
});
</script>

Jquery Post ajax variables wont enter PHP

I have the following code:
$(document).on('submit', function (event) {
event.preventDefault();
console.log('submitting');
hostingURL = '/<?echo $this->CI->uri->uri_string();?>';
$('form').attr('action', hostingURL);
var form = $(this);
$.ajax({
type: "POST",
url: hostingURL,
data: form.serialize()
}).done(function (data) {
$(document).unbind("submit");
$("#maincenter").html(data);
console.log('posted');
}).fail(function (data) {
alert('failed');
});
});
this is getting the requested url, and change the form to the action needed, then posting it to the server, and returning data.
server sided i have:
echo print_r($_POST);
echo "<br> type: ".$_SERVER['REQUEST_METHOD']." <br>";
It seems like whatever i do in my form wont acually submit it. The data back is correct, but from the server side code response i do get: Array ( ) 1 type: GET no matter what im doing.
So my question is: How can i acually make the form submit the post data?
The jquery function will be used on all my forms, so i need to get every field in the form to be submitted to.
Below is one example form.
example form:
<form method="POST">
<textarea class="textarea col-12" style="height:150px;" id="messageholder" name="profiltekst" placeholder="Profiltekst">
<? echo $userprofile->profiletext ?>
</textarea>
<div class="bottomform">
<input type="submit" class="makecenter" name="updateprofile" value="Endre profiltekst">
</div>
</form>

Undefined index error in php using ajax

<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
<input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required id='contact_no'>
<br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
<button type="reset" class="btn btn-default" id='reset'>Reset</button>
</form>
Ajax and Javascript Code
script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dialcode = $(".country-list .active").data().dialCode;
var contact = $("#contact_no").val().replace(" ","");
var countrycode = $('.country-list .active').data().countryCode;
var cn;
var cc;
var dc;
$.ajax({
url: "test.php",
type: "POST",
data: {'cc' : contact},
success: function(data)
{
alert("success");
}
});
});
});
</script>
The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement
test.php is as follows
<?php
if(isset($_POST['submit'])){
$contact = $_POST['cc']; //it shows the error here
}
echo $contact;
I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help
You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:
$('#submit').on('click', function()
{
//do stuff
$.ajax({
data: {cc: contact},
method: 'post',
success: function()
{
//handle response here
}
});
return false;
});
Then, in PHP:
if (isset($_POST['cc']))
{
//ajax request with cc data
}
Also not that this:
$("#contact_no").val().replace(" ","");
Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:
$("#contact_no").val().replace(/\s+/g,"");
You are using ajax to form submit
and you use $_POST['submit'] to check it would be $_POST['cc']
test.php
<?php
if(isset($_POST['cc'])){// change submit to cc
$contact = $_POST['cc'];//it shows the error here
}
echo $contact;
#Saty answer worked for me, but my code on ajax was a bit different. I had multiple form data wrapped up into a form variable, that was passed to the php page.
const form = new FormData();
form.append('keywords', keywords);
form.append('timescale', timescale);
form.append('pricing_entered', pricing_entered);
$.ajax({
url: "../config/save_status.php",
data: form,
method: "POST",
datatype: "text",
success: function (response, data) {
}
Then my php was:
if (isset($_POST['data'])) {
// all code about database uploading
}

Callback message for php form

I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>

JQuery's ajax post request does not work as it's supposed to be

The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/

Categories