Simple ajax call not working - php

So I doing simple edit/delete/new for mysql DB update.I am using ajax as I need it to in a single page.
So when I check New button, a new form shows up(from ajax call to php file). I get html form. I am trying to validate this.
But I am not able. Code seems right. My code here
trail.php
<?php include( 'connect.php'); ?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$("#form1").validate({
debug: false,
rules: {
plid: "required",
},
messages: {
plid: "Please select a pack list id..",
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "aa.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
});
</script>
</head>
<body>
<div id="result1"></div>Packing List</br>
<form id="form1" name="form1" action="" method="post">
<?php echo '<select name="plid" id="plid">'; echo '<option value="" selected="selected">--Select the Pack List Id--</option>'; $tempholder=a rray(); $sql="SELECT `pl_id`
FROM (
SELECT `pl_id`
FROM packlist
ORDER BY `pl_id` DESC
LIMIT 30
) AS t" ; $query=m ysql_query($sql) or die(mysql_error()); $nr=m ysql_num_rows($query); for ($i=0; $i<$nr; $i++){ $r=m ysql_fetch_array($query); if (!in_array($r[ 'pl_id'], $tempholder)){ $tempholder[$i]=$ r[ 'pl_id']; echo "<option>".$r[ "pl_id"]. "</option>"; } } echo '</select>'; ?>
<br/>
<input type="submit" name="new" id="new" value="New" />
<br/>
<input type="submit" name="delete" value="Delete" />
<br/>
<input type="submit" name="edit" id="edit" value="Edit" />
<br/>
</form>
</body>
And my ajax called php file
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$("#form2").validate({
debug: false,
rules: {
plidnew: "required",
},
messages: {
plidnew: "Please select a pack list id..",
}
});
});
</script>
</head>
<body>
<?php $a=isset($_POST[ 'plid']) && $_POST[ 'plid']; $b=isset($_POST[ 'new']) && $_POST[ 'new']; if($a&&$b) { ?>
<form name="form2" id="form2" method="post" action="">
<P>
<LABEL for="plidnew">PackList No
<INPUT type="text" id="plidnew">
</LABEL>
<BR>
<BR>
<LABEL for="itemidnew">Item Id
<INPUT type="text" id="itemidnew">
</LABEL>
<BR>
<BR>
<LABEL for="quannew">Quantity
<INPUT type="text" id="quannew">
</LABEL>
<BR>
<BR>
<LABEL for="potnew">Potency
<INPUT type="text" id="potnew">
</LABEL>
<BR>
<BR>
<LABEL for="sizenew">Size
<INPUT type="text" id="sizenew">
</LABEL>
<BR>
<BR>
<INPUT type="submit" id="newsubmit" name="newsubmit" value="Submit">
<INPUT type="reset">
</P>
</form>
<?php }
$c=isset($_POST[ 'plid']) && $_POST[ 'plid'];
$d=isset($_POST[ 'delete']) && $_POST[ 'delete'];
if($c&&$d) {
echo "delete!!";
}
$e=isset($_POST[ 'plid']) && $_POST[ 'plid'];
$f=isset($_POST[ 'edit']) && $_POST[ 'edit'];
if($e&&$f) {
?>
<form name="form3" id="form3" method="post" action="aa.php">
<P>
<LABEL for="plidedit">PackList No
<INPUT type="text" id="plidedit">
</LABEL>
<BR>
<BR>
<LABEL for="itemidedit">Item Id
<INPUT type="text" id="itemidedit">
</LABEL>
<BR>
<BR>
<LABEL for="quanedit">Quantity
<INPUT type="text" id="quanedit">
</LABEL>
<BR>
<BR>
<LABEL for="potedit">Potency
<INPUT type="text" id="potedit">
</LABEL>
<BR>
<BR>
<LABEL for="sizeedit">Size
<INPUT type="text" id="sizeedit">
</LABEL>
<BR>
<BR>
<INPUT type="submit" id="editsubmit" name="editsubmit" value="Submit">
<INPUT type="reset">
</P>
</form>
<?php } ?>
</body>
I had doubts about validating the form. I tried the validation codes in both page.
But no ajax effect as shown in firebug. Any help appreciated..Thanks a lot..

while using ajax with type "post", you should be careful in passing data
data and data1 are the parameter of the webmethod or service. Try this
var d1="asd";
$.ajax({
type: "POST",
url: "aa.php",
data: "{data:'"+d1+"',data1:'"+d2+"'}",
cache: false,
success: function(response) {
$('#result1').html(response);
}
});

Related

Multiple arrays to a JSON array to PHP via AJAX

I have a form
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div><label for="post[uname]">Username <em>*</em></label> <input id="post[uname]" type="text" name="uname" value="" /></div>
<p class='note' id='err[Name]'></p>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
I have two arrays post and err. I'm trying to send them to php and then in php it will json_encode the array and print it on the screen like so:
{
"err": {
"uname": "Please enter a user name"
}
"post": {
"uname": ""
}
}
or this is if the user did enter a name:
{
"post": {
"uname": "Bob Ross"
}
}
There could be multiple fields for post and err but it should still follow the same suite.
How do I send the data to php, I understand it's some sort of serializeArray but it doesn't format it properly when I do:
JSON.stringify($("#ajax-form").serializeArray())
A jsfiddle to full html:
https://jsfiddle.net/dzv8ttjn/1/
Your best bet is to call .serialize(); on the form which will give you something like: user-name=some%20name&email=some%20emale&gender=Female&interests=Software
Send that to the PHP script, and have the script create the format of the response while looping over the $_POST array. Something like the below would work:
(note that I've changed your id's to be more sensible and updated the jQuery version used)
<?php
if(count($_POST)>0){
$response = ['err'=>[], 'post'=>[]];
foreach($_POST as $key => $value)
{
$response['post'][$key]=$value;
if(trim($value) == '') $response['err'][$key]='Please enter a '.$key;
}
echo json_encode($response);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Lab4: Form Validation with AJAX,JQuery,JSON and PHP</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript">
$("#ajax-form").on('submit', function(event) {
event.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataString,
success: function(response) {
if (response) {
alert('test worked');
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<h2>Form Validation with AJAX,JQuery,JSON and PHP</h2>
<div class="form-container">
<span id="ajax-message"></span>
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div>
<label for="uname">Username <em>*</em></label>
<input id="uname" type="text" name="user-name" value="" />
<p class='note' id='name-error'></p>
</div>
<div>
<label for="password">Email Address <em>*</em></label>
<input id="password" type="text" name="email" value="" />
<p class='note' id='password-error'></p>
</div>
<div>
<label for="post[gender]">Gender <em>*</em></label>
<input type="radio" name="gender" value="Male" class="form-check-input" id="Male" required> Male
<input type="radio" name="gender" value="Female" class="form-check-input" id="Female" required> Female
<p class='note' id='gender-error'></p>
</div>
<div>
<label for="interests">Interests<em>*</em></label>
<input type="checkbox" name="interests" value="Music" class="form-check-input" id="Music"> Music
<input type="checkbox" name="interests" value="Software" class="form-check-input" id="Software"> Software
<input type="checkbox" name="interests" value="Hardware" class="form-check-input" id="Hardware"> Hardware</div>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
</div>
<h3>JSON Array</h3>
<pre id='debug'></pre>
</div>
</body>
</html>

jQuery update content from PHP

I have a table with a lot of rows, each row has 2 input fields and 1 submit button. When I click on the submit button the data is passed to a PHP script, the PHP script processes the data and returns some text.
Currently the submit button is replaced with the text that is returned by the PHP script. But I want that the returned text is being shown next to the button, so the button doesn't disappear.
I am not able to fix that, maybe somebody can help me with that?
<html>
<head>
<title>Add data with Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('click', '#submitButton input[type=button]', function(){
var field1 = $(this).parent().parent().find(".field1").val();
var field2 = $(this).parent().parent().find(".field2").val();
var field3 = $(this).parent().parent().find(".field3").val();
var submitButton = $(this);
$.ajax({
type: "POST",
url: "add_data.php",
data: { field1: field1, field2: field2, field3: field3 }
})
.done(function(msg) {
submitButton.parent().html(msg);
});
});
</script>
</head>
<body>
<form method="POST">
<input type="hidden" class="field1" value="product 1">
<input type="text" class="field2" value="data1">
<input type="text" class="field3" value="data2">
<div id="submitButton">
<input type="button" name="submitButton" value="Add">
</div>
</form>
<form method="POST">
<input type="hidden" class="field1" value="product 2">
<input type="text" class="field2" value="data1">
<input type="text" class="field3" value="data2">
<div id="submitButton">
<input type="button" name="submitButton" value="Add">
</div>
</form>
<form method="POST">
<input type="hidden" class="field1" value="product 3">
<input type="text" class="field2" value="data1">
<input type="text" class="field3" value="data2">
<div id="submitButton">
<input type="button" name="submitButton" value="Add">
</div>
</form>
</body>
Well, instead of replacing the content:
submitButton.parent().html(msg);
append to the content:
submitButton.parent().append(msg);

How to upload file on ajax response

I am playing with jQuery Ajax and I want to upload file to specific folder on ajax response.
My HTML Form:
<form type="post" method="post" action="" id="newCustomerForm" enctype="multipart/form-data">
<div>
<label for="username">Username</label>
<input name="username" id="username" type="text" />
</div>
<br />
<div>
<label for="email">Email</label>
<input name="email" id="email" type="text" />
</div>
<br />
<div>
<label for="message">Message</label>
<input name="message" id="message" type="text" />
</div>
<br />
<div>
<label for="file">File</label>
<input name="file" id="file" type="file" />
</div>
<br />
<input type="hidden" name="action" value="addCustomer"/>
<input type="submit" name="submit" value="Submit">
</form>
My Ajax Code:
<script type="text/javascript">
$(function() {
$("#newCustomerForm").validate({
rules: {
"username": {
required: true
}
},
messages: {
"username": {
required: "Please, enter a name"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "<?php echo esc_url( home_url( '/' ) ); ?>wp-admin/admin-ajax.php",
data: $(form).serialize()+'&file='+document.getElementById('file').value,
timeout: 3000,
success: function(data) {
$("#feedback").html(data);
},
error: function() {
alert('failed');
}
});
return false;
}
});
});
</script>
I am getting ajax data inside bellow function:
add_action('wp_ajax_addCustomer', 'addCustomer');
function addCustomer() {
echo $username = $_POST['username'];
echo "<br />";
echo $email = $_POST['email'];
echo "<br />";
echo $message = $_POST['message'];
echo "<br />";
echo $file = $_POST['file'];
echo "<br />";
die();
}
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
I am getting file name on response but I am confused how to upload image to specific folder on my project folder.
I will appreciate If you help me to solve my issue.
Thanks :)

Posting data to self using jquery

I am trying to post some form data to self with no success.My code is as follows
<html>
<title>Post to self</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.x-button').live("click", function () {
$.ajax({
type: "POST",
url: "self.php",
data: $(".aj").serialize(),
success: function (data) {
alert("Data Loaded:");
}
});
});
});
</script>
</head>
<body>
<?php
if(isset($_POST['submit']))
{
echo $_POST['firstname'];
}
?>
<form name="input" action="" class="aj" method="post">
<article>
<label>Firstname</label>
<input type="text" name="firstname" value="Ed" class="x-input"
/>
</article>
<article>
<label>Lastname</label>
<input type="text" name="lastname" value="Doe" class="x-input"
/>
</article>
<article>
<label>City</label>
<input type="text" name="city" value="London" class="x-input"
/>
</article>
<input type="submit" value="Update Options" class="x-button" />
</form>
</body>
</html>
When using <form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> in plain php and html it works but i can't get it to work with jquery.
you are mixing two approch altogether.
<form id="myform" action="" >
.....
</form>
To send ajax request to the same page you can keep url parameter empty/removed
TRY
<script type="text/javascript">
$(document).ready(function () {
$('.x-button').live("click", function () {
$.post({
data: $('form#myform').serialize(),
success: function (data) {
alert("Data Loaded:");
}
});
});
});
</script>
Of course you do not want to include the whole page to the response text so you need a statement if ajax is requested
<?php
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
if(isset($_POST))
{
print_r($_POST);
}
}else{
?>
<html>
<title>Post to self</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.x-button').live("click", function () {
$.ajax({
type: "POST",
url: "self.php",
data: $(".aj").serialize(),
success: function (data) {
alert("Data Loaded:");
}
});
});
});
</script>
</head>
<body>
<form name="input" action="" class="aj" method="post">
<article>
<label>Firstname</label>
<input type="text" name="firstname" value="Ed" class="x-input"
/>
</article>
<article>
<label>Lastname</label>
<input type="text" name="lastname" value="Doe" class="x-input"
/>
</article>
<article>
<label>City</label>
<input type="text" name="city" value="London" class="x-input"
/>
</article>
<input type="submit" value="Update Options" class="x-button" />
</form>
</body>
</html>
<?php }?>
add return false; at the end of the inline javascript function to avoid the form gets submitted the "normal" way

jQuery not working as expected on HTTPS Internet explorer

When I try to run my code on any other webbrowsers apart from the Internet explorer it works fine. But when I try to run the code on Internet explorer I do get an alert box saying HERE along with an Ok button. but the problem is when I click on that OK button I do not get anything. Ideally I should be getting another alert box.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(event) {
alert("here");
$.post('process.php', {name:'test1',email:'test.com'}, function(data)
{
$('#results').html(data);
alert(data);
});
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<label for="email" id="email_label">Email</label>
<input type="text" name="email" id="email" size="30" value=""/>
<br>
<input type="button" name="submit" id="submit" value="Submit">
</form>
<div id="results"><div>
</body>
</html>
Any help on this is very much appreciated.
Edit: I found out that Internet Explorer which has HTTP works perfectly fine but not on Internet Explorer which uses HTTPS.
Change your code to
<form name="myform" id="myform" action="" method="POST" onsubmit="return validate(this);">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<label for="email" id="email_label">Email</label>
<input type="text" name="email" id="email" size="30" value=""/>
<br>
<input type="button" name="submit" id="submit" value="Submit">
</form>
<script>
function validate(elem){
$.post('process.php', {name:'test1',email:'test.com'}, function(data)
{
$('#results').html(data);
return true;
});
return false;
}
</script>
try using jquery $.ajax() for posting your form data using $(fomname).serialize() method
function submitYourForm()
{
$.ajax({
type: 'POST',
cache: false,
async:true,
url: 'your url',
data: $('#myform').serialize(),
success: function(data) {
alert(data);
}
});
}
change your button type from "submit" to "button" and call your function onclick the button
like
<input type="button" name="submit" onclick="submitYourForm();" value="Submit" />
remove function call onsubmit.
try this

Categories