Calling php scripts using ajax - php

I am making a chat script and an hoping to code it so that when a user submits a message, the script will run chat_new.php and then refresh #cbox. I use the code below to try and accomplish this, but unfortunately it won't reload. Just to rule it out, I tested without any jQuery and chat_new.php executes without problems, so it definitely is my ajax script. In addition, getUpdates() works just fine on it's own. I only have a problem when posting new messages through ajax.
<div id="cbox" align="left">
<script>
$(document).ready(function() {
setInterval(function() {
getUpdates()
}, 2000);
});
function getUpdates() {
$("#cbox").load("/lib/chat_post.php");
}
$("#submitmsg").click(function() {
$.ajax({
type: 'POST',
url: '/lib/chat_new.php',
data: {
submitmsg: 'submitmsg',
usermsg: 'usermsg'
},
success: function() {
getUpdates()
}
});
});
</script>
</div>
<form name="message" method='post' id="cbox_input">
<input name="usermsg" id='usermsg' type="text" size="63" maxlength="255" />
<input name="submitmsg" id='submitmsg' type="submit" />
</form>

Several issues:
Your click handler exists before the element it references and is not inside document.ready. Therefore it can't find the element and never gets bound to it
Once that is fixed you need to prevent the default form submit process. Otherwise page will reload on submit
// put this inside ready()
$("#submitmsg").click(function (event) {
event.preventDefault();
//other code
})

This might be a simple as moving }); from the third line of your script, to just before </script> so that your function and your ajax call are inside $(document).ready(... and therefore only get processed once the DOM has loaded, and all HTML elements are on the page.

Related

variable not sent from ajax to php

I am submiting a form to a php page using ajax in order to make a query.
The problem is that the $_POST is empty.
What am I doing wrong here?
Any ideas?
FORM
<div id="button_left">
<form>
<label>
<input type="text" class="search" size="30" style="margin-left:20px;" name="epitheto" id="epitheto" placeholder="Επίθετο" />
</label>
<label>
<input type="submit" value="Αναζήτηση" />
</label>
</form>
</div
FUNCTION
$(function () {
$('#button_left').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'people_name_query_final.php',
data: $('form').serialize(),
success: function () {
$("#pelates_last_name_query").slideDown("slow");
$("#pelates_last_name_query").load( "people_name_query_final.php");
}
});
});
});
PHP
if(isset($_POST['epitheto'])){
//some code
}
Add one argument to your success function:
success: function (response) {
$("#pelates_last_name_query").slideDown("slow");
$("#pelates_last_name_query").html( response);
}
and you will get response from php page....
P.S. Test php page should look like this (or whatever you want for response - you should ECHO something, send some output):
<?php
if(isset($_POST['epitheto'])){
print_r($_POST);
}
?>
so, vars are sent properly.... (i've tested it right now).
If your php page looks like code you atached/showed us - there is no any output, you didn't printed anything....
<form> element has submit event, <div> doesn't.
Change the first line to this:
$('form').on('submit', function (e) { // <-- change '#button_left' to 'form'
// (...) Code
}
I believe Amit might be correct. You are specifying the incorrect data to submit.
Change <form> to <form id="content">
Then change your JQuery code accordingly.
$('#content').on('submit', function (e) {//rest of your code//}
Another possible issue is that the scope on your URL is incorrect.
url: 'people_name_query_final.php', will work assuming the PHP script and JQuery are in the same directory.
Also, if you do print_r($_POST); exit; in your PHP script you see nothing?
Check the network tab on your browser developer tools to make sure the data is sent properly.

Cant .ajax() submit a php form that has been loaded onto main page with jQuery .load()

I'm having the following problem. Below is an explanation of what my PHP pages are and how they work. When I access form.php directly and try to submit it via AJAX, it works perfectly.
Problem - When I .load() form.php into main.php, none of the jQuery code within form.php fires. (verified through firebug) No submits, no alerts, nothing. How can I get the jQuery code within form.php to work when its loaded into main.php?
main.php -> This is the main PHP page which has a link on it. Once this link is clicked, the following jQuery code fires to load "form.php" within a div called #formcontainer. This is the code within main.php that loads form.php.
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php");
});
});
</script>
form.php -> this is a form that gets loaded above. It submits data to MySQL through an jQuery .ajax() POST. Here is the jquery code which submits the form, which has an ID called #homeprofile.
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$(document).ready(function() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
});
Use on() for this like,
$(document).on('submit','#homeprofile',function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
return false;
});
You should be using the .on() syntax for targeting dynamically created elements (elements loaded into the DOM by JS or jQuery after the initial rendering)
Good
// in english this syntax says "Within the document, listen for an element with id=homeprofile to get submitted"
$(document).on('submit','#homeprofile',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Not as good
// in english this syntax says "RIGHT NOW attach a submit listener to the element with id=homeprofile
// if id=homeprofile does not exist when this is executed then the event listener is never attached
$('#homeprofile').on('submit',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Hopefully this helps!
Small issue is that you reference formcontaineropen in the jquery call (this is probably a typo?). The cause is that that a JS code loaded via AJAX will get interpreted (therefore eval() is not needed) but the document ready event will get triggered immediately (which may be before the AJAX loaded content is actually inserted and ready in the document - therefore the submit event may not bind correctly). Instead you need to bind your code to success of the AJAX request, something like this:
main.php:
<html>
Foobar
<div class="formcontainer"></div>
<script src='jquery.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontainer").load("form.php", '',
function(responseText, textStatus, XMLHttpRequest) {
onLoaded();
});
});
});
</script>
form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type="text/javascript">
function onLoaded() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
};
</script>
My solution is somewhat peculiar but anyhow here it is.
This would be your main.php:
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php", '', function(response){
var res = $(response);
eval($('script', res).html());
});
});
});
</script>
And this is your form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
</script>

How to correct bind javascript/jquery to included php files

I know this has been asked some time, but the solutions before did not help, and I do not understand if I am missing something
I have simple php/hmtl page with an index.php where I include the different content php pages with a simple GET check:
if (isset($_GET['section'], $section[$_GET['section']])) {
include $section[$_GET['section']];
} else {
include $section['home'];
}
Now one of these sections contains a form which I want to do some magical ajax/jquery action with.
In my javascript file which is loaded at the bottom of the index.php I have following jquery ajax stuff
//ajax load domain search script
$(document).ready(function(){
$('#lookup_domain').live("click", function(e) {
e.preventDefault();
searchVal = $('#domain').val();
topLevel = $('.custom_select').val();
domain = searchVal + '.' + topLevel;
$.ajax({
type: 'GET',
url: 'script_domain.php',
data: 'domain=' + domain,
dataType: 'html',
beforeSend: function() {
$('#result').html('<img style="margin-left: 80px;margin-top: 30px;" src="_assets/img/loader.gif" alt="loading..." />');
if (!searchVal[0]) {
$('#result').html('<p>Syötä domain nimi.</p>');
return false;
}
},
success: function(response) {
$('#result').html(response);
},
error: function(response) {
$('#result').html('<p>Haussa virheitä.</p>');
}
});
});
});
I thought it would be enough to use
$(document).ready(function(){
and the live method (i have jquery 1.7.1 so live should be working?)
$('#lookup_domain').live("click", function() {
but unfortunatedly this is not working, the form just sends it to itself and loads the page again.
Here is the form:
<?php
if(!defined('indexcalled')){die('Direct access not premitted');}
?>
<div id="domain_search">
<h5>hae verkkotunnusta</h5>
<form action="#" method="get" class="domain_form">
<input type="text" name="domain" class="domain_input" />
<div class="select_wrap">
<select class="custom_select">
<option value="fi">.FI</option>
<option value="com">.COM</option>
<option value="net">.NET</option>
<option value="me">.ME</option>
<option value="info">.INFO</option>
</select>
</div><!--/select wrap-->
<input type="submit" value="Syötä" class="domain_submit_btn" id="lookup_domain"/>
</form>
<div class="clear"></div>
</div><!--/domain search-->
What am I missing here? Is there any good documentation about how to use jquery with this kind of dynamical page setup?
EDIT
My original question was, how to handle these kind of elements properly with jquery, because they are included later on.
I found that I should be working with on() instead of live because its deprecated in 1.7 too. So I edited the code like this:
$(document.body).on("click", '#lookup_domain', function(e){
e.preventDefault();
$(document.body).on("click", '#domain', function(event){
alert($(this).text());
});
But the alert does not work, it does nothing. What am I missing here?
You're calling e.preventDefault(), which should keep the form from submitting, however you are not passing the event object into your click handler. Update it to this and it should work:
$('#lookup_domain').live("click", function(e) {
e.preventDefault();
...
});
Because you are using a submit button for your live click you need to disable the form submission.
There are two solutions:
1, Return false on the click event:
$('#lookup_domain').live("click", function() {
// all of your code
return false;
})
2, add an onsubmit attribute to your form:
<form action="#" method="get" class="domain_form" onsubmit="return false;">
</form>
Thanks for all guys who helped me in the chat, the correct method is to first have the document ready, then use .on() with click method with body to access the element created afterwards. Then just with normal .val() to get the values, like this:
$(document).ready(function(){
$(document.body).on("click", '#lookup_domain', function(e){
e.preventDefault();
searchVal = $('#domain').val();

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
});

Categories