I don't know what i did wrong in the ajax call. I want to return the data back to my script and work with it but its not returning result. Here are some things i will like to clarify as well as i am new to ajax programming. if the ajax call is successful and it returns result to the script. Where in the script will the result be. Will i have to create an array that holds the result or ...
Here is the html
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
<div id="response"></div>
<div>
<label>Name</label><input type="text" name="name" id="nameid">
</div>
<div>
<label>Phone Number</label><input type="text" name="phone" id="phoneid">
</div>
<div>
<button type="submit" class="btn" id="btnsubmit">Submit</button>
</div>
</form>
<div id="success"></div>
//my script
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
function submitForm(formData){
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
}
If you are trying ajax form submission and need to populate the result in the success div without refresh, you need return false
Don't use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
Here don't need the action in form, try like
<form id="reserveform" onsubmit="return submitForm();">
In function use form serialize so all input elements value in form will available
function submitForm(){
var formData = $("#reserveform").serialize();
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
return false; // use this otherwise the form will be submitted and results an entire page refresh
}
please try this
you have to put the btnsubmit click event inside onload or document ready
$(document).ready(function()
{
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
}
);
You cant use like this $("#success").html(data); because data is in json format. here, the data is an object. You need to parse it and assign to tags.
I see you configured the form to submit to the same document that you are in already. This is fine, we do this all the time.
However, you are also stopping the form from submitting and then using AJAX to submit the values. You specify reservation.php as your ajax processor. Is this the same PHP page you are on already? If so, then I know what the problem is: you can't do that.
By design, AJAX must use an external PHP file to process the AJAX. If you try to do this inside the same document, the AJAX will only echo back the full HTML of the document itself.
Short answer: use an external PHP file. This is by design.
See this other answer for more information about exactly this issue.
See these other posts for further info about AJAX and getting info into the PHP processing script, and returning info back from the PHP processing script:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Related
My page has an html form to collect email, first name, last name and a checkbox. The form begins with this header:
<form action="echo_test.php" method="post" name='register' id='register'>
I submit the form with this button:
<div class="EMail_Pwd_JoinPage"><button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit" onclick="GetDate(); GetCkBx();">Submit data</button></div>
That calls this jquery function:
<script type="text/javascript">
$("#btn_submit").on("click", function (event) {
event.preventDefault();
form_data = $('form').serialize()
console.log("Okay, I'm starting");
console.log(form_data);
console.log("More Info");
GetDate();
return $.ajax({
type: "POST",
url: "echo_test.php",
data: form_data,
success: function (responseText) {
console.log("Server Reply " + responseText);
},
error: function (error) {
console.log("Okay, I failed" + error);
}
});
});
</script>
It submits to echo_test.php on my server:
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
?>
In the onclick event submit code above it should reply from the server:
success: function (responseText) {
console.log("Server Reply " + responseText);
},
But the Chrome dev console does not show any reply. The other console.log messages above do appear correctly (including the serialized form data).
I asked a similar question back in May, but the situation is different here.
Why doesn't this code echo back from the server?
Idk what does onclick attribute mean,
onclick="GetDate(); GetCkBx();"
So i think just remove onclick attribute. And here new code,
<div class="EMail_Pwd_JoinPage"><button type="submit" class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button></div>
Also update your button action jQuery code,
$("#btn_submit").on("submit",
As per my comment, remove onclick="GetDate(); GetCkBx();" from the button tag and call those two functions in the click event handler you created.
New Button Tag:
<button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button>
in echo_test.php return the echo statement or use die().
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
return;
?>
I have a drpcategory dropdown in a form. I will just paste the dropdown code below;
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
Then I AJAX post every time I make a selection in the above drpcategory dropdown as below;
<script>
$(function(){
$('#drpcategory').on('change',function()
{
$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
});
});
</script>
This seems to be currently working as I'm getting outputs like below in Chrome Browser > Inspect > Network tab every time I make a selection in drpcategory. Here is the screenshot;
The question is how can I capture this AJAX post data using PHP within the same page and echo it within the same page? So far I have tried;
<?php
if(isset($_POST['drpcategory']))
{
echo 'POST Received';
}
?>
I'm looking for a solution using only PHP, JQuery and AJAX combined.
This question was later updated and answered here:
AJAX POST & PHP POST In Same Page
First of all, this line -> type: $(this).attr('post') should be type: $(this).attr('method'),. So this will give the value ** type:post** and
As far as i understand, you are asking to send ajax whenever you select options from drpcategory. Why are you submitting the entire form for this. If i where you, i should have done this problem by following way
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
On you php side, you can get your data like,
echo $_POST['drpcategory'];
I recommend you read the documentation for the ajax function, I tried to replicate it and I had to fix this:
$.ajax({
// If you don't set the url
// the request will be a GET to the same page
url: 'YOU_URL',
method: 'POST', // I replaced type by method
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
http://api.jquery.com/jquery.ajax/
OUTPUT:
First change to $value
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category2 = file($category, FILE_IGNORE_NEW_LINES);
foreach($category2 as $value)
{
echo "<option value='".$value."'>".$value."</option>";
}
?>
</select>
then add url
<script>
$(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:'folder/filename.php',
type: 'post',
data: '{ID:" . $Row[0] . "}',
success: function(result) {
console.log(result);
}
});
});
$('#drpcategory').on('change',function()
{
$("#form").submit();
});
});
try request
if(isset($_REQUEST['ID']))
The result will/should send back to the same page
Please try this code:
$.post('URL', $("#FORM_ID").serialize(), function (data)
{
alert('df);
}
I think you have an eroror syntax mistake in ajax jQuery resquest because ajax post 'http://example.com/?page=post&drpcategory=Vehicles' does not return this type url in browser Network Tab.
<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.
Here ajax request example
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
`
It sounds like you're trying to troubleshoot several things at once. Before I can get to the immediate question, we need to set up some ground work so that you understand what needs to happen.
First, the confusion about the URL:
You are routing everything through index.php. Therefore, index.php needs to follow a structure something like this:
<?php
// cleanse any incoming post and get variables
// if all your POST requests are being routed to this page, you will need to have a hidden variable
// that identifies which page is submitting the post.
// For this example, assume a variable called calling_page.
// As per your naming, I'll assume it to be 'post'.
// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
// set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
header('Content-Type: application/json');
print json_encode(array('message' => 'Your submission was received'));
// if this is from an ajax call, simply die.
// If from a regular form submission, do a redirect to /index.php?page=some_page
die;
}
// if you got here, there was no POST submission. show the view, however you're routing it from the GET variable.
?>
<html>
(snip)
<body>
<form id="form1" method="post">
<input type="hidden" name="calling_page" value="page" />
... rest of form ...
<button id="submit-button">Submit</button>
</form>
}
Now, confusion about JQuery and AJAX:
According to https://api.jquery.com/jquery.post/ you must provide an URL.
All properties except for url are optional
Your JQuery AJAX will send a post request to your index.php page. When your page executes as shown above, it will simply print {message: "Your submission was received"} and then die. The JQuery will be waiting for that response and then do whatever you tell it to do with it (in this example, print it to the console).
Update after discussion
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<!-- HTML to receive AJAX values -->
<div>
<label>Item</label>
<select class="" id="drpitem" name="drpitem"></select>
</div>
<script>
$(function(){
$('#drpcategory').on('change',function() {
$.ajax({
url: '/receive.php',
method: 'post',
data: $(this).serialize(),
success: function(result) {
workWithResponse(result);
}
});
});
});
function workWithResponse(result) {
// jquery automatically converts the json into an object.
// iterate through results and append to the target element
$("#drpitem option").remove();
$.each(result, function(key, value) {
$('#drpitem')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
</script>
receive.php:
<?php
// there can be no output before this tag.
if(isset($_POST['drpcategory']))
{
// get your items from drpcategory. I will assume:
$items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');
// send this as json. you could send it as html, but this is more flexible.
header('Content-Type: application/json');
// convert array to json
$out = json_encode($items);
// simply print the output and die.
die($out);
}
Once you have everything working, you can take the code from receive.php, stick it in the top of index.php, and repoint the ajax call to index.php. Be sure that there is no output possible before this code snippet.
I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.
I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.
I'm using jquery tabify with 4 tabs and each content same form calling via ajax.(assume form.php)
1st tab everything works fine with the form.
2nd,3rd and 4th tab failed to get input type="text" value
tabify field with (4 tabs here actually I make it short as the code is long):
$(document).ready(function () {
$('#general_information_tab').tabify();
});
function recp(refer,id,plan){
if(plan == 0)
{
$('.stgcontent').load('stage/stage_procedure1.php?plan_id=' + id + '&T_REFERID=' + refer );
}else{
$('.stgcontent').load('stage/new_taskstg.php?plan_id=' + id + '&T_ID=' + refer);
}
<div id="general_tab_content">
<ul id="general_information_tab" class="general_information_tab">
<li class="active"><a href="#one" onClick="recp('1','<?php echo $plan_id; ?>','0')" >Immediate Response Steps</a></li>
<div id="one" class="content_gi">
<div class="stg1">
<img src="images/task/add.ico" height="10px" width="10px" /> Add Task
<div class="stgcontent">
<script type="text/javascript">
recp('1','<?php echo $plan_id; ?>','0');
</script>
</div>
</div>
</div>
in new_taskstg.php
$(function(){
$(".newTaskSubmitBtn").click(function(){
var T_CONTENT = $(".task_name").val();
var T_REFERID = $(".refer").val();
var SAVE_PLAN = $(".plan").val();
var V_ID = $(".vendor").val();
var dataString='T_CONTENT=' + T_CONTENT + '&T_REFERID=' + T_REFERID + '&SAVE_PLAN=' + SAVE_PLAN + '&V_ID=' + V_ID;
alert(T_CONTENT + T_REFERID + SAVE_PLAN + V_ID);
if(T_CONTENT=='' || T_REFERID=='' || SAVE_PLAN=='' || V_ID=='')
{
//ERROR MESSAGE
$(".fail").show();
$(".success").hide();
}
else
{
$.ajax({
type: "POST",
url: "stage/insert.php",
data: dataString,
success: function(data){
//SUCCESS MESSAGE
$(".success").show();
$(".fail").hide();
}
});
}
return false;
});
});
form field code:
<input type="text" name="task_name" class="form_input task_name" />
TEST I DID :
As above var T_CONTENT = $(".task_name").val(); and prompt like this alert(T_CONTENT); what it shows on 1st tab it able to capture it while the 2nd 3rd and 4th tab failed...
Was suspecting multiple instances problem...
Problem Solved. Mian point is to avoid from multiple instances since tabify couldn't differentiate which tab the form is and it takes 4 tabs together. So to solve my case I just use unique id in 4 forms.