AJAX Passing Form Data - javascript

I am trying to figure out why this is not working. Here is the sub-set of my form that looks like this:
<input type="hidden" id="gift_id3" name="giver3gift_id" value="925"></td>
<tr id="tr3">
<td>
<select class="type" id="type3" name="giver3paymenttype_val">
<option value="1" SELECTED>Check</option>
<option value="2">Cash</option>
<option value="3">ACH</option>
<option value="4">In Kind Donation</option>
</select>
</td>
<td><input type="text" class="refnum" id="refnum3" name="giver3ref_num" value="2147483647"></td>
<td><input type="text" class="amount" id="amount3" name="giver3amount" value="25.00" onBlur="this.value=formatCurrency(this.value)"></td>
<td>
<select class="type" id="type3" name="giver3taracct_val">
<option value="1" SELECTED>General Fund</option>
<option value="2">Building Fund</option>
<option value="3">Missions Fund</option>
</select>
</td>
<td><input type="checkbox" id="void3" name="giver3void">
</tr>
Here is my AJAX:
var $inputs = $("#dialog-editgiving :input");
var parameters = [];
$inputs.each(function() {
parameters[this.name] = $(this).val();
});
$.ajax({
url : "./scripts/form_process/update_giving.php",
type: "POST",
data : {parameters:parameters},
success: function(data, textStatus, jqXHR)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
Here is my update_giving.php file
<?php
foreach ($_POST as $key => $value) {
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
}
?>
When I look through the $inputs array, I get the the values that are submitted in the form. Then it is handed off to the "./scripts/form_process/update_giving.php" script, I get nothing in the POST object.
Do I have something incorrect in my AJAX request?

instead of this code
var $inputs = $("#dialog-editgiving :input");
var parameters = [];
$inputs.each(function() {
parameters[this.name] = $(this).val();
});
use
var paramerter = $( '#dialog-editgiving' ).serialize();
for fetching all input from the form..
and fetch data in update_giving.php file as yoy fetch in normal php function
for example
$_POST['giver3taracct_val'];
i hope this code will help you.

Try to execute the code at form submit and serialize all the data using serialize()
try something like this:
$('form').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
url : "./scripts/form_process/update_giving.php",
type: "POST",
data : data,
success: function(data, textStatus, jqXHR)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});

for use the register page
<script>
function my_user(user_name){
var dataString = 'user_name='+ user_name +'&tbl_name='+ tbl_name+'&valid_user='+ valid_user;
$.ajax({
type: "POST",
url: "user_ajax.php",
data: dataString,
cache: false,
success: function(data) {
if(data == 1){
$("#user_exits").html("User Name Already Exist!");
$('#btn_submit').addClass("disabled");
//$("#user").focus();
}
else if(data == 0){
$("#user_exits").addClass("hide");
$('#btn_submit').removeClass("disabled");
}
}
});
}
</script>
<input required type="text" class="form-control" placeholder="User Name *" id="user" name="v_user_name" onblur="my_user(this.value)" value="<?php echo $user_name; ?>" autofocus >
//user_ajax.php
<?php
$page_no=$_POST['page_no'];
$tbl_name=$_POST['tbl_name'];
if($tbl_name=='tbl_user' && $_POST['user_name']!='' && $_POST['valid_user']=='user_exit'){
$sql_user = "SELECT * FROM tbl_user WHERE v_user_name='".$_POST['user_name']."' ";
$rsd_user = mysql_query($sql_user);
$sql_user_exist = "SELECT * FROM tbl_user WHERE id ='".$_SESSION['usr_id']."' ";
$rsd_exist_user = mysql_query($sql_user_exist);
$row_user=mysql_fetch_array($rsd_exist_user);
if($row_user['v_user_name']==$_POST['user_name']){
echo $msg_user=0;
}
else{
$msg_user = mysql_num_rows($rsd_user); //returns 0 if not already exist
echo $msg_user;
}
}
?>

With the assistance of Rubby Smith's comment. I was able to make this code work. Thanks Everyone.
var parameters = $("#dialog-editgiving :input").serialize();
$.ajax({
url : "./scripts/form_process/update_giving.php",
type: "POST",
data : {parameters:parameters},
success: function(data, textStatus, jqXHR)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
Using the following within the PHP script.
$params = array();
$form_fields = array_keys($HTTP_POST_VARS);
for ($i = 0; $i < sizeof($form_fields); $i++) {
parse_str($HTTP_POST_VARS[$form_fields[$i]], $params);
}

Related

JQuery Display Alert Message on Form Submit

I am trying to display alert messages on jquery from the client side. The jquery will be called once the submit button is clicked. The form then will call the server side php. Here is my code:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
But the alert message does not pop up inside the $.postmethod
And I also want to know how I can pop up the alert message from the server side. Here is my sample code:
SERVER SIDE
<?php $query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>alert('ERROR')</script>";
return false;
} ?>
In summary, the code above works but I need to display messages that would tell me if the query is successful or not. Thanks
My new problem is that the code below bring me to another page:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
$('#formAdd').on('submit', function (e) {
e.preventDefault();
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.ajax({
context: this,
url: $(this).attr('action'),
type: 'POST',
data: new FormData(this),
dataType: 'json'
}).done(function (data) {
if(data == 'ok') {
alert("DATA SUCCESSFULLY ADDED");
}
if(data == 'no') {
alert("ERROR");
}
}).fail(function (data) {
console.log('failed');
});
});
});
SERVER
$query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
mysqli_close($conn);
echo json_encode('no');
return false;
}
I need to return after the json_encode because there are still methods below that.
HTML Form
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
Script :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
$(document).on('submit', "#formAdd", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
error:function(){
alert("ERROR : CANNOT CONNECT TO SERVER");
},
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
PHP server side like this:
<?php
$insert = mysqli_query($conn, "insert query here");
if($insert) {
echo json_encode('ok');
} else {
echo json_encode('no');
}
?>
Just you need to put id="id" in input type text.
<input type="text" name="id">
Working Code
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" id="id" name="id">
<input type="submit" value="submit">
</form>

How to use ajax in PHP foreach?

I have a form with two select html tags and an input submit. To populate the value of option tags and to display the equivalent values of selected option tag, I use PHP, please see snippet below.
Now, I want to use AJAX using JS to avoid the reloading of the browser when the user clicked the button. But I don't know how. Please help me
Here's the link
Snippet:
if(isset($_POST['mall_list'])){
$mall_list= $_POST['mall_list'];
$malls= $wpdb->get_results($wpdb->prepare("SELECT stores FROM tablename WHERE malls = '" . $mall_list. "' GROUP BY stores ORDER BY stores", OBJECT));
echo '<div class="\record\">';
foreach ($malls as $record){
echo '<div>' . $record->stores . '</div>';
}
echo '</div>';
} elseif(isset($_POST['store_list'])){
$store_list= $_POST['store_list'];
$stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= '" . $store_list. "' GROUP BY malls ORDER BY malls", OBJECT));
echo '<div class="\record\">';
foreach ($stores as $record){
echo '<div>' . $record->malls. '</div>';
}
echo '</div>';
}
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
</form>
JAVASCRIPT
//callback handler for form submit
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
if you want to post data through ajax jquery. this code work for you.
$( "form" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "your post url",
data: $('#yourformname').serialize(),
success: function (data)
{
}
});
});
javascript
$("#form").submit(function(e){
var data = $(this).serialize();
var url = $(this).attr("action");
$.post({
url,
data,
function(res)
{
if(res.code == 0)
{
//success
//code somthing when the server response
alert(res.message);
}
}
});
})
server
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
#is ajax request
# code your business logic
#response data
$response = [
'code' => 0,
'message' => 'success',
'data' => []
];
echo json_encode($response);exit;
} else {
#is normal request
}

Pass values from JQUERY to PHP then output to INPUT in FORM

i need to get a value from the a form then send it to php using jquery then output the result a dropdown select menu
get the value of using jquery
<input id="search" name="search" type="text">
send it to php and perform a query
<select id="farmertype" name="farmertype" >
<option value="" > - PLEASE SELECT FARM -</option>
//// output here as options
</select>
my php file farm.php
<?php
include_once("../init.php");
$q = ($_POST["search"]);
$db->query("SELECT * FROM farmers ");
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
echo "<option value='$idno'>$idno</option>";
}
}
?>
the jquery part is so messy this is where i really need help
$("#search").click(function() {
search = $(this).attr('#search');
$.ajax({
type: 'GET',
url: 'farm.php',
data: "#search=" + search,
});
});
try this, it will help you.
JQuery:
$("#search").click(function() {
search = $(this).val();
$.ajax({
type: 'POST',
url: 'farm.php',
data: {searchValue:search},
success:function(result) {
console.log(result);
}
});
});
PHP:
<?php
include_once("../init.php");
$q = ($_POST["searchValue"]);
$db->query("SELECT * FROM farmers");
$result = [];
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
$result = "<option value='$idno'>$idno</option>";
}
print_r($result);
?>
what is the purpose of your variable $q?
Your jquery can be like :
$("#search").click(function() {
search = $('#search').val();
$.ajax({
type: 'GET',
url: 'farm.php',
data: {search : search},
success: function(html){
alert(html);
}
});
});
$("#search").click(function() { /* I think you should use keyUp or use click on a button, nobody clicks an input box */
var search = $(this).val();
$.ajax({
method: 'POST', //
url: 'farm.php',
data: {'search' : search},
success: function(data){
alert(data);
}
});
});

How can I call second jquery/ajax request?

Well, I'm validating my html form with jquery/ajax request. It's process by add_contact_process.php page. In this page if data (family or given name) is exit then I'm showing a message with a button which value is Yes and Cancel.
So
1) If Yes button is press I want to call a another jquery/ajax request which save the data to db.
2) If Cancel button is press then I want to remove/hide the message.
Can someone suggest me how can I do this ?
Html form code :
<form id="addcontact">
<table width="450" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Family name</td>
<td><input type="text" name="family_name" maxlength="50" placeholder="Family name"/></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="given_name" maxlength="30"placeholder="Given name"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add Contact" class="submit"></td>
</tr>
</table>
</form>
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
$('#success').delay(3000).fadeOut('slow');
</script>
add_contact_process.php page :
<?php
$family_name = inputvalid(ucfirst($_POST['family_name']));
$given_name = inputvalid(ucfirst($_POST['given_name']));
$exitfname = mysqli_query($link, "SELECT family_name FROM contact_details WHERE family_name = '$family_name'");
$numfname = mysqli_num_rows($exitfname);
$exitgname = mysqli_query($link, "SELECT given_name FROM contact_details WHERE given_name = '$given_name'");
$numgname = mysqli_num_rows($exitgname);
$msg = array();
$msg['error'] = false;
if(empty($family_name)){
$msg[] = "<div class='error'>Family name required.</div>";
$msg['error'] = true;
}
if(strlen($given_name) > 30){
$msg[] = "<div class='error'>Given name is too big.</div>";
$msg['error'] = true;
}
// If error is not found
if($msg['error'] === false){
if(!empty($family_name) && $numfname >= 1 || !empty($given_name) && $numgname >= 1){
$msg[] = "<div class='error'>A contact with this name exists. Do you wish to continue adding this new contact?
<input type='submit' name='warning' value='yes' id='yes' class='submit' style='margin:0px;'/>
<input type='submit' name='warning' value='Cancel' id='cancel' class='submit' style='margin:0px;'/>
</div>";
$msg['error'] = true;
}else{
$query_2 = "INSERT INTO contact_details (family_name, given_name) VALUES('$family_name', '$given_name')";
$query_2 = mysqli_query($link, $query_2);
$last_id = mysqli_insert_id($link);
if($query_2){
$msg[] = "<div class='success'><strong>Successfully added a new contact</strong>. </div>";
$msg['last_id'] = "$last_id";
$another = "close";
}else{
$msg[] = "<div class='success'>Sorry we can not add a new contact details. </div>";
$msg[] .= mysqli_error();
$another = "close";
}
}
}
echo json_encode($msg);
?>
Call Second ajax within success
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
/*------------------------------------------------------------------*/
if(confirm('Write your message here')){
/* Second ajax after clicking ok on confirm box */
$.ajax({
url : 'Second URL',
method :'POST',
data : {'data1':data1},
success:function(response){
// code after success
},
error: function(e){
return false;
}
});
}else{
$('#success').hide();
$('#success').hide();
}
/*----------------------------------------------------------*/
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
You should define the second Ajax call in first Ajax call complete method. By default Ajax call is asynchronous, it will start executing the code or statements in success method with out waiting for response from the server. you code should me like this
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
// some code
},
complete:function () {
//you second ajax call
}

No Data Posted in a form

I use a form which sends data with a POST method to a php file via AJAX. Everything is ok and I can see the results in the html table in its id div name. But now this very same table contains input fields (second form) with the same method. All ids and names are different, I can see the fields values with
alert( $("input[name=id]").val() );';
Am I missing something ?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form name="ajaxform" id="ajaxform" action="edit.php" method="POST">
<select name="user" id="simple-post" onchange="this.value.submit()">
<option value="">Select a person:</option>
<option value="0">John</option>
<option value="1">Peter</option>
<option value="1">Heinrich</option>
</select>
</form>
<div id="simple-msg">
</div>
<script>
$(document).ready(function()
{
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});
</script>
</body>
Now the edit.php page
<?php
$json_a=json_decode(json_encode($_POST),true);
$output=array();
$i=0;
foreach ($json_a as $key => $value){
echo $key . ':' . $value; // peut-ĂȘtre branchĂ©!
$output[$i]= $value;
$i++;
}
$array_user=array();
$array_user[0]=$output[0];
$array_user[1] ="Yes";
$array_user[2] ="mypass";
echo '<form name="ajaxform1" id="ajaxform1" action="SQL_user.php" method="POST">
';
echo '<input type="text" name="id" size="3" value="' .$array_user[0]. '"/>';
echo '<input type="text" name="online" size="3" value="' .$array_user[1]. '"/>';
echo '<input type="text" name="password" size="20" value="' .$array_user[2]. '"/>';
echo '<input type="button" id="simple-post1" value="Apply" />';
echo '</form>';
echo '<br>';
echo'<div id ="simple-msg1">';
echo'</div>';
echo '<script>
$(document).ready(function()
{
$("#simple-post1").click(function()
{
$("#ajaxform1").submit(function(e)
{
$("#simple-msg1").html("<img src='."'loading.gif'".'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg1").html('."'<pre><code class=".'"prettyprint"'.">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)".'"
{
$("#simple-msg1").html('."'<pre><code class=".'"prettyprint">AJAX Request Failed<br/> textStatus='."'+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
});
".'$("#ajaxform1").submit();
});
});
</script>';
?>
The second form doesn't work...
you have put the following code to run if an element with id=simple-post gets clicked. notice, .submit is nested inside .click
$(document).ready(function () {
$("#simple-post").click(function () {
$("#ajaxform").submit(function(e){
//code to execute on submit action goes here
}
$("#ajaxform").submit(); //SUBMIT FORM
});
});
so the EventHandler on form submit will registered ONLY AFTER an element with id=simple-post gets clicked which is the reason, ajax request is not happening & form gets submitted normally.
Did you mean the following:
$(document).ready(function () {
$("#ajaxform").submit(function (e) {
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code
class="prettyprint">' + data + '</code></pre>');
},
error: function (jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#simple-post").click(function () {
$("#ajaxform").submit(); //SUBMIT FORM
});
});
The above code will set EventHandler on form submit on $(document).ready. The form will get submitted via ajax/xhr either when:
Submit button form is pressed.
An element with id=simple-post gets clicked.(Run Code button)
Is this what you intend on doing?

Categories

Resources