How to pass value from html form without using submit button - javascript

Current code:
index.html
<script type="text/javascript">
$('#username').blur(function(){
$.ajax({
type: "POST",
url: "search.php",
data: {text:$(this).val()}
});
});
</script>
<form id="search" action="search.php" method="post">
<input type="text" id="username" name="username" size="30" placeholder="username ..." />
<input type="submit" id="submit-button" name="sa" value="search" />
</form>
search.php
<?php
echo $_POST['username'];
?>
If I press the submit button it works well but I want to send the value from the field once I focuse out of the field, without pressing the submit button.

You can try focusout.
$('#usernamecopy').focusout(function(){
$.ajax({
type: "POST",
url: "search.php",
data: {username :$('#username').val()}
});
});
In php file you can use:
$user= $_REQUEST['username'];

Not tested but I think if you change data: {text:$(this).val()} to data: {text:$("#usernamecopy").val()}; it will work because when you put this inside the data; the this refers to the data instead of #usernamecopy . By the way, I hope you are not mistaking #usernamecopy with #username

**Use following code in JavaScript :**
<script type="text/javascript">
$('#username').blur(function(){
var value = $("#username").val();
$.ajax({
type: "POST",
url: "search.php",
data: "username="+value,
success: function(data){
}
});
});
</script>

Related

Form submit only one value with AJAX passing form data to PHP in the same page

I need to pass a single value from my form to my php in the same page. It´s probably not an option to create another .php file and take the code there since there´s a lot going on.
This is the part of the code I need to fix, currently it only works when the code is on another file, since the $_POST is not messing around with other parts of the code. Specifically I need to manage to pass the 'client' or the 'empre' from the form alone to the php.
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
if($(".cliente").click(function() {
var name = $("#client").val();
var dataString = 'client='+ name;
}))else if($(".empresa").click(function() {
var name = $("#empre").val();
var dataString = 'empre='+ name;
}));
$.ajax({
type: "POST",
data: dataString});
});
</script>
</head>
<body>
<form>
<input name="client" type="text"><br>
<input class="cliente" type="submit" value="Buscar cliente"/><br>
<input name="empre" type="text"><br>
<input class="empresa" type="submit" value="Buscar empresa"/><br>
</form>
//PHP HERE
//HTML AGAIN
</body>
</html>
PHP (same page, just separating for readability)
if(isset($_POST['empre'])){
//DB QUERY
}
elseif(isset($_POST['client'])){
//DB QUERY
}
You can combine and send it in same AJAX call as below, and in PHP you can do:
$parameters = json_decode($_POST['params']);
$parameters would have all the variables sent in that AJAX call.
I would recommend, not to use same page for your AJAX. You should keep it in separate file. That would make code much cleaner, lighter, readable and easy-to-tweak.
$(function() {
$(".cliente, .empresa").click(function(e) {
e.preventDefault();
var paramsToSend = {};
if ($(this).hasClass('client'))
paramsToSend['client'] = $('form[name="client"]').serialize();
else
paramsToSend['empre'] = $('form[name="client"]').serialize()
$.ajax({
url: 'index.php' //assuming this is index.php (same page)
type: "POST",
data: {
params: JSON.stringify(paramsToSend)
},
success: function(data) {},
failure: function(error) {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="client">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente" />
</form>
<form name="empre">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa" />
</form>
//PHP HERE //HTML AGAIN
Why not use separate forms to process the data? (Your PHP logic mentioned will work with this proposed solution)
$(function() {
$(".cliente").click(function(e) {
e.preventDefault();
alert('Going to post data for client, check the console log now');
$.ajax({
url: $('form[name="client"]').attr('action'),
type: "POST",
data: $('form[name="client"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
$(".empresa").click(function(e) {
e.preventDefault();
alert('Going to post data for empre, check the console log now');
$.ajax({
url: $('form[name="empre"]').attr('action'),
type: "POST",
data: $('form[name="empre"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="client" action="https://someurl.com/fileto.php">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente"/>
</form>
<form name="empre" action="https://someurl.com/fileto.php">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa"/>
</form>

input value data is not passing using jquery/ajax to Php

I'm trying to get result from Mysql database but I'm getting warning message it's because it's not passing the html field value to jquery/ajax method. I think issue is on this line data : SearchValue,. So that In my php page it's not getting $search = $_POST['SearchValue']; value and showing warning message.
Can anyone tell what is wrong in my code ? Thank You.
Html Page:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
var SearchValue = $('#txt_name').val();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "doSearch.php",
data : SearchValue,
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="text" name="search" id="txt_name" /> </td>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
Php page:
$search = $_POST['SearchValue'];
Please Use Below Code :
$(document).ready(function() {
$("#display").click(function() {
var SearchValue = $('#txt_name').val();
var str = $( "#form_id" ).serialize();
$.ajax({
//create an ajax request to load_page.php
type: "POST",
url: "doSearch.php?searchValue="+SearchValue,
data : str,
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
You are submitting the form via native method. That means if you click on your submit button the page will be reloading (since in your case you haven't included the form action).
One thing you could do is make a button and a textfield outside of the form and declare its onClick attribute like this:
<input type="text" id="search">
<button onclick="doSearch(document.getElementById('search').value)"> Search <button>
OR
<input type="text" id="search">
<button onclick="doSearch($("#search").val())"> Search <button>

ajax on submit no refresh form using php

ok so i know this ajax works, but i cant seem to understand why it's not submitting here.
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(){
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
submit form
<form action="" method="post" onsubmit="return false;" id="myform">
submit button
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
i'm pretty something is wrong with the button, but i want to keep the way the button is because alot of my other forms use this same button, thanks if you can explain to me why click this submit button does nothing.
You are selecting an <input> instead of a <button>. I had success by changing your jQuery selector from this:
$('input[type=submit]')
to this:
$('button[type=submit]')
http://jsfiddle.net/H3Bcc/
Not all browsers interpret a click attached to a submit button as submitting the form so you are effectively just negating the click of that button.
Preventing a form submission should preferably be captured by attaching the submit handler to the <form> when you have a <input type="submit"> or <button type="submit> so this is the best way to assure success:
jQuery
$(function(){
$('#myform').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
HTML
<form action="postitem.php" method="POST" id="myform">
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
</form>
try this :
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(e){
e.preventDefault(); // prevent the browser's default action of submitting
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});

How to post to php on input change then get results in content div

I want to do just what the title says, when data is inputted into the textfield, I want it sent to posttothis.php, then have the result printed in a content div. I can't seem to make it work.
testscript.html
<html>
<head>
<script type="text/javascript">
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
</script>
</head>
<body>
<input type="text" name="text" id="text">
<div id="content" name="content">
<script>
$('#text').keyup(function(){
$.ajax({
type: "POST",
url: "posttothis.php",
data: {text: $(this).val()},
success: function(data)
{
$("#content").html(data);
}
});
});
</script>
</body>
</html>
posttothis.php
<?php
$testvar=$_POST['text'];
echo $testvar;
?>
Thanks
EDIT: Updated my script with the suggested modifications, but still can't get it to display what I type in the textbox in the content div. To answer the questions below: I don't want to submit the form, I just want to get the value from it on every change. Console shows no errors.
EDIT2: I updated the working code, maybe it helps someone else in the future.
You can use the On Key up function instead.
<input type="text" name="text" id="text">
<div id="content" name="content">
<script>
$('#text').keyup(function(){
$.ajax({
type: "POST",
url: "posttothis.php",
data: {text: $(this).val()},
success: function(data)
{
$("#content").html(data);
}
});
});
</script>
Why not try jQuery post?
Example
<input type="text" name="text" id="text">
<div id="content" name="content">
<script>
$('#text').keyup(function(){
$.post('posttothis.php', {text:$('#text').val()}, function(data) {
$("#content").html(data);
});
});
</script>
put "," after data: {text: $('#text').val()}
<input type="text" name="text" id="text">
<div id="content" name="content">
<script>
$('#text').change(function(){
$.ajax({
type: "POST",
url: "posttothis.php",
data: {text: $('#text').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
</script>
Use:
$('#text').keyup(function(){
Instead of
$('#text').change(function(){
Also your are missing a comma (,) after data property
data: {text: $('#text').val()},

Serialize checkboxs within Ajax call using jQuery

i need to serialize form input to send an Ajax call using jQuery to php script and each time i tried to print out the values of the form it gives empty array .
HTML Form
<form class="form-horizontal" id="generateCompression" method="post">
<fieldset>
<div class="control-group"><label class="control-label">Checkboxes</label>
<div class="controls">
<input type="checkbox" name="names[]" value="Jan-2011"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2012"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2013"> Jan-2013</label>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Generate</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
Javascript
$(document).ready(function(){
$("#result").hide();
$("#generateCompression").submit(function(){
$.ajax({
url: "compare-action.php",
type: "POST",
data: $("#generateCompression").serialize(),
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
return false;
});
});
this is the PHP file
<?php
$inputs = $_POST;
print_r($inputs);
?>
Checkboxes do not send anything to the server if at least one checkbox is not checked.
Your script needs to check for the existence of your form field, if the formfield doesnt exist then you know nothing has been checked.
To test simply add a text box to your form and then run your script again.
Try this.
Send serialized data in one variable like
$.ajax({
url: "compare-action.php",
type: "POST",
traditional: true,
data: {
"test_data" : $("#generateCompression").serialize()
},
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
And in the compare-action.php file
print_r($_POST("test_data"));

Categories

Resources