JQuery AJAX POST not returning anything - php

Can't figure out what's wrong but all that happens is the URL changes to "http://localhost/?search=test" if I enter "test" for instance.
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$("#Form").submit(function(e) {
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
</script>
</head>
<body>
<form id=Form>
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
search.php
<?php
echo 'The search is '. $_POST['search'];
?>

You're missing the action and method on your form, which are necessary for the form to generate a submit event.
<form id="Form" method="post" action="search.php" />
Now that we have the action and method defined, why not just take it from the form instead of re-writing it in Javascript? That would be better for re-usability. Also note that you have to assign event handlers when the DOM is ready. At the time you're assigning the event, the DOM element doesn't exist, so it will do nothing:
<script type="text/javascript">
$(document).ready(function() { // Here, after DOM is ready
$('#Form').submit(function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// At this point, we already have the response from the server (we got it asynchronously)
// Lets update a div, for example <div id="response_message"></div>
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
// Another option (same as before but with a function): Pass the response data to another function already defined: processData() in this case
// Use one or another, they're the same
processData( data );
},
error: function(err) {
alert('An error just happened...');
}
});
});
});
// This functions only receives data when the asynchronous call is finished
function processData( data )
{
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
}
</script>
Note that in asynchronous calls you DO NOT expect a return. It simply doesn't exist by design (because the script would be blocked until the data is ready, and that's called synchronous). What you do in asynchronous calls is to define a function/method that will be called at any time when the data is ready (that's the success handler function). You don't know at what time it will be called, you only know that it will be called when data has been fetched and the argument will be the actual response from the server.

1st you forget " Form id and good to add method=""
<form method="post" action="#" id="Form">
2nd try to use e.preventDefault(); in the beginning not the end
3rd try to rearrange the code
<body>
<form method="post" action="#" id="Form">
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
<script>
$("#Form").on('submit',function(e) {
e.preventDefault(); // use it here
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
});
</script>

Related

Multiple forms in in a page - load error messages via ajax

I having multiple forms in a single page submitting via jQuery ajax. All forms use same class names. Also i am using malsup jquery plugin for form submission.
I can successfully pass the data to a php file but the error message is reflecting on all forms div.message. I don't want to have different form ids because i need to have all ids in the jquery then.
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
jQuery part
<script>
$(document).ready(function() {
$('.myform').on('submit', function(event) {
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
$('div.message').append('<div>'+message+'</span>');
}
}
});
});
});
</script>
How can i append the error message to the submitted form's div.message correctly?
Any help will greatly appreciated.
I think you can get the msg div before post .
$(document).ready(function() {
$('.myform').on('submit', function(event) {
msgDiv=($this).children('div.message');//before post get the msg div first
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
msgDiv.append('<div>'+message+'</span>');
}
}
});
});
});
</script>

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>

Getting data from PHP page on form submit

I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)

Insert record using jQuery after ajax call doesn't work

I have an insert and load record (jQuery & PHP) script working fine without using AJAX. but after the AJAX call, insert (jQuery) doesn't work.
This is my code:-
$(".insert").live("click",function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval==''){
alert("Please Enter Some Text");
}
else{
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(html){
$("table#update tbody").prepend(html);
$("table#update tbody tr").slideDown("slow");
document.getElementById('content').value='';
}
});
}
return false;
});
$(".load").live("click",function() {
$.ajax({
type: "POST",
url: "test.php",
success: function(msg){
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
}
});
});
});
Definitely recommend using your browsers dev tools to examine the exact request that is submitted and see if there is a problem there first.
You might also want to change the way you pass the dataString to the ajax request.
If your boxval has a "&" in it then you'll end up with an incorrectly formatted string. So, try initialising data instead as:
var data = {};
data.content = boxval;
This will ask jQuery to escape the values for you.
I'd be curious to see your form markup and your back-end PHP code; it may provide a clue.
Often I'll have a form variable called 'action', just to tell the PHP code what I want it to do (especially if that PHP script is a controller for many different actions on an object). Something like <input type="hidden" name="action" value="insert"/> or even multiple <input type="submit" name="action"/> buttons, each with a different value. In the PHP code I'll have something like:
switch ($_POST['action']) {
case 'insert':
// insert record and send HTML
break;
// other actions
}
If you've done something like this, perhaps the PHP is looking for the presence of a variable that doesn't exist.
Without being able to look at your code, I'd highly recommend the incredibly handy jQuery Form Plugin http://jquery.malsup.com/form/ . It allows you to turn a form into an AJAX form, formats your data properly, and doesn't forget the data from any of your form elements (except <input type="submit"/> buttons that weren't clicked on, which is the same behaviour that a non-AJAX form exhibits). It works just like the standard $.ajax() method.
I solved the problem
I replaced this code
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
with
$("#container").html(msg);
Thank you very much for your answers
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clicker').click(function(){
var fname = $('.fname').val();
var lname = $('.lname').val();
var message=$('.message').val();
$.ajax({
type:"POST",
url: "submit.php",
cache:false,
data: "fname="+fname+"&lname="+lname+"&message="+message,
success: function(data){
$(".result").empty();
$(".result").html(data);
}
});
return(false);
});
});
</script>
</head>
<body>
<div>Data Form</div>
<form id="form1" name="form1" method="post" action="">
<input name="fname" type="text" class="fname" size="20"/><br />
<input name="lname" type="text" class="lname" size="20"/><br />
<div class="result"><textarea name="message" rows="10" cols="50" class="message"> </textarea></div>
<input type="button" value="calculate" class="clicker" />
</form>
</body>
</html>
submit.php
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("ajaxdb",$con);
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$message=$_REQUEST['message'];
$sql="insert into person(fname,lname,message) values('$fname','$lname','$message')";
mysql_query($sql) or die(mysql_error());
echo "The data has been submitted successfully.";
?>

jQuery submit ajax form with 2 submit buttons

im trying to achieve the following, in php i have a form like this:
<form method="post" id="form_1" action="php.php">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
the form action file is:
<?php
if( $_POST["sub"]=="add"){ ?>
<script>
alert("")
</script>
<?php echo "ZZZZZZ"; ?>
<?php } ?>
so this means if i press sub with value add an alert prompt will come up, how can i do the same thing(differentiate both submit) but using a Ajax request:
the following code so does not work:
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize()
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html)
}
})
})
})
</script>
</head>
<body>
<div id="1" style="width: 100px;height: 100px;border: 1px solid red"></div>
<form method="post" id="form_1" action="javascript:;">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
</body>
You could put the event handler on the buttons instead of on the form. Get the parameters from the form, and then add a parameter for the button, and post the form. Make sure the handler returns "false".
$(function() {
$('input[name=sub]').click(function(){
var _data= $('#form_1').serialize() + '&sub=' + $(this).val();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
You have to explicitly add the "sub" parameter because jQuery doesn't include those when you call "serialize()".
In this case you need to manually add the submit button to the posted data, like this:
$(function(){
$('form#form_1 :submit').submit(function(){
var _data = $(this).closest('form').serializeArray(); //serialize form
_data.push({ name : this.name, value: this.value }); //add this name/value
_data = $.param(_data); //convert to string
$.ajax({
type: 'POST',
url: "php.php?",
data: _data,
success: function(html){
$('div#1').html(html);
}
});
return false; //prevent default submit
});
});
We're using .serializeArray() to get a serialized version of the form (which is what .serialize() uses internally), adding our name/value pair to that array before it gets serialized to a string via $.param().
The last addition is a return false to prevent the default submit behavior which would leave the page.
Lots of semicolon missing, see below
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
});
});
jQuery Form plugin provide some advance functionalities and it has automated some tasks which we have to do manually, please have a look at it. Also it provides better way of handling form elements, serialization and you can plug pre processing functions before submitting the form.

Categories