JQuery to Reload DIV Layer with PHP GET from Text Box - php

Greetings from some noob trying to learn JQuery,
I am attempting to make it when you type something in a box below a div layer it reloads that layer upon submission of the form with a php get of the text box in the form. Expected behavior is it would reload that box, actual behavior is it don't do anything. Can someone help me out here.... Below is the code.
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
<input type="submit" name="submit" class="button" id="submit_btn" value="New City" />
</form>
<script>
/* attach a submit handler to the form */
$('form[name="changewx"]').submit(function(event) {
/* get some values from elements on the page: */
var $form = $( this ),
city = $('#city').val()
/* Send the data using post and put the results in a div */
$('#currentwxdiv').load('http://api.mesodiscussion.com/?location=' + city);
return false;
});
</script>
Its giving the Javascript Console Error Error....
"XMLHttpRequest cannot load http://api.mesodiscussion.com/?location=goodjob. Origin http://weatherofoss.com is not allowed by Access-Control-Allow-Origin."

You are using POST method? is impossible to post to an external url because with ajax, the url fails the "Same Origin POlice".
If you use GET method, is possible to do that.
Another solution is to make a proxy. A little script that recive the params and then... using CURL or another thing you have to post to the external URL... finally, you jquery have to do the post thing to the proxy:
For example:
$.ajax({
url: '/proxy.php?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});

I do it so:
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
</form>
<script>
$('#city').keyup(function() {
var city = $('#city').val()
$.ajax({
url: 'http://api.mesodiscussion.com/?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
});
</script>

To help you out, i need to test this.
What's the url address of your html code working ?
http://api.mesodiscussion.com/?location= doesn't work... only list the directory content... maybe that's de problem?
Greatings.

Related

Ajax.serialize() request NOT WORKING

I am trying to send my form values to php page in order to perform SQL requests to my server according to my form values. This is original php with form and ajax script:
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<form enctype="multipart/form-data" method="post">
<input type="datetime-local" name="start" id="start">
<input type="datetime-local" name="finish" id="finish">
<input type="checkbox" name="consta" id="consta" value="tru"> Remove const
<input type="submit" name="apply" id="apply">
</form>
<script>
$('#apply').click(function(){
var data= $('form').serialize();
$.post('gensetapply.php', data);
});
</script>
And in gensetapply.php I am trying to get variables through $_POST:
<?php
$con=$_POST['consta'];
$str=$_POST['start'];
$fin=$_POST['finish'];
echo $con.", ".$str.", ".$fin;
?>
So, I am sure my ajax request is not working.
I am new to this things and have wrote code above looking to similar examples, so please feel welcome to point out my mistakes. There might be a typo cause I am handtyping it again here, not copy-paste from source.
EDIT:
It was working, I just couldn't see it when i refresh the page, but through devtools in Chrome (Network>Response) I. Hope it'd help some other fools like me ;)
1st : Your using post method to post the data to server so you need to prevent the default submit
<script>
$('#apply').submit(function(e){
e.preventDefault();
var data= $('form').serialize();
$.post('gensetapply.php', data);
});
</script>
2nd : or Simple change the type="submit" to type="button".
Here 'Apply 'button type is submit. Therefore your form submits immediately. As you are handling form submission through ajax so the solution is you need to stop submitting form. You can fix it returning false in click event like following
<script>
$('#apply').click(function(){
var data= $('form').serialize();
$.post('gensetapply.php', data);
return false;
});
</script>

jQuery Ajax Call inside of PHP

I'm clearly doing something wrong here, but I can't figure out why the Ajax isn't firing and instead insists upon a page load. The newBatable() fires fine, I just can't seem to get the vote to respect the ajax call.
HTML - not sure how to put html in here as code :/ - I feel dumb.
<form class="form-horizontal" id="batable1" action="vote.php" method="GET">
<div id="success-vote-1"></div>
<input type="radio" name="batableResult" value=" include ()" /> include ()<br/>
<input type="radio" name="batableResult" value="require ()" />require ()<br/>
<input type="radio" name="batableResult" value="both of above" />both of above<br/>
<input type="radio" name="batableResult" value="None of above" />None of above<br/>
<button class="btn btn-primary" onClick="vote(1)">Vote</button>
<input type="hidden" name="batableId" id="batable-id" value="1"/>
</form>
JS - the console display everything I want, the php script processes everything nicely and functions perfectly, it is just it has to load the php in the browser so it's not using AJAX
/***************************************/
function newBatable() {
var batableData = $('#new-batable').serialize();
//console.log(batableData);
$.ajax({
url: "process.php",
data: batableData,
success: function(data){
$('#success-new-batable').html(data);
}
});
}
/***************************************/
function vote(poll_id) {
//console.log(poll_id)
var batableId = "#batable" + poll_id;
//console.log(batableId)
var pollData = $(batableId).serialize();
//console.log(pollData);
$.ajax({
url: "vote.php",
data: pollData,
success: function(data){
var batable_success_id = "#success-vote" + poll_id;
$(batable_success_id).html(data);
}
});
}
The submit button fires the JavaScript and then immediately submits the form.
If you are using onclick, then return false to stop that.
You would be better off using a more modern event binding technique though.
how about attaching a click event via jquery to the button?
$(".btn").on('click', function(e){
e.stopPropagation()
e.preventDefault();
vote(1);
});
this would usually be placed in document .ready jquery in an external file or somewhere near the bottom of your page inside script tags.
Does this help?
Since you're already using jQuery, as SubstanceD, you should use jQuery's on() method and stop the event propagation and prevent the default action (submitting the form).
I also noticed a possible bug in your code. It looks like there is a typo. You have
var batable_success_id = "#success-vote" + poll_id;
and <div id="success-vote-1"></div>. You have a dash after vote in the div's ID while you are concatenating batable_success_id into #success-vote1, for example. So even if the AJAX call is made, it probably won't update your HTML like you're expecting.

how to have a pop up contact form on submit display a confirmation message in the popup?

I'm having great issues making this contact form that can be seen on the below visual. What I want the contact form to do is display on submit a thank you message or a message of confirmation instead of redirecting to the contact.php file where there isn't any styles you can see this in action on the provided link.
I've found some information that I can do this with Jquery Ajax that I've also tried displayed below, but I still can't seem to get it to work on submit to show a message in the pop up.
Does anyone know an easier way to do this or maybe point me in the right direction as this is something that I've been trying to fix for god knows how long.
Thank you for any help
Visual:
http://madaxedesign.co.uk/dev/index.html
PHP & HTML:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form id="submit_message" class="hide_900" method="post" action="/contact.php" onsubmit="javascript: doSubmit();">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div class="submit">
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
Jquery:
function doSubmit(){
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
You can add return false; at the end of your doSubmit function or the following code to prevent the form to redirect the user to the action page.
var doSubmit = function (event) {
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
event.preventDefault();
}
$(function () {
$('#submit_message').submit(doSubmit);
});
Modified HTLM
<form id="submit_message">
...
</form>
What is this code doing ?
First, we are defining a function to submit the form data.
Notice the event argument in the function. The first variable in this function is all the form values serialized in a ajax-complient request string. The .ajax() function is sending all the datas to your server. Note that as you did not set the type argument in the .ajax() function, the data are going to be send using the GET HTTP method.
Finally, event.preventDefault() prevents the submit event to be triggered in the browser. When the browser detect a submit event, it will try to submit the form based on the action and the method parameters in the <form> html tag. Usually, this submission performs an user redirection to the action page. This event.preventDefault() will disable this redirection. Note that the event argument is going to be set automatically by jQuery.
Last part, the $(function() { ... }); part means "execute this part when the document is fully loaded." It ensures that the element with sumbit_message id exists before calling the .submit() method. This last method is an event binder. It means that when the submit event is fired on the submit_message form, the function doSubmit will be called.
I hope you have a better understanding of this script. This is a pretty basic one, but if you understand clearly the mechanics, it will help you do become a better jQuery programmer. :)
Fiddle Demo
1.<form onsubmit='confirm()'>
function confirm()
{
alert("Thank You");
}
2.in contact.php call the page that is displayed again
You need to prevent the default event of the form. To do this, add the e.preventDefault(); function to the top of your function in order to prevent this event from firing.
Also notice that we are passing the e parameter to your function. This represents the event that has been fired.
function doSubmit(e){
e.preventDefault();
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
}
Try this
change your form with
<form id="submit_message" class="hide_900" method="post">
and in script put it
$("#submit_message").submit(function(e){
e.preventDefault();
//call your ajax
});

sending form data to php using ajax

I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts....
It would be great help if some one helps me out with this
index.html
<script type="text/javascript">
$(document).ready(function(){
$("#submit_btn").click(function() {
$.ajax({
url: 'count.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data');
}
})
});
</script>
</head>
<form name="contact" id="form" method="post" action="">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
In count.php i want to implement
<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);
$output=$FNO+$SNO;
echo $output;
?>
(i want to display output in count.php page not in the first page index.html)
Thanks for your help in advance.
You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:
$('#form').submit(function() {
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
alert(data); //check to show that the calculation was successful
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.
I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:
$("#submit_btn").click(function() {
$("#form").submit();
});
I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.
Index.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
<label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
<!-- The following div will use to display data from server -->
<div id="result"></div>
</body>
<script>
/* attach a submit handler to the form */
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
//Get the first value
value1 = $form.find( 'input[name="SNO"]' ).val(),
//get second value
value2 = $form.find( 'input[name="FNO"]' ).val(),
//get the url. action="count.php"
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { SNO: value1, FNO: value2 } );
/* Put the results in a div */
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
});
</script>
</html>
count.php
<?php
$FNO = $_POST['FNO'];
$SNO= $_POST['SNO'];
$output = $FNO + $SNO;
echo $output;
?>
There are a few things wrong with your code; from details to actual errors.
If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.
Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").on("submit", function () {
$.post("/count.php", $(this).serialize(), function (data) {
alert(data);
}, "text");
return false;
});
});
</script>
As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.
<form method="post" action="/count.php" id="form">
<label for="number1">Enter First no:</label>
<input type="number" name="number1" id="number1">
<label for="number2">Enter Second no:</label>
<input type="number" name="number2" id="number2">
<input type="submit" value="Calculate">
</form>
The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.
Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.
<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
echo 'Error';
} else {
echo ($number1 + $number2);
}
Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).
You can do like below to pass form data in ajax call.
var formData = $('#client-form').serialize();
$.ajax({
url: 'www.xyz.com/index.php?' + formData,
type: 'POST',
data:{
},
success: function(data){},
error: function(data){},
})

Simple PHP/AJAX question

Ok, so I am fairly new to webdeveloping, so probably a silly question:
I have this search form which does autocomplete for fooditems (gets values from a database column) and that works. Now when I press the submit button I want to load a block of code that displays the food-items' calories etc (also in the database on the same row as the food-item).
How can I accomplish such a thing. I kno this is a fairly broad question, but what i am really asking is, how can I make a small part of my website reload when pressing the submit button and using the input given in the text field as a parameter of some kind.
I don't need whole answers, just any tips getting to the right path would be greatly appreciated!
here my code for the input and button:
in head
<script type="text/javascript" src="jquery.js"></script>
<script>
function ok(){
$.post("test.php", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
}
</script>
in body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" onclick="ok()" />
</form>
or:
head:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$("input[type='submit']").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
</script>
body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" />
</form>
jQuery and Ajax.
Change that input to a button
<button id="submit">Save</button>
For this I would do something like:
$("button#submit]").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
You need to first catch the click event .bind("click"). Then initiate an ajax call $.post which you will send data to. This data is received on the server via the POST array.
Like Josh said, jQuery is the way to go here.
You'll want to do 3 things:
Attach a click handler to a button like "onclick='doSomething();'"
In that function,use jQuery to do an async post to a script like
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
When this comes back, you can do something with that data(instead of the alert above), like $('#listnode').append... which would stick the HTML into your list
This is the general pattern, but you'll have to fit it to your scenario.
It is hard to answer your question from what little you have given us, but I will assume little knowledge.
Your input fields have to be inside a form tag. The form tag includes an action and a method. The method must be "POST" to send the data. The action can be any URL.
You simply have to name the URL of your php script that will handle the results.
It will find the data in $_POST['food'] etc. It has to build the reply page - the whole screen, with the food and data and the search form for the next submit if you want.
If you want to use AJAX to replace part of the screen, then you have a whole nother level of problems. The trick is to replace the content of a div tag with the requested data.

Categories