Sending HTML form via AJAX to PHP server - javascript

I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>

Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.

You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

Related

How to get php page to receive ajax post from html page

I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.

Use Javascript (jQuery) to display result of request in ASP.NET MVC

I have an ASP.NET MVC project and currently I am using ViewData["ResultMessage"] to show the result of a form (which is done after the user submits & refreshes the page).
I want to do it right after he clicks submit (without refreshing the page). So I have to use Javascript for that, which I am new with. No experience what so ever.
How my form looks like is this:
<form id="contactForm" method="post" action="..">
<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" placeholder="Your email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5" placeholder="Your message" required minlength="20"></textarea>
</div>
<input type="submit" value="Send Message" />
<p>#ViewData["ContactActionResult"]</p>
</form>
You can see the result is displayed with Razor using ViewData. Now I want to do it without refreshing the page and learn JS on the way.
What I have tried so far:
$(function () {
$("button").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "/Receiver",
data: car,
datatype: "html",
success: function (data) {
alert("Congratulations, it worked!");
$('#contactForm').html(data);
},
error: function(data) {
alert("Failed.");
}
});
});
});
But I am not sure if I did something wrong or simply not implementing it right. I have the above function inside <script> here </script> in my HTML page. Nothing happens when I click the submit button on the form.
If it is an ajax call, It is best if you return a JSON response . You can use the Request.IsAjaxRequest() to determine whether the request is normal form request or ajax call.
You should also consider using to the PRG pattern. After successfully saving, you should do a redirect to a GET action where you can render a view, instead of returning to the same view with a viewbag message. If you want to pass some message to the new view/action, use TempData instead of ViewData.
[HttpPost]
public ActionResult Receiver(string name, string Email)
{
// Your existing code to save
if(Request.IsAjaxRequest())
{
return Json(new { status = "success", message = "Created successfully" });
}
// Normal form submit. So let's follow PRG pattern
TempData["ResultMessage"] = "Created successfully";
return RedirectToAction("Index");
}
You can also put a try/catch and return a json like this for error usecase
return Json(new { status = "error", message = "some serious error" });
In Index action/view, you can read TempData["ResultMessage"] and display to user.
Now, for the ajax usecase, in your current view, you can add a div to show the message
<form id="contactForm" method="post" asp-action="Receiver">
<div id="msg"></div>
<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5"
placeholder="Your message" required minlength="20"></textarea>
</div>
<input type="submit" value="Send Message" />
</form>
and now in your ajax call's success callback, check the json response coming back from server and show the message property as needed. If you are putting the script inside the razor view file, make sure you are putting it inside a Scripts section so that it will be evaluated in the proper order (After jQuery is loaded, assuming you load jQuery before calling RenderSection("scripts") inside the layout)
#section Scripts
{
<script>
$(function (){
$("#contactForm").submit(function (e){
e.preventDefault()
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: car,
success: function (data){
if (data.status === "success")
{
$('#msg').html(message);
}
//to do : handle statuss=="error" as needed
},
error: function (data)
{
alert("Failed.");
}
});
});
});
</script>
}
For asp.net core, you can write a IsAjaxRequest method in your base controller and use that. jQuery will add X-Requested-With header with value XMLHttpRequest for your ajax calls.
protected bool IsAjaxRequest()
{
return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}

Best way to upload files using Ajax and before submitting

I have a form with multiple fields but also a file upload. I am able to upload multiple files.
I also know that it is possible to upload files with AJAX.
So I would like to upload my files using ajax while i'm filling in every other field. But how would I link the already uploaded images then? And also prevent the images to be uploaded again?
This is the form:
<form id="form_validation" method="POST" action="{{route('storeexpense')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="description" required>
<label class="form-label">Omschrijving</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="number" class="form-control" name="amount" required>
<label class="form-label">Bedrag</label>
</div>
</div>
<div class="form-group form-float">
#foreach ($types as $type)
#if ($type->id === 1)
<input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" checked />
<label for="rdio{{$type->id}}">{{$type->description}}</label>
#else
<input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" />
<label for="rdio{{$type->id}}">{{$type->description}}</label>
#endif
#endforeach
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="datepicker form-control" name="date" placeholder="Please choose a date..." required>
<!-- <label class="form-label">Datum</label> -->
</div>
</div>
<div class="form-group demo-tagsinput-area">
<div class="form-line">
<input type="text" class="form-control" id="tagsinput" data-role="tagsinput" placeholder="Labels" name="tags" required>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
#if (count($errors) > 0)
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<input type="file" name="attachments[]" multiple class="custom-file-control"/>
</div>
</div>
<button class="btn btn-primary waves-effect" type="submit">SAVE</button>
</form>
This is the PHP code that saves the information from the form:
public function store(UploadRequest $request)
{
// Save new transaction in database
$transaction = new Transaction;
$transaction->description = $request->description;
$transaction->amount = $request->amount;
$input = $request->date;
$format = 'd/m/Y';
$date = Carbon::createFromFormat($format, $input);
$transaction->date = $date;
$transaction->transactiontype_id = $request->transactiontype;
$transaction->user_id = Auth::id();
$transaction->save();
// Put tags in array
$inputtags = explode(",", $request->tags);
// Loop through every tag exists
// EXISTS: get ID
// NOT EXISTS: Create and get ID
foreach ($inputtags as $inputtag)
{
$tag = Tag::firstOrCreate(['description' => $inputtag]);
$transaction->tags()->attach($tag->id); //Put the 2 ID's in intermediate table ('tag_transaction')
}
//Check if there are files
if (!is_null($request->attachments))
{
//Loop through every file and upload it
foreach ($request->attachments as $attachment) {
$filename = $attachment->store('attachments');
// Store the filename in the database with link to the transaction
Attachment::create([
'transaction_id' => $transaction->id,
'path' => $filename
]);
}
}
Thanks,
Bart
It sounds like you want to make a fancy form that starts uploading the file as soon as you choose it and meanwhile the user can continue filling the rest of the form. If so, I'd do it like this:
Implement your main text/data form, eg.
<form method="POST" action="/save-data-endpoint.php">
<input name="email" type="text" />
<button type="submit>Submit</button>
</form>
Next to it, a form for the images. eg.
<form method="POST" class="file-upload-form" action="/save-file.php">
<input name="my-file" type="file" />
<!-- note that we wont show a submit button -->
</form>
For the user, it all looks like the same form but clicking the submit button will send only the data to the save-data-endpoint.php. Now we need some js to control this madness (I'll use jQuery for brevity). But you can use FileReader api in js, ajax progress tracking to make it even fancier. See https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications for more.
$(function(){ // run when document is ready
// listen when the input changes (when a file is selected)
$('.file-upload-form').on('change', function(e){
// file has been selected, submit it via ajax
// show some kind of uploading indication, eg. a spinner
$.ajax({
type:'POST',
url: $(this).attr('action'),
data: new FormData(this),
cache:false,
contentType: false,
processData: false,
success:function(data){
// the save-file.php endpoint returns an id and/or a url to the saved/resized/sanitized image
console.log(data.id, data.url);
// we then inject this id/url, into the main data form
var $hiddenInput = $('<input type="hidden" name="uploads[]" value="'+data.id+'">');
$('.main-form').append($hiddenInput);
// show a thumbnail maybe?
var $thumbnail = $('<img src="'+data.url+'" width="20" height="20" />');
$('.main-form').append($thumbnail);
// hide spinner
// reactivate file upload form to choose another file
$('.file-upload-form').find('input').val('');
},
error: function(){
console.log("error");
}
});
});
});
Your backend will get the images as they are selected, one by one. You then save them and return an id and/or a url to the image to be used in the success handler in js. After adding some images your main form should look something like this:
<form method="POST" action="/save-data-endpoint.php">
<input name="email" type="text" />
<button type="submit>Submit</button>
<input type="hidden" name="uploads[]" value="x">
<img src="...x.jpg" width="20" height="20" />
<input type="hidden" name="uploads[]" value="y">
<img src="...y.jpg" width="20" height="20" />
</form>
Now when the user fills the remaining fields and clicks submit, your server will get all the data along with an array called uploads which contains all the image ids/paths you have already saved. You can now store this data and relate it to the files.
I wont go deeper on the backend side as it can be implemented on any language. In summary the basic flow would be:
send files one at a time to a save file endpoint that returns a file identifier (can be an id, hash, full path to image, etc)
js injects those ids into the main form
the main form is submitted to a save data endpoint that returns a success or error message and stores + relates all the data in your preferred method of storage.
Hope it helps!

How to urlencode angularjs ng-model realtime

Recently I've started a new project and would like to do some angularjs magic. The problem is i'm not skilled enough in angularjs or javascript to know how I could do it. One requirement is that it has to be in realtime without reloading a page.
So let me start with my questions now. I've got a simple input field and a display section that instantly shows everything that I type in. However I want the display part to be modified on the fly.
<div id="form" class="form-wrap" ng-app="" />
<form action="index.php" method="post" id="form" />
<input type="text" name="url" id="url" value="" ng-model="name" />
<input type="submit" name="form_submit" id="form_submit" value="GOTO" />
</form>
https://example.com/index.php?url={{name}}
</div>
I'm already doing a validation in javascript but I dont know if it needs to be done in javascript or somehow in de anguarjs code itself. Just to be sure my javascript validation code:
<script>
$('<div class="loading"><span class="bounce1"></span><span class="bounce2"></span><span class="bounce3"></span></div>').hide().appendTo('.form-wrap');
$('<div class="success"></div>').hide().appendTo('.form-wrap');
$('#form').validate({
rules: {
url: { required: true, url: true }
},
messages: {
url: {
required: 'Address is requ!red',
url: 'Address is not val!d (https://www.nu.nl)'
}
},
errorElement: 'span',
errorPlacement: function(error, element){
error.appendTo(element.parent());
},
});
</script>
As you might guess by now I want the {{name}} value to be urlencoded realtime so that an url like: https://www.google.nl/?q=a b c will be changed to https://www.google.nl/?q=a%20b%20c However, how should I do this?
Thanks in advance!
Hi you can call a function on ng-change to encode name into url format like below.
I have create a function urlFormat which take name value and convert it to url format and push new variable urlname back.
<div id="form" class="form-wrap" ng-app="" />
<form action="index.php" method="post" id="form" />
<input type="text" name="url" id="url" value="" ng-model="name" ng-change="urlFormat(name)" />
<input type="submit" name="form_submit" id="form_submit" value="GOTO" />
</form>
https://example.com/index.php?url={{urlname}}
</div>
And create that function inside your controller like
$scope.urlFormat = function (name) {
$scope.urlname = encodeURI(name)
}

Bootstrap Popup on sending form data to mail

I am working as junior web master maybe that's why I have come with a simple question here. I have designed a single page application for client which has contact form at the end of page, validation is done using bootstrap but to send form data to mail id only method I know is using php with action directing different page. since my website is single page application i would like a popup on successful submission to mail id
Below is the HTML code for the contact form
<form class="form-inline" data-toggle="validator" role="form" method="post" id="enquiry" action="index.php">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Name</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail3" placeholder="Name" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Mobile Number</label>
<input type="text" class="form-control" id="exampleInputPassword3" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Email Id</label>
<input type="email" class="form-control col-lg-12" id="exampleInputPassword3" name="email" placeholder="Email Id" required>
</div>
<br/> <br/>
<div class=" col-lg-12 form-group">
<textarea cols="80" placeholder="Enter query Here" class="form-control" name="query" id="address" data-error ="Please Enter Your Query" required></textarea><br/><br/>
</div>
<button style="background-color:#f15a24; color:#FFF;" name="submit" id="submit" type="submit">Submit</button>
</form>
Can use php to send form data and still get a pop up in same page?
Or do I need to use jquery to send data and pop-up?
It would be great if somebody helps me out with code, thanks in advance
Updated
below(index.php page) i have added the code what you have given,
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.min.js"></script>
<script src="js/jquery.fittext.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/creative.js"></script>
<script src="js/validator.js"></script>
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success"){ alert("Success"); }else{ alert("Failed"); }
//Failure message if ret is false
});
}
});
});
</script>
Add this js to your script
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success")
{
alert("Success");
} else {
alert("Failed");
}
}
});
}
);
});
submit.php contains the code to send and exit it with the success (true) or failure (false) message. That will be caught in ret variable.
Edited
This will be more detailed answer I was looking for, I thought it be would be helpful for somebody so I have answered my own question as an alternative solution, check out the links below.
Show submitted form response on the same page. (No Reload)
http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html

Categories

Resources