Problem in jQuery sending values with $.post - ajax

EDITED: After two hours trying to solve my problem I was obfuscated, so I came to StackOverflow, I read related questions that did´nt solve my problem, and finally I asked help. I simplified my code and posted this question. Testing the code you gave me I could see where I was failing. That's embarrassing: just before calling $.post I was changing the content of the form div to show an ajax loader gif, so when $.post was called the inputs had been deleted.
Hello. I´m testing jQuery AJAX functions, and I can´t send data by $.post.
This is the process:
form.php: a html form and a jquery script that send values by $.post and alerts the result
process.php: a php script that receives the values, work with them and returns something.
FORM
<form action="#" method="post">
<label for="name">Your name</label>
<input type="text" name="name" id="name" />
<label for="email">Your email</label>
<input type="text" name="email" id="email" />
<input type="button" value="send" id="btnSend" />
</form>
JQUERY
function sendAjaxPost(){
$.post('process.php',{
name: $('#name').val(),
email: $('#email').val()
},
function(data){
alert(data);
});
}
$('#btnSend').click(function(){
sendAjaxPost();
}
PROCESS.PHP
foreach($_POST as $key => $value)
{
echo $key . ' => ' . $value . '<br/>';
}
I can´t send $('#name').val(), but if I send a string everything works fine. I have alert $('#name').val() inside the jQuery function and it´s possible to read it. I have followed the sintaxis shown in $.post.
Could someone give me a light? Thanks in advance

If you can read the input fields on the function, you can try this,
function sendAjaxPost(){
name=$('#name').val();
email=$('#email').val();
alert(name);
alert(email);
//If this two alerts the name and email, try with $.get();
$.post('process.php',{
name: name,
email:email
},
function(data){
alert(data);
});
}

Related

send multipart form with ajax - send file and text

i need to send some data and an image file with ajax .
i know that must use multipart form and formdata but i don't know how - i googled it and i found some way for send file, but i need to send whole form.
this is my html form
<form id="formData" enctype="multipart/form-data">
<input type="file" id="uploader" name="image" accept="image/jpg, image/jpeg, image/png, image/bmp, image/raw"/>
<input type="hidden" name="action" id="action" value="receiver"/>
<input type="hidden" name="route" id="route" value="image"/>
</form>
thanks.
Hope something like this might do it for you mate... :)
html
//Include this script in head
<script src="http://malsup.github.com/jquery.form.js"></script>
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allows you to have full control over how the data is submitted
<div id='preview'></div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
<input type="file" name="photoimg" id="photoimg" />
</form>
Script File
$('#photoimg').on('change', function()
{
$("#imageform").ajaxForm({target: '#preview', //Shows the response image in the div named preview
success:function(){
},
error:function(){
}
}).submit();
});
ajaximage.php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
$tmp = $_FILES['photoimg']['tmp_name'];
$path = "uploads/";
move_uploaded_file($tmp, $path.$name) //Stores the image in the uploads folder
}
You could get the values of fields like action,route etc using $_POST inside the php file.For mare details check the below link mate.. :)
http://malsup.com/jquery/form/#ajaxForm

My .ajax call isn't working

I have a form on my website that pushes to my e-mail address. Previously before I wrote an ajax function the form would successfully push to my e-mail address. Only problem is when the user fills out the form it takes them to another page upon submitting the form. The HTML for my form is below.
<form id="contact" method="post" action="E-mail-form.php" name="EmailFromMyWebsite">
<label for="name">Name</label> <br>
<input type="text" name="name" class="required" placeholder="Your Name" title=" (Your name is required)"> <br />
<label for="email">E-mail</label> <br>
<input type="email" name="email" class="required email" placeholder="Name#email.com" title=" (Your email is required)"> <br />
<label for="message">Message/Comment</label> <br>
<textarea name="message" class="required" placeholder="Leave a brief message" title=" (Please leave me a brief message)"></textarea> <br />
<input type="submit" name="submit" id="submit" value="Send Message" />
</form>
</div><!-- /end #contact-form -->
The ajax call I wrote is...
$("#submit").on('click', function(){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:"formData",
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
});
My javaScript console shows no errors so I think the problem is with my jQuery logic. On Chrome when I click submit I am redirected to my homepage. On Firefox the form submits but I am redirected to another page, therefore it is completely ignoring my AJAX call. Can someone with AJAX experience tell me what I'm doing wrong? Also I would love to attach a message if the call fails. Can I add 'failure:' and for the value put a function just like I did for success?
You have two issues
your form is submitting normally
you're attempting to post the wrong data
To prevent the form from submitting you can return false from the jQuery click handler or call preventDefault from the event object.
You are sending a string "formData" as the form data instead of the string in the formData variable
$("#submit").on('click', function(event){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:formData,
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
event.preventDefault();
// or
return false;
});
There's a good chance that the normal form submit action is still taking place, even though you have an AJAX call as well. An easy fix for this may be to simply change the button type from submit to button. That way your click handler will still work, but it won't perform the default action of submitting the form on its own.
<input type="button" name="submit" id="submit" value="Send Message" />

Automate AJAXed forms with Jquery

I want to improve my website and figured out a good way to do it was by submitting forms via AJAX. But, I have so many forms that it would be inpractical to do $('#formx').submit(). I was wondering if there was a way to do this automatically by making an universal markup like;
<form class="ajax_form" meta-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
</form>
And have this submit to ajax/pagename.php, where it automatically includes inputx and inputy?
This would not only save me a lot of time but also a lot of lines of code to be written.
First question so I hope it's not a stupid one :)
Something like this should work for all forms. It uses jQuery - is this available in your project? This specific code chunk hasn't been tested per say, but I use this method all the time. It is a wonderful time saver. Notice I changed meta-submit to data-submit so that its value can be fetched using $('.elemenet_class').data('submit');
HTML
<!-- NOTE: All Form items must have a unique 'name' attribute -->
<form action="javascript:void(0);" class="ajax_form" data-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
<input type="submit" value="go" />
</form>
JavaScript
$('.ajax_form').submit(function(e){
var path = $(this).attr('data-submit'); //Path to Action
var data = $(this).serialize(); //Form Data
$.post(path, {data:data}, function(obj){
});
return false;
})
PHP
//DEBUGGING CODE
//var_dump($_POST);
//die(null);
$data = $_POST['data'];
$inputx = $data['inputx'];
$inputy = $data['inputy'];
you can create ajax fot text boxes so that it can update to database whenever change the focus from it.
<form id="ajax_form1">
<fieldset>
<input type="text" id="inputx" value="x_value" />
<input type="text" id="inputy" value="y_value" />
</fieldset>
</form>
<script>
$(document).ready(function()
{
$("form#ajax_form1").find(":input").change(function()
{
var field_name=$(this).attr("id");
var field_val=$(this).val();
var params ={ param1:field_name, param2:field_val };
$.ajax({ url: "ajax/pagename.php",
dataType: "json",
data: params,
success: setResult
});
});
});
</script>

Load Dojo form from ajax call

I am trying to implement something like this.
http://app.maqetta.org/mixloginstatic/LoginWindow.html
I want the login page to load but if you click the signup button then an ajax will replace the login form with the signup form.
I have got this to work using this code
dojo.xhrGet({
// The URL of the request
url: "'.$url.'",
// The success callback with result from server
load: function(newContent) {
dojo.byId("'.$contentNode.'").innerHTML = newContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});'
the only problem is the new form just loads up as a normal form, not a dojo form. I have tried to return some script with the phaser but it doesnt do anything.
<div id="loginBox"><div class="instructionBox">Please enter your details below and click <a><strong>signup</strong>
</a> to have an activation email sent to you.</div>
<form enctype="application/x-www-form-urlencoded" class="site-form login-form" action="/user/signup" method="post"><div>
<dt id="emailaddress-label"><label for="emailaddress" class="required">Email address</label></dt>
<dd>
<input 0="Errors" id="emailaddress" name="emailaddress" value="" type="text"></dd>
<dt id="password-label"><label for="password" class="required">Password</label></dt>
<dd>
<input 0="Errors" id="password" name="password" value="" type="password"></dd>
<dt id="captcha-input-label"><label for="captcha-input" class="required">Captcha Code</label></dt>
<dd id="captcha-element">
<img width="200" height="50" alt="" src="/captcha/d7849e6f0b95cad032db35e1a853c8f6.png">
<input type="hidden" name="captcha[id]" value="d7849e6f0b95cad032db35e1a853c8f6" id="captcha-id">
<input type="text" name="captcha[input]" id="captcha-input" value="">
<p class="description">Enter the characters shown into the field.</p></dd>
<dt id="submitButton-label"> </dt><dd id="submitButton-element">
<input id="submitButton" name="submitButton" value="Signup" type="submit"></dd>
<dt id="cancelButton-label"> </dt><dd id="cancelButton-element">
<button name="cancelButton" id="cancelButton" type="button">Cancel</button></dd>
</div></form>
<script type="text/javascript">
$(document).ready(function() {
var widget = dijit.byId("signup");
if (widget) {
widget.destroyRecursive(true);
}
dojo.parser.instantiate([dojo.byId("loginBox")]);
dojo.parser.parse(dojo.byId("loginBox"));
});
</script></div>
any advice on how i can get this to load as a dojo form. by the way i am using Zend_Dojo_Form, if i run the code directly then everything works find but through ajax it doesnt work. thanks.
update
I have discovered that if I load the form in my action and run the __toString() on it it works when i load the form from ajax. It must do preparation in __toString()
Firstly; You need to run the dojo parser on html, for it to accept the data-dojo-type (fka dojoType) attributes, like so:
dojo.parser.parse( dojo.byId("'.$contentNode.'") )
This will of course only instantiate dijits where the dojo type is set to something, for instance (for html5 1.7+ syntax) <form data-dojo-type="dijit.form.Form" action="index.php"> ... <button type="submit" data-dojo-type="dijit.form.Button">Send</button> ... </form>.
So you need to change the ajax contents which is set to innerHTML, so that the parser reckognizes the form of the type dijit.form.Form. That said, I urge people into using a complete set of dijit.form.* Elements as input fields.
In regards to:
$(document).ready(function() {});
This function will never get called. The document, youre adding innerHTML to, was ready perhaps a long time a go.
About Zend in this issue:
Youre most likely rendering the above output form from a Zend_ Dojo type form. If the renderer is set as programmatic, you will see above html a script containing a registry for ID=>dojoType mappings. The behavior when inserting <script> as an innerHTML attribute value, the script is not run under most circumstances (!).
You should try something similar to this pseudo for your form controller:
if request is ajax dojoHelper set layout declarative
else dojoHelper set layout programmatic

Make form use ajax

I am having issue making a form be sent using ajax.
Here is my code:
<form id="form" method="get">
<input type="text" name="name" id="name"><br>
<input type="text" name="email" name="email"><br>
<input type="submit" id="submit" value="submit">
</form>
$('#submit').click(function(event){
alert('ajax');
});
The "ajax" alert shows, but then the page gets reloaded! How can I stop this behaviour?
You have to use preventDefault
$('#submit').click(function(event){
event.preventDefault();
alert('ajax');
});
use $.submit() instead of click :)
$('#form').submit(function(event){
alert('ajax');
// here some ajax functions for sending via get or post ;)
return false; // this stops loading the action site.. its something like e.preventDefault() on links
});

Resources