PHP page not recieving POSTed jquery ajax request - php

I have my first PHP page having search form:
<form action="#" class="form-inline" id="form_srch">
<input type="text" id="toSearch" name="toSearch" placeholder="Enter Application Number" class="form-control" style="width:250px" required >
<button type="button" class="btn btn-primary" onclick="search()">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
<i><b><p style="display:none;color:red" id="result">** Empty Value</p></b></i>
</form>
<div id="ajax"></div>
and a javascript function
<script>
function liveCheck() {
$("#result").show();
}
function search() {
var inp = $("#toSearch").val();
if(jQuery.trim(inp).length > 0)
{
jQuery.ajax({
url: "load_search_prereg.php",
data:{ to : inp },
type: "POST",
success:function(data){
$("#ajax").load('load_search_prereg.php');
//alert(data);
},
error:function (){}
});
}
else{
liveCheck();
}
}
</script>
And i have my second PHP page named load_search_prereg.php to process the POSTed input and the code is
<?php
require '../backend/_classes.php';
$x = new DB();
$id = $_POST['to'];
$sql=$x->select(1,'*','tblregistration','app_number',"'$id'");
$fetch = $sql->fetchObject();
var_dump($fetch);
The problem is when i clicked the search button in my first PHP page, It displays no array of posted data while im using the $("#ajax").load('load_search_prereg.php'); method in my javascript. But when i use alert(data);, it returns the expected result. Does the problem occur in $("#ajax").load('load_search_prereg.php'); method ? Help pls.

Not:
$("#ajax").load('load_search_prereg.php');
But:
$("#ajax").html(data);
I've assumed you just want to write this data into div
edit:
instead of var_dump($fetch); you must return your data a JSON object, eg:
$fetch = $sql->fetchObject();
echo json_encode($fetch);
Then you can do in js what you want

It should be method:"POST" instead of type: "POST".
By default method is set to GET.

Related

PHP and AJAX update data to database

I'm trying to update a simple string to the database with PHP and AJAX.
Here is the code:
HTML
<form id="phoneNumberForm" class="form-inline" method="post" enctype="multipart/form-data">
<div class="form-group mx-sm-3 mb-2 align-content-center">
<label for="phoneNumber" class="sr-only">Phone</label>
<input type="text" class="form-control" name="phoneNumber" id="phoneNumber" placeholder="Phone">
</div>
<button type="submit" name="phoneNumber_submit" id="phoneNumber_submit" class="btn btn-primary mb-2">Save</button>
<div id="phoneSuccess"></div>
</form>
PHP
if (isset($_POST['phoneNumber_submit'])) {
$phoneNumber = $_POST['phoneNumber'];
$profileEditAdmin = $db->query('UPDATE users SET user_phone = ? WHERE user_name = ?', $phoneNumber, $_SESSION['user_name']);
}
AJAX
$('#phoneNumberForm').submit(function(e) {
e.preventDefault();
let phoneNumber = $('#phoneNumber').val();
let $body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
$.ajax({
type: "POST",
data: {
phoneNumber:phoneNumber,
},
success: function() {
$('#phoneSuccess').html('<p>Saved.</p>');
setTimeout(function() {
$('#phoneSuccess').fadeOut();
}, 2000)
}
});
});
When I remove preventDefault() I get the entry in the database, but page is reloaded.
My goal is to have an entry in the database and to avoid page refreshing.
Here your PHP looks for a variable called phoneNumber_submit:
if (isset($_POST['phoneNumber_submit'])) {
But here your AJAX sends only a variable called phoneNumber:
data: {
phoneNumber:phoneNumber,
}
Clearly these two names do not match, so the if statement will never be true and the query will never run. It works when you submit the form without AJAX because you have name="phoneNumber_submit" on your submit button, so this value is sent to the server.
So you can either:
1) hard-code this value into your data parameter:
data: {
"phoneNumber": phoneNumber,
"phoneNumber_submit": true
}
OR
2) just let jQuery do the work for you and use the serialize function to get all the values and names you've already defined in your HTML and send them directly to the server, without you needing to specify each one again:
data: $(this).serialize()
Note: this in the above code will be your <form> element since you're handling the form's "submit" event.

wizard-form tow button different call ajax

I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)

ajax form submit -> receive respone from php

I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="Zmień" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.

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
}

Form posts data twice

I have a feedback form in a pop-up div that otherwise works fine but processes SQL twice when the form results in error at first instance.
This is the html form:
<div id="stylized" class="myform">
<form id="form" method="post" name="form">
<p>Report:
<select id="fbtype" name="fbtype">
<option>Bug</option>
<option>Suggestion</option>
<option>Discontentment</option>
<option>Appreciation</option>
</select>
</p>
<p>Brief description:
<textarea name="comments" id="comments" cols="45" rows="10"></textarea>
</p>
<span class="error" style="display:none">Please describe your feedback.</span>
<span class="success" style="display:none">We would like to thank you for your valuable input.</span>
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
</form>
</div>
The feedback_form_submit() function is:
function feedback_form_submit() {
$(function() {
$(".submit").click(function() {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
}
And the processfeedback.php has:
include "./include/session_check.php";
include_once "./include/connect_to_mysql.php";
if (isset($_POST['fbtype'])){
$userid =$_SESSION['id'];
$fbtype=$_POST['fbtype'];
$comments=$_POST['comments'];
$sql = mysql_query("INSERT INTO feedback (userid, type, comments)
VALUES('$userid','$fbtype','$comments')") or die (mysql_error());
}
Could anyone figure out why does the form submits twice? And any suggestion to control this behaviour?
If this is actually the code you're using, you seem to have wrapped your onclick function around the $.click event-adding function:
function feedback_form_submit() {
$(function() {
// This adds a click handler each time you run feedback_form_submit():
$(".submit").click(function() {
// ... //
return false;
});
});
}
When I tried this on jsFiddle.net, I clicked Submit the first time and nothing happened, then the second time it posted twice, the third click posted three times, etc.
You should just keep it simple: take out the onclick attribute:
<input type="button" value="Submit" class="submit" />
and remove the feedback_form_submit() wrapper:
$(function() {
$(".submit").click(function() {
// ... //
return false;
});
});
This way the $.click handler function will be applied just once, when the page loads, and will only run once when Submit is clicked.
EDIT:
If your form is loaded via AJAX in a popup DIV, you have two options:
Keep your onclick but remove the $.click wrapper instead:
function feedback_form_submit() {
// ... //
}
and
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()" />
Note that you only need to return false if you're using <input type="submit" ... >; when using <input type="button" ... >, the browser does not watch the return value of onclick to determine whether to post the form or not. (The return value may affect event propagation of the click, however ...).
Alternatively, you can use jQuery's $.live function:
$(function() {
$('.submit').live('click',function() {
// ... //
});
});
and
<input type="button" value="Submit" class="submit" />
This has the effect of watching for new DOM elements as they are added dynamically; in your case, new class="submit" elements.
Your feedback_form_submit function doesn't return false and on submit click you're also posting to the server. There is no need to have onClick in:
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
Change that to:
<input type="button" value="Submit" class="submit"/>
And change your code to:
// Update: Since you're loading via AJAX, bind it in the success function of the
// AJAX request.
// Let's make a function that handles what should happen when the popup div is rendered
function renderPopupDiv() {
// Bind a handler to submit's click event
$(".submit").click(function(event) {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
// This is the success function for the AJAX request that loads the popup div
success: function() {
...
// Run our "onRender" function
renderPopupDiv();
}

Categories