No Data Posted in a form - javascript

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?

Related

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
}

AJAX Passing Form Data

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);
}

jQuery validation submitHandler not work in $.ajax post form data

I have Send data using $.ajax and validation with jQuery validation plugin like this :
<div class="" id="ajax-form-msg1"></div>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
JS:
jQuery(document).ready(function ($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [4, 20],
},
},
submitHandler: function (form) {
$("#ajax-1").click(function (e) {
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false
}).done(function (data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
});
}
});
});
In action my form validate using jQuery validation but after validation not submit and not send data.
how do fix this problem?!
DEMO HERE
The submitHandler is expecting a submit and you have a click event inside it and then an ajax call.
If you have a button type="submit" inside a form you don't even need a click event, the plugin will do the validation automatically. So just make the ajax call inside the submitHandler.
If you need to bind the action to a button using the click event, the proper approach should be something like this:
$('#button').click(function(){
var form = $('#myform').validate({...}); #store the validator obj
if (form.is_valid()){
// submit using ajax
} else {
// dont do anything
}
});
Call form.submit() at the end of your done function.
See: http://jqueryvalidation.org/validate/
Also, you do not need $("#ajax-1").click() because the submitHandler will be called automatically when you click on that button anyways. You can test this yourself by putting a console.log as the first line of submitHandler. Then fill out the form and press the button. See if it prints out your log message.
In submitHandler you are handling the submit , then again why did you write click event?
Here is the fix.
jQuery(document).ready(function($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [2, 20],
},
},
submitHandler: function(a, e) {
//a is form object and e is event
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false,
success: function(data) {
console.log(data)
},
error: function(err) {
console.log(err)
}
}).done(function(data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function(jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
Use success and error call backs to get data or error messages.
Note: Here (In StackOverflow) you will get 404 Page Not Found error when you submit. So try in your local.

jQuery ajax to PHP, returning Error and empty object

I am trying to use jQuery ajax to call PHP and return JSON.
My test is very simple, but all I seem to be getting is an empty object.
I am not getting any PHP errors in the LOG File.
jqXHR is shown as an object with the 'alert', but does not appear in the 'Chrome' console.
The 'Unpacked' alert does not show at all
I have obviously missed something or made some stupid error, but I can not see what I have done wrong.
HTML
<body>
<form id="frmSearch" onsubmit="matchQryString();">
Search: <input type="text" name="qryWords" value="" />
<input type="submit" name="submit" value="Search" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function matchQryString() {
alert("Running AJAX");
$.ajax({
type:'POST',
url: 'rtnJSON.php',
data:$('#frmSearch').serialize(),
dataType: 'json',
success: function(response) {
alert("PHP Return SUCCESS");
alert(response);
},
error: function (jqXHR, exception) {
alert("PHP Return ERROR");
alert(jqXHR);
alert(exception);
console.log(jqXHR);
var op = "";
for (property in jqXHR) {
op += property + ': ' + obj[property]+'; ';
}
alert ("Unpacked: " + op);
}
});
return false ;
}
</script>
</body>
PHP
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
header('Content-type:application/json;charset=utf-8');
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
form being submitted before $.ajax() call ? Try removing onsubmit from html , type="submit" from input element , attaching click event to type="submit" element , calling .e.preventDefault() within click handler . Also note, obj does not appear defined within error handler of $.ajax()
html
<form id="frmSearch"">
Search: <input type="text" name="qryWords" value="" />
<input type="button" name="submit" value="Search" />
</form>
js
$(function() {
function matchQryString(e) {
e.preventDefault();
alert("Running AJAX");
$.ajax({
type:'POST',
url: 'rtnJSON.php',
data:$('#frmSearch').serialize(),
dataType: 'json',
success: function(response) {
alert("PHP Return SUCCESS");
alert(response);
},
error: function (jqXHR, exception) {
alert("PHP Return ERROR");
alert(jqXHR);
alert(exception);
console.log(jqXHR);
var op = "";
for (property in jqXHR) {
op += property + ': ' + obj[property]+'; ';
}
alert ("Unpacked: " + op);
}
});
};
$("[name=submit]").on("click", matchQryString);
})

create form dynamically and submit it

So I have a jQuery plugin I wrote below, in plugin.js. I want to be able to also submit the form via JSON/AJAX every time it's created.
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
$('#form').submit(function(e)
{
var postData = form.find('form').serializeArray();
if(postData.name === "someREGEXstring" || postData.email === "someREGEXstring") {
console.log("empty inputs not cool");
}
var formURL = $('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
$('#form').submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
in HTML view
<div id="newForm"></div>
<script>
$(document).ready(function(){
$("#newForm").create();
});
</script>
Is this the correct way to make this or should I:
Create a another namespace under the same file for the AJAX portion
Create another namespace under a different file the AJAX portion
If the question is purely about how to arrange the code, I would suggest you pull the form template out of the code completely and make your plugin more flexible.
Option 1. Create the form as a template in the page and pass the
template selector to plugin as an option
Option 2: Pass the template to your plugin
Here is an example of the first technique: http://jsfiddle.net/TrueBlueAussie/c8bmw/7/
Template in HTML:
<script id="template" type="template">
<div id="form" class="container">
<div>User Login</div>
<form action="/create/one" method="post"/>
<input type="text" name="name" placeholder="name"/>
<input type="email" name="email" placeholder="email"/>
<button type="submit">Login</button>
</form>
</div>
</script>
Create with:
$(document.body).create('#template');
And plugin simplified to:
(function ( $ ) {
$.fn.create = function(template) {
form = $($(template).text());
form.submit(function(e) {
// This is the actual form object now
var $form = $(this).find('form');
// Test contents of form here
// If values are correct proceed with Ajax call
var postData = $form.serializeArray();
var formURL = $form.attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); // Stop default action
});
return this.append(form);
};
}( jQuery ));
Now your plugin code will work with any form.
Based on your comment I have removed the automatic submit of the form, as that made no sense
This should work:
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
form = $(form);
form.submit(function(e) {
var postData = form.find('form').serializeArray();
var formURL = form.find('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
form.submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
Here is a demo in JSFiddle.
What is fixed:
form = $(form) is used in order to create the DOM elements based on the form string.
Change the way postData, formURL are initialized.
<div id="#newForm"></div>
should be
<div id="newForm"></div>
to load this form element
I have some chages, like:
$('#form').submit(function(e) should be $(form).submit(function(e) as variable form contains all the HTML of form wrapped within DIV.
in the submit of form, $(this) will refer to the form element itself.
Here is the modified code:
(function ($) {
$.fn.create = function () {
var formContainer = $("<div />", {
id : "form",
class : "container"
}).append("<div>User Login</div>");
var form = $("<form />", {
action: "/create/one",
method : "post",
submit : function(e){
var actionUrl = $(this).attr("action");
alert(actionUrl); // just to check if this is working or not
$.ajax({
url : actionUrl,
type : "POST",
data : $(this).serializeArray(),
success : function (data, textStatus, jqXHR) {},
error : function (jqXHR, textStatus, errorThrown) {}
});
e.preventDefault();
}
})
.append('<input type="text" name="name" placeholder="name"><input type="email" name="email" placeholder="email"><button type="submit">Login</button>')
.appendTo(formContainer);
return this.append(formContainer);
};
}(jQuery));
$("#test").create();
HTML for testing:
<div id="test"></div>
JS fiddle: http://jsfiddle.net/ashishanexpert/y99mt/2/
I have created the HTML nodes via jquery instead of just HTML string. attaching events to nodes is easier than converting string to HTML first and then attaching event to them. Hope you like it.

Categories

Resources