How to access PHP super global post variable after AJAX request - php

I have a form in index.php:
<form action="submit.php" method="post" id="registerSubmit">
<input type="text" name="name" id="name" placeholder="Name">
<button id="submit" type="submit">Submit</button>
</form>
<div id="result"></div>
When the form is submitted it gets intercepted by Jquery:
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "load.php",
method: "post",
data: "",
dataType: "text",
success: function(Result) {
$('#result').text(Result)
}
})
});
});
However, when the AJAX request gets sent to load.php. I am not able to access the super global post variable:
<?php
$name = $_POST['name'];
echo $name;
?>
I'm able to access the form data through Jquery, but I didn't want to have to parse JSON to send to Mysql. How can I access the super global post form data after the AJAX request and if it's not accessible, what are best practices for sending php form data through Ajax to Mysql?

You need to pass data through AJAX call
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "load.php",
method: "POST",
data: $(this).serialize(), // Send all form data to AJAX
dataType: "text",
success: function(Result) {
$('#result').text(Result)
}
})
});
});

You need to pass data through AJAX call When the form is submitted.
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
var name = document.getElementById("name").value;
var dataString ='name=' + name;
$.ajax({
url: "load.php",
method: "post",
data: "dataString",
dataType: "text",
success: function(Result) {
$('#result').text(Result)
}
})
});
});
In the load.php page
<?php
$name = $_POST['name'];
echo $name;
// code for insert in mysql with PHP.
?>

Related

Use AJAX Return value to PHP function

My ajax successfully return the value but my problem is I can't use the value to my function. How do I convert this div to a value?
<?php
echo $ajax_user_id = '<div id="result"></div>'; //value can display here
getName($ajax_user_id); //value wont work here
?>
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result)
}
})
});
});
</script>
You can't use it that way.because jQuery is a scripting language which runs in browser when DOM is fully loaded and elements are available to make selectors.While php is server side language which runs on server way before page load.anyway to fulfill your need you can try something like this.
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result);
getNameAjax(Result);
}
})
});
});
function getNameAjax(val)
{
$.ajax({
type: "POST",
url: GetNameAjax.php,
data:{'user_id':val},
success: function(res){
$('#name').html(res);
}
});
}
</script>
GetNameAjax.php file you can write like this
$ajax_user_id=$_POST['user_id'];
function getName($ajax_user_id)
{
return "name on the basis of id";
}

On button click perform ajax for sending values in forms are in while loop

How can I send input values through AJAX on button click? My code is below. Thanks in advance.
while
{
<form class="commentform">
<input type="hidden" class="proid" name="proid" value="<?=$rr['id']?>">
<input type="text" class="form-control" name="comval" placeholder="Write a comment.." autocomplete="off">
<button class="btn btn-post" type="button">Post</button>
</div>
</form>
}
$(document).ready(function() {
$(document).on('click', '.btn-post', function(){
var thePostID = $(this).val;
$.ajax({
url: 'fetch_comments.php',
data: { postID: thePostID },
type: 'POST',
success: function() {
alert(data);
}
});
Firstly, the correct method is $(this).val(), not just $(this).val.
Secondly, you can simplify your code by getting the data from the closest form element using serialize(). Try this:
$(document).on('click', '.btn-post', function() {
var $form = $(this).closest('form');
$.ajax({
url: 'fetch_comments.php',
data: $form.serialize(),
type: 'POST',
success: function() {
alert(data);
}
});
});
$("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.

jQuery Ajax function not working. Php code is working without errors

I was trying to use AJAX to submit form data to a .TXT file using PHP code.
The results are getting added to the text file but AJAX functionality is not working. Please let me know the error in my code.
Here is the Code for the form:
<div id="page-wrapper">
<h1>AJAX Sign Up Form </h1>
<div id="form-messages"></div>
<form id="signup" method="post" action="mailer.php">
<div class="field">
<input type="email" id="email" name="email" placeholder="Enter Your Email" required>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
Here is the jquery(2.1.1) code
$(document).ready(function() {
$("#sign_btn").click(function(event){
var mail = $("#mail").val();
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: mail
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
});
});
Here is the mailer.php
<?php
$email = $_POST["email"];
$fp = fopen("signup.txt", "a");
$savestring = "$email\n";
fwrite($fp, $savestring);
fclose($fp);
echo "<h1>Thank You For Subscribing</h1>";
?>
Instead of
data: mail
use
data: {email: mail}
because, in PHP you're looking for $_POST["email"] which means, $_POST array has a key named email with some value.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Send your data (as a object) above in my code
Thanks
You can go with any of the folowing :
only if mail is an object that has all the input of a form like
var mail = new FormData($(this)[0]); // on form submit ofcourse
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: mail
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
if you want to send a single variable via ajax to php then give the data its key so that you can access it by that key in php like this
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: "mail=" + mail,
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
The button id is missing in the form code...

Update textarea From User Input by jQuery and Ajax

I am trying to update a value in my php file and present it in a textarea using jquery and ajax. to make it short, I have:
1- A Form with User Input and Submit button and a Text area
2- A PHP file called data.php
3 -and the html file
Here is my codes
<form>
<input type="text" name="name"><br>
<textarea name="wstxt" id="wstxt" cols="40" rows="5"></textarea>
<input type="button" name="txta-update" id="txta-update" value="Update Textarea" />
</form>
PHP is as simple as:
<?php
$name = "Jordano";
echo $name;
and here is the jquery
$(document).ready(function() {
$('#txta-update').click(function() {
$.ajax({
type: "GET",
url: "data.php",//get response from this file
success: function(response){
$("textarea#wstxt").val(response);//send response to textarea
}
});
});
});
can you please tell me how I can send the input value to php and update the textarea from new value?
Thanks
Update
Send data like this
data:{name:$('input[name="name"]').val()}
you js file becomes
$.ajax({
type: "GET",
url: "data.php", //get response from this file
data:{name:$('input[name="name"]').val()},
success: function (response) {
$("textarea#wstxt").val(response); //send response to textarea
}
});
or
$(document).ready(function () {
$('#txta-update').click(function () {
var name_val = $('input[name="name"]').val();
$.ajax({
type: "GET",
url: "data.php", //get response from this file
data: {
name: name_val
},
success: function (response) {
$("textarea#wstxt").val(response); //send response to textarea
}
});
});
});
To get value in PHP
<?php
$name = $_GET['name'];
echo $name;
?>

$.ajax( type: "POST" POST method to php

I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:
<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=f.title.value;
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
And this is the php code on the server :
<?php
$title = $_POST['title'];
if($title != "")
{
echo $title;
}
?>
The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.
You need to use data: {title: title} to POST it correctly.
In the PHP code you need to echo the value instead of returning it.
Check whether title has any value or not. If not, then retrive the value using Id.
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
In php code, use echo instead of return. Only then, javascript data will have its value.
try this
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
function signIn()
{
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
type: 'POST',
url: "auth_loginCode.jsp",
data: {Username: Username, Password: Password},
success: function (data) {
alert(data.trim());
window.location.reload();
}
});
}
contentType: 'application/x-www-form-urlencoded'

Categories