PHP not capture $_POST data send by ajax jquery on same page - php

I am using ajax to post data on the same page and trying to echo posted data with php with following script.
$('button').click(function(){
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function(){},
success: function(data){alert(data)},
error: function(err) {alert(err.responseText);}
})
})
and php script is :
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
my html is:
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
My problem is php does not echo posted data on page, but when i post form data on another php file which is same php script; php is able to echo posted data and ajax is alert that. please help me to resolve this issue. thanks

It's difficult to tell without seeing your entire PHP page as one listing, but from your description it sounds like your issue is either because of the way you are declaring your .click() event or the way you are posting to the page. The former is more likely.
The $.ajax() request will use an XMLHttpRequest object to POST to your PHP script. The PHP script should then take those values and generate the return string from the combination of the plain text in the script and the inserted echo'd values. This should then be received by the success method's callback function and alerted to your page as a blob of HTML text in the alert box.
Indeed, this is exactly what happens if I use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function() {},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err.responseText);
}
});
});
});
</script>
</head>
<body>
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
</body>
</html>
However, if I comment out the lines for $(document).ready(function(){ and its corresponding end });, then nothing happens when I click.
So, try wrapping your .click() event definition in a $(document).ready().

Related

value is not coming $POST array in php

I am building a simple sign up form using ajax when I creating a data object and pass to PHP file.It shows variables and doesn't show values of that PHP variable.
The code of HTML of form is
<form id="myForm" name="myForm" action="" method="POST" class="register">
<p>
<label>Name *</label>
<input name="name" type="text" class="long"/>
</p>
<p>
<label>Institute Name *</label>
<input name="iname" type="text" maxlength="10"/>
</p>
<div>
<button id="button" class="button" name="register">Register »</button>
</div>
</form>
The code of js is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
The code of PHP is
(mainlogic.php)
if(isset($_POST)) {
print_r($_POST);//////varaibles having null values if it is set
$name=trim($_POST['name']);
echo $name;
}
You are serializing your form on document load. At this stage, the form isn't filled yet. You should serialize your form inside your button click event handler instead.
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
In this code you serialize blank form, just after document is ready:
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Valid click function should begins like:
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({...
It means - serialize form right after button clicked.
var form = $("#myForm").serialize();
That is the line that collects the data from the form.
You have it immediately after $(document).ready(function() { so you will collect the data as soon as the DOM is ready. This won't work because it is before the user has had a chance to fill in the form.
You need to collect the data from the form when the button is clicked. Move that line inside the click event handler function.
The problem is that you calculate the form values at the beginning when loading the page when they have no value yet. You have to move the variable form calculation inside the button binding.
<script>
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Alpadev got the right answer, but here are a few leads that can help you in the future:
ajax
You should add the below error coding in your Ajax call, to display information if the request got a problem:
$.ajax({
[…]
error: function(jqXHR, textStatus, errorThrown){
// Error handling
console.log(form); // where “form” is your variable
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
$_POST
$_POST refers to all the variables that are passed by the page to the server.
You need to use a variable name to access it in your php.
See there for details about $_POST:
http://php.net/manual/en/reserved.variables.post.php
print_r($_POST); should output the array of all the posted variables on your page.
Make sure that:
⋅ The Ajax request ended correctly,
⋅ The print_r instruction is not conditioned by something else that evaluates to false,
⋅ The array is displayed in the page, not hidden by other elements. (You could take a look at the html source code instead of the output page to be sure about it.)

AJAX - form submit, same page, PHP

EDIT: I have changed the AJAX code to what I am now using and I have also included JQuery in my code
I've read up on as much AJAX as I can and I am flat out failing!
My HTML form looks like this:
<form action="match_details.php" method="post" id="match_details">
....
<button type="submit" form="match_details" name="match_details" class="w3-button w3-block w3-mam w3-section" title="Update Match Postcode">Update</button>
</form>
From Stack I've managed to get this AJAX:
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
I've tried changing it from button to input and back again but nothing seems to change. The form still submits but it ignores the AJAX and the page refreshes.
You need to prevent the JS from submitting the form, and you're using the wrong form ID. Also, judging by the comments, you need to include jquery.
In the head of your HTML file, between <head> and </head> or just before the closing </body> tag, you can use the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The following code may help you (though it's advised to not query the same page as your ajax request emits from):
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>

Cant .ajax() submit a php form that has been loaded onto main page with jQuery .load()

I'm having the following problem. Below is an explanation of what my PHP pages are and how they work. When I access form.php directly and try to submit it via AJAX, it works perfectly.
Problem - When I .load() form.php into main.php, none of the jQuery code within form.php fires. (verified through firebug) No submits, no alerts, nothing. How can I get the jQuery code within form.php to work when its loaded into main.php?
main.php -> This is the main PHP page which has a link on it. Once this link is clicked, the following jQuery code fires to load "form.php" within a div called #formcontainer. This is the code within main.php that loads form.php.
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php");
});
});
</script>
form.php -> this is a form that gets loaded above. It submits data to MySQL through an jQuery .ajax() POST. Here is the jquery code which submits the form, which has an ID called #homeprofile.
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$(document).ready(function() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
});
Use on() for this like,
$(document).on('submit','#homeprofile',function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
return false;
});
You should be using the .on() syntax for targeting dynamically created elements (elements loaded into the DOM by JS or jQuery after the initial rendering)
Good
// in english this syntax says "Within the document, listen for an element with id=homeprofile to get submitted"
$(document).on('submit','#homeprofile',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Not as good
// in english this syntax says "RIGHT NOW attach a submit listener to the element with id=homeprofile
// if id=homeprofile does not exist when this is executed then the event listener is never attached
$('#homeprofile').on('submit',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Hopefully this helps!
Small issue is that you reference formcontaineropen in the jquery call (this is probably a typo?). The cause is that that a JS code loaded via AJAX will get interpreted (therefore eval() is not needed) but the document ready event will get triggered immediately (which may be before the AJAX loaded content is actually inserted and ready in the document - therefore the submit event may not bind correctly). Instead you need to bind your code to success of the AJAX request, something like this:
main.php:
<html>
Foobar
<div class="formcontainer"></div>
<script src='jquery.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontainer").load("form.php", '',
function(responseText, textStatus, XMLHttpRequest) {
onLoaded();
});
});
});
</script>
form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type="text/javascript">
function onLoaded() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
};
</script>
My solution is somewhat peculiar but anyhow here it is.
This would be your main.php:
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php", '', function(response){
var res = $(response);
eval($('script', res).html());
});
});
});
</script>
And this is your form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
</script>

passing a value to php from textbox using jquery doesnt work please help

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5b1.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script>
<input type="text" id="textbox">
<button id="inlinesubmit_button" type="button">submit</submit>
<script>
function call_this()
{
alert(<?php echo $_POST['text'];?>);
}
$('#inlinesubmit_button').click(function(){
$.ajax({
type: "POST",
url: "sync_loading1.php",
data: {text:$('#textbox').val()}
});
call_this();
});
</script>
this gives undefined in alert box please help me in pointing out what am I doing wrong
You probably need to wrap it in quotes (' or "), to make it a string.
alert('<?php echo $_POST['text'];?>');
It also appears you are overlooking something with how JavaScript runs (client side) and PHP (server side). They can't directly communicate; PHP can echo JavaScript, and JavaScript can make HTTP requests to PHP files.
Hard to figure out what you're doing... but the key is that you need the client code, plus the server handler.
Your HTML:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5b1.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script>
<script type="text/javascript">
function call_this(data, status, xhr)
{
alert(data);
}
$(document).ready(function(){
$('#inlinesubmit_button').click(function(){
$.ajax({
type: "POST",
url: "sync_loading1.php",
data: {text:$('#textbox').val()},
success: call_this
});
});
});
</script>
<input type="text" id="textbox">
<button id="inlinesubmit_button" type="button">submit</submit>
sync_loading1.php
<?php
// Perform action. Maybe you want to log this into a DB.
// Maybe you want to just print out some text:
echo nl2br('Hello world. Here was my input:'.$_POST['text']);
This function isnt going to work sadly, you are running an ajax call to an external file, and the external file cant do an alert because its not being viewed by the user. if you want to alert the data of the text field, just do alert($('#textbox').val());

simple jquery fetch from mysql

I am trying to use jQuery with MYSQL and I wrote something like this :
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function example_ajax_request() {
$('#example-placeholder').html('<p>Loading results ... <img src="ajax-loader.gif" /></p>');
$('#example-placeholder').load("loadres.php");
}
</script>
</head>
<body>
<div id="query">
<select name="show" id="box" >
<option value="0">Select A Test</option>
<option value="All">--All--</option>
<option value="M1">Model1</option>
</select>
<input type="button" onclick="example_ajax_request()" value="Click Me!" />
</div>
<div id="example-placeholder">
<p>Placeholding text</p>
</div></body>
</html>
Basically I want to pass parameters to the loadres.php file. But unable to figure out the exact way to do.
Any help is appreciated.
Thanks.
You should use the $.ajax() method from jQuery. you can pass data to the url and have a callback at the end.
$.ajax({
url: 'loader.php',
data: 'somedata',
type: 'GET',
success: function(data){
$('#example-placeholder').text(data);
}
});
This will do the trick. This method also provides far more flexibility. You can have different functions such as error functions and complete functions.
$('#example-placeholder').load("loadres.php?show=" + $('#box option:selected').val());
This will use jquery to get the selected value from the drop down list and append it to the URL as a querystring parameter, which you can access in the loadres.php page.
similar to saif-bechan's post you can use ajax with post and data can hold an object to pass multiple parameters
$.ajax({
type:"POST",
url: loadres.php,
data: {
foo:'bar',
selected:$('#selector').val()
},
dataType: 'json',
error: function(data) {
//error code here
},
success: function(data) {
//success code here
}
});
I will also note that is is better to put your click event in jquery context not in the html
so in script somewhere use
$('#button_id').click(function(){
//call to ajax
};

Categories