Form post via PHP/Ajax from other domain - javascript

This is my form:
<!-- our form -->
<form id='userForm'>
<div><input type='text' name='firstname' placeholder='Firstname' /></div>
<div><input type='text' name='name' placeholder='Lastname' /></div>
<div><input type='text' name='email' placeholder='Email' /></div>
<div><input type='hidden' name='nl' vaule="1" /></div>
<div><input type='submit' value='Submit' /></div>
</form>
...and this is my current code:
$(document).ready(function(){
$('#userForm').submit(function(){
// show that something is loading
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'https://www.otherdomain.com?param=XYZ',
data: $(this).serialize()
}).done(function(data){
// show the response
$('#response').html(data);
}).fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
When submitting this form via Ajax form my URL (which is NOT the goal-URL) I get a origin-error beacause of the cross-domain-policy. I can not edit anything in .htaccess.
So, is there an easy way to send the serialized data via JSONP to an PHP script which is submitting the data to avoid the origin-issue?
Hope that you had these problem too and help me with this.

Related

Stop form from redirecting on submit

I'm very aware that this question has been asked several times but I have tried at least 6 solutions and it has not worked. I'm collecting data to send to a google form but on form submission the browser redirects to a success page. I'd like for it to all happen using AJAX but my code isn't working.
HTML:
<form id="userinfo" method="get" action="https://script.google.com/macros/s/xxx/exec" accept-charset="UTF-8" onsubmit="return false">
<input type="text" name="name" id="formname" placeholder="Name">
<input type="text" name="email" id="formemail" placeholder="Email">placeholder="Game Days">
<input type="submit" value="submit" id="upload_data"/>
</form>
JS:
$("#userinfo").submit(function(e) {
var urll = "https://script.google.com/macros/s/xxx/exec"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urll,
data: $("#userinfo").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
You could use the jQuery Form Plugin to send the form without doing a submit.
Your code should look kinda like this:
$("#userInfo").ajaxSubmit({
success: function(data)
{
alert(data); // show response from the php script.
}
});

Dynamic Ajax Form withsubmission

i am trying to build a customer list with using mysql,php and ajax. i currently have a list of customers displayed on the page and my end goal is to be able to create a new customer and edit the other customers on the same page.
i have a form for creating a new customer and then a form for each customer listed on the page its basically the same form as the new customer but with and id on the end of the name tags to make sure each name is different from the other and one updates and one creates see below
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form name='frm_details' id='frm_details' action=''>
<input type='text' class='form-control' name='box1' required>
<input type='text' class='form-control' name='box2' required>
<input type='submit' value='Save' >
</form>
<form name='frm_details' id='frm_details' action=''>
<input type='text' class='form-control' name='box1_2465' required>
<input type='text' class='form-control' name='box2_2465' required>
<input type='submit' value='Save' >
</form>
<script>
$(function() {
$('#frm_details').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if(data.status == '1')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
}
});
});
});
</script>
this works flawlessly for the creation of a new customer however when i submit the second form to edit the customer with the id in the name tag it fails to execute the ajax is there any chance someone could point out where i am going wrong if possible i would like to keep a single ajax request just with the form id changed $('#frm_details2465')
1st: id must be unique as I said
2nd: you can change Ids like so
in html
<form name='frm_details' id='frm_details1' action=''>
<form name='frm_details' id='frm_details2' action=''>
in js
$('form[id^=frm_details]')
or you can use classes
<form name='frm_details' class='frm_details' id='frm_details1' action=''>
<form name='frm_details' class='frm_details' id='frm_details2' action=''>
and in js
$('form.frm_details')

jQuery Ajax post to php not printing response

I am using the new way to post data to a php page through ajax without a page refresh but the response is not printing to the console.
Note: I am not yet collecting form data to send until I can actually get the ajax to work.
HTML:
<form id="myForm" action="process.php" method="post">
<input type="text" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span><br />
<input type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span><br />
<input type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span><br />
<input type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span><br />
<input type="submit" value="Submit">
</form>
jQuery:
$('#myForm').on('submit', function(e){e.preventDefault()});
var request = $.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
});
request.done(function(response){
console.log(response);
});
request.fail(function(){
console.log('fail');
});
PHP:
<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>
Your on submit function is not doing anything. You need to have the ajax call inside of it.
Try:
jQuery(document).ready(function ($) {
$('#myForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
})
.done(function(response){
console.log(response);
})
.fail(function(){
console.log('fail');
});
});
});
Also I do not know where you are loading the JS. But you might want to wrap it in a document ready function to make sure your form exist when it is called.
Lastly there is a very nice plugin for forms that will make this easier for you. JQuery.Form.
http://malsup.com/jquery/form/

How to submit a form with input image into modal Bootstrap?

I have a modal form using bootstrap. The form contains some text inputs and a image input.
I submit the form with ajax, and all data is received at the PHP file correctly. Alas, the image isn't being uploaded.
What is my code problem?
<script>
$(document).ready(function () {
$("input#submit").click(function(){
$.ajax({
type: "POST",
url: "insert.php",
data: $('form.contact').serialize(),
success: function(msg){
$("#th").html(msg)
$("#form-content").modal('hide');
$("#pro").html(content);
},
error: function(){
alert("failure");
}
});
});
});
</script>
The form:
<form class="contact" name="contact" enctype="multipart/form-data">
<label for="inputNombre" class="sr-only">Título</label>
<input id="inputNombre" name="inputNombre" class="form-control" placeholder="Título" required="TRUE" autofocus="" type="text">
<br>
....
<div class="upload_pic1 inline">
<input id="imagen" name="imagen" type="file">
</div>
<div class="modal-footer">
Cerrar
<input id="submit" class="btn btn-success" type="submit" value="Crear">
</div>
</div>
</form>
EDIT:
insert.php
<?php
session_start();
if (!isset($_SESSION["name"]) && $_SESSION["name"] == "") {
// user already logged in the site
header("location: Login.html");
}
require_once('funt.php');
conectar('localhost', 'root', '', 'db');
if (isset($_POST['inputNombre'])) {
$nombre = strip_tags($_POST['inputNombre']);
....
//Here the var imagen
if(is_uploaded_file($_FILES['imagen']['tmp_name'])){
$rutaEnServidor='imagenes';
$rutaTemporal=$_FILES['imagen']['tmp_name'];
$nombreImagen=$_FILES['imagen']['name'];
$rutaDestino=$rutaEnServidor.'/'.$nombreImagen;
move_uploaded_file($rutaTemporal,$rutaDestino);
} else { //Always enter here, so is not uploaded
$rutaEnServidor='imagenes';
$rutaTemporal='/noPicture.png';
$rutaDestino=$rutaEnServidor.'/noPicture.png';
move_uploaded_file($rutaTemporal,$rutaDestino);
}
...
How can I change this and upload the picture with all data in form?
You can use FormData interface. Then you have to tell jQuery not to set content type, nor process data.
Check compatibility table for the FormData constructor first. It might suffice.
Otherwise read through this discussion, How can I upload files asynchronously?.

Contact form using e.preventDefault(); not working live

UPDATE - the contact form is found at this URL.
I am trying to get the following contact form to function, using this tutorial.
I manage to get everything to work as expected on my computer using apache webserver.
After uploading the files to an online website, the ajax function does not kick in.
I seems like the e.preventDefault(); stops working after the upload, and the form is redirected to a new site,and not just being processed on the site without the reload.
I have also been trying to use the return false; instead of e.preventDefault(); without any success.
Her is my code:
.html
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
.js
$(function(){
$('form').submit(function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading").fadeOut(function(){
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
})
Please help!
That's because your JS is missing a closing });. Please check this demo to confirm that the default action is indeed prevented and the ajax does kick in. However, I was expecting a POST but instead I am seeing an OPTIONS request.
NOTE: Giving an element a name or id attribute value of submit is bad practice. You cannot for example use JavaScript to submit the form via default form submission -- this.submit() or $('form')[0].submit() without getting the error ...submit() is not a function .....
$(function() {
$('form').submit(function(e) {
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$("#loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$("#loading").fadeOut(function() {
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
});
}); // <==== MISSING THIS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
Since you are submitting via AJAX anyway, you may find it easier to change your input type to button, and bind to click instead of form submit, to avoid the default submit behaviour you are trying to circumvent.

Categories