Basicly, In my html I have a form that consists of 2 selects and 2 text inputs. I would like to send values from that form into a php file called solve.php. This file will produce a variable called $cenaCelkom. I want to show the value of that variable in one of my divs.
I have to send tvalues from my form without redirecting to the solve.php. I have this for sending values to my php, but I cant find out if it works.
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "solve.php",
data: formdata
});
return false;
});
});
If this is ok, I would like to know how to get the value from my php after executing it. BTW: I am not an experienced js or jquery programmer, so please go easy on me :)
Thank you.
<div id="myresult"><div>
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function (e) {
e.preventDefault();
var formdata = $(this).serialize();
$.post('solve.php', $(this).serialize(), function(result){
$('#myresult').html(result);
});
});
});
You can grab the values of the inputs by using $_POST['inputnamehere'] from your solve.php page.
You can use $.load() method in jQuery
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
$( "#yourDivId" ).load(
'solve.php',
$('form').serialize(),
complete(responseText, textStatus, XMLHttpRequest){
//do whatever after ajax operation
}))
return false;
});
});
</script>
On solve.php simply get the values via $_GET and use print() for output:
<?php
print( $_GET['val1'] + $_GET['val2']) // Show a summation of two numbers
?>
Related
I have 2 forms on the same page and want them to submit independently of each other using AJAX. The code I currently have is:
<script type="text/javascript">
$("#form_tab").on("submit", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
success: function(data){
$('#ResponseDiv').html(data);
}
});
});
</script>
When I put both form id's to form_tab they both submit when the other is. How Can I make they both submit interdependently with the same code? Thanks!
ID's must be unique or else you will have problems with JavaScript. You can use
$('form').on('submit', function() {
var formID = $(this).id; // get this form's id
Then you can use the ID, if you need to, to handle processing for each form.
I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.
I have a form where I would like to pass the value of an text input field to an external page without a form submit event. I would like to field value to become a php variable on the external page.
Here is what I have so far:
<script type="text/javascript">
jQuery(document).ready(function() {
$(function() {
cityField = $('#the_form input[id=city]');
$.ajax({
type: "POST",
url: "external.php",
data:{ city: cityfield },
success: function(data){
console.log(data);
}
});
});
});
</script>
Within the external.php page, I would like to declare the city form field value as a php variable as
$city = $_POST['city'];
To start with
jQuery(document).ready(function() {
and
$(function() {
are equivalent. The $(function() should be something like
$("input[type='button']").click(function() {
so that when you click the button, it runs the ajax request.
I cleaned up the code but the data is not being sent to external.php. It is being set but not posting. Here is my revised code
<script type="text/javascript">
$('#city').blur(function() {
var cityField = document.querySelector('#city').value;
$.ajax({
type: "post",
url: "external.php",
data: {'cityField': cityField },
dataType: "text",
success: function(data, status){
if(status=="success") {
alert("You typed: " + cityField);
}
}
});
});
I dont feel right posting an answer for a single change... But
EDIT: There are actually a few things...
<!-- For .click() -->
Click Me!
<script type="text/javascript">
// $(function() { // Trigger on page load
// $('#doStuff').click(function() { // Trigger on a click
$('#city').blur(function() { // Trigger when the focus on the field is lost (click away, tab to another field, ect)
// $('#city').change(function() { // Trigger when the fields value changes
var cityField = $('#city');
$.ajax({
type: "POST",
url: "external.php",
data:{ 'city': cityField.val() },
success: function(data){
console.log(data);
}
});
});
</script>
Changes:
You dont need jQuery(document).ready(function() {}) AND $(function(){ }). Its the same thing.
Its smart to put a var in front on your variables.
Case is important. cityField and cityfield are not the same thing
You were just sending the whole dom element to your external script. (which I assume you only wanted the contents of the input)
Also, you dont need to look for "an input, with an 'id' attribute , with a value of 'city'". Just look for #city
EDIT:
Your updated code (just putting it here so its easier to see):
<script type="text/javascript">
$('#city').blur(function() {
var cityField=$('#city').val();
$.ajax({
type:"post",
url:"autosuggest.php",
data:{'cityField':cityField },
dataType:"text",
complete:function(data, status) {
alert("You typed: "+cityField);
}
});
});
</script>
Your data will should be available in autosuggest.php as $_POST['cityField'];
Having a status check within the success function, is a little redundant, in my opinion.
It would be better to move the success:function(data,... to a complete:function(data,...
I need to submit a form and check for its completion without using the submit button.
I managed to submit it trough document.getElementById('logoForm').submit();, but now I need to call a function if the form was successfully submitted.
My form:
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
Submit function:
$("#file1").change(function() {
document.getElementById('logoForm').submit();
//setTimeout(reloadImg, 2000) this was how i called the next function but its not safe at all
alert('submited');
});
The function I want to be called on a successful submit:
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
You need to submit the form using AJAX, otherwise you will have a page reload, rendering all your JS void.
This is how you could do it with jQuery
//bind to submit
$("#logoForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
ok i got it working!!
$("document").ready(function(){
$("#file1").change(function() {
//bind to submit
$("#logoForm").submit(function(e)
{
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
});
});
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
but once i click the file input i have to reload the page to make it work again... any ideas how to work around this?
As Regent said: "Amazing mix of pure JavaScript and jQuery"
if you will be using jquery first of all you will need to include the jquery library, I don't know if you did that.
Also, if you are working with jquery try to use all that jquery provide you to write less code.
Seeing your code I am assuming that you have a form with a input type file into. And when a file is loaded to the field, you want to submit the form. Also the form is targetted to a frame, so I am assuming that you have an iframe element there too.
To know if the form was successfully submitted you can use an ajax request but in this case your are sending files with the form, so you can not use an ajax request.
You can return a javascript code in your response that will be executed from into the iframe so, you can access to the parent element to do that you want
I have modified a little bit your code to integrate jQuery at all.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
jQuery("#file1").change(function() {
jQuery('#logoForm').submit();
});
});
</script>
</head>
<body>
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
<input type="file" name="file1" id="file1" />
</form>
<iframe name="frame"></iframe>
</body>
</html>
Then in your includes/uplLogo.php you need to return the javascript code to execute a similar of reloadImg()
So, in your includes/uplLogo.php you could have:
<?php
...
Your code here
...
if($all_is_ok) { ?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var id = jQuery('#AppId', window.parent.document).val();
jQuery.post("includes/step_img.php", {id: id}, function(data) {
jQuery('#imgDiv', window.parent.document).html(data);
});
});
</script>
<?php } ?>
I have not tested it because I just wrote it but I think that works.
Try to comment this line: e.unbind();
Try also to add a log just after the input file changes, and verify if you can see the log in the js console:
...
$("#file1").change(function() {
console.log('input file changed');
//bind to submit
...
for those who will need this in the future the problem was:
$("#file1").change(function()
i just changed that to:
function changed()
and add it to input on onchange method!
i am using this jquery code:
<script type="text/javascript">
$(document).ready(function () {
$("#message").hide();
$("#please_wait_box").hide();
$("#editcustomer").submit(function (e) {
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString = $("#editcustomer").serialize();
$.ajax({
type: "POST",
url: "editcustomer_go.php",
cache: false,
data: dataString,
success: function (res) {
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if (res.indexOf("success") != -1) {
window.location.href = res.substr(8);
}
}
});
});
});
</script>
to submit forms without changing the page.
then the editcustomer_go.php echoed results display in:
<div id="message" class="messagebox"></div>
<div id="please_wait_box" class="messagebox">Please Wait...</div>
i am using tinymce for text editors - its working okay but when the data is posted in the PHP, its not seeing the changed data in the tinymce text editor - it has to be plain text.
how can i get round this?
To grab the data from TinyMCE you need to use their getContent() function.
So in your case it'd be
// Grab a reference to the editor
var ed = tinyMCE.get('tinymceeditorname');
// Get it's content
var editordata= ed.getContent();
... and then just pass editordata along with the rest of the form as the AJAX call data.