Ok i have this code and i want to send this price from and price to to some other page when user clicks on submit but without refreshing page and without form.On other page i will use this inputs for sql query and display results.
Price from:<input type="text" name="from" id="from" width="50px" />
Price to:<input type="text" name="to" id="to" width="50px" />
<input type="submit" id="submit" value="Search"/>
using jquery
$('#submit').click(){
event.preventDefault();// prevent form from submitting
$.ajax({
type: 'POST',
url: 'targetpage.php', //your page here
data: {price_from:$('#from').val() , price_to: $('#to').val()},
success: function(response){
}
});
});
Hi you can achieve this using jQuery+Ajax, try this
$('#submit').click(function(event) {
var from = $('#from').val();
var to = $('#to').val();
$.ajax({
type: "POST",
url: "page_name.php",
data:"from="+from+"&to="+to,
success: function (msg) {
//some action
}
});
});
and in your php(page_name.php) file you can get the posted value and can do the necessary operation
$from = $_POST['from'];
$to = $_POST['to'];
var _from = $('#from').val();
var _to = $('#to').val();
$.post('your_file.php',{from: _form, to: _to},function(data){
//Do Something with returned data.
},'json');
'json' at the end could also be 'html' depending upon what you're returning.
Related
First of all I'm sorry if my English isn't totally correct.
I'm learning to use json and I want to try with this simple code, where I insert name and surname and with Ajax I send them to a json struct for then show them in a table.
ajax.php
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<input type="submit" id="invia" value="ISCRIVITI" />
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
<script type="text/javascript">
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
</script>
json.php
<?php
header("Content-Type: application/json", true);
$dati = array( 'nome'=>$_POST['nome'], 'cognome'=>$_POST['cognome'] );
echo json_encode($dati);
?>
Where are the mistakes? Because the outputs are shown for just a second and then they will disappear.
Thank you to everybody.
When you submit the form it will reload all page again, so assigned html visible for short time only.
Use preventDefault() function to overcome this situation.
<script type="text/javascript">
$("#iscrizione").submit(function(event){
event.preventDefault()
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
On submitting form, it will reload page by default. We can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. Read more about .submit() event.
1.On using returning false after ajax call.
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
return false; // add return false here
});
2.By using event.preventDefault()
$("#iscrizione").submit(function(event){
event.preventDefault();// use preventDefault() on event
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
});
Either return false or preventDefault() will work, as the other two answers have described. However, it's important to understand that you don't have to submit the form at all, and indeed it isn't best practice to do so. After all, it doesn't make much sense to use HTML to submit the form and then disable the submit behavior in your code. Especially when you don't have to.
AJAX was invented to overcome the problems (such as yours) that result when you reload the page. The point about AJAX is that it gives you the ability to update your page with new data without reloading it.
So, the cleaner way to do what you want is to make your button simply a button, and call your code from the button's click event. Have a look at this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Test
</title>
<!--jQuery file-->
<script src="includes/jquery/jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function showMyPHP() {
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("#td_nome").html(msg.nome);
$("#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
}
$('#invia').on('click', function(e, ui){
showMyPHP();
});
});
</script>
</head>
<body>
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<button type="button" id="invia">"ISCRIVITI"</button>
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
</body>
</html>
You can see that we're not submitting the form at all here. Rather, we're calling the AJAX through the button's click event. You'll see that you get the results you're looking for, without resorting to using HTML to submit the form and then disabling the default submit behavior in code.
Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});
It is a datepicker. I need to pass selected date as parameters in php form url.
The datepicker value is in jQuery. I got the selected date value through ajax and i posted as $_POST['from'] and $_POST['to'].
<script type="text/javascript">
$(document).ready(function(){
var frm = $('#easy_widget_form');
var first, second;
first = $(".hasDatepicker[name=from]").val();
second = $(".hasDatepicker[name=to]").val();
//alert(first + " , " + second);
first = $(".hasDatepicker[name=from]").datepicker('getDate');
second = $(".hasDatepicker[name=to]").datepicker('getDate');
//alert(first + " , " + second);
jQuery.ajax({
type: "POST",
url: "form_widget.php",
data: "first=" +first+"&second="+second,
dataType: "text",
success: function(){
alert("Done");
}
});
}};
</script>
When i pass the date in url http://www.domain.com/?from=".$_POST['from']."&to=".$_POST['to']; it doesn't work.
Error : String was not recognized as a valid DateTime.
Here is my PHP
<form method="post" action="http://www.domain.com/?from=".$_POST['from']."&to=".$_POST['to']" name="easy_widget_form" id="easy_widget_form">
<input id="easy-widget-datepicker-from" type="text" name="from" value="20.04.2014" class="hasDatepicker">
<input id="easy-widget-datepicker-to" type="text" name="to" value="22.04.2014" class="hasDatepicker">
<p class="easy-submit"><input type="submit" class="easybutton" value="Reserve now!"></p>
</form>
can someone help?
you are doing it wrong actually as far as I understand. If you use ajax for form submit why do you want to have that action url in form markup?
I would prefer to do like this
// point the request to necessary url
jQuery.ajax({
type: "POST",
url: "http://www.domain.com/?from="+first+"&to="+second,
success: function(response){
// use the response accordingly
}
});
Hope this help
I've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.
I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');