I have a form that is posting data to a php api file. I got the api working and it creates an account but want to use AJAX to send the data so I can make the UX better. Here is what the PHP sending script is expecting:
<form id="modal-signup" action="/crowdhub_api_v2/api_user_create.php" method="post">
<div class="modal-half">
<input type="text" placeholder="First Name" name="user_firstname"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Last Name" name="user_lastname"></input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="male" name="user_gender">Male</input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="female" name="user_gender">Female</input>
</div>
<div class="modal-half">
<input type="date" placeholder="DOB" name="user_dateofbirth"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Zip Code" name="user_zip"></input>
</div>
<input class="end" type="email" placeholder="Email" name="user_email"></input>
<input type="password" placeholder="Password" name="user_password"></input>
<input type="submit"></input>
</form>
PHP
$user_firstname = $_REQUEST['user_firstname'];
$user_lastname = $_REQUEST['user_lastname'];
$user_email = $_REQUEST['user_email'];
$user_password = $_REQUEST['user_password'];
$user_zip = $_REQUEST['user_zip'];
$user_dateofbirth = $_REQUEST['user_dateofbirth'];
$user_gender = $_REQUEST['user_gender'];
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
How would I send this via ajax? I found this script that says it worked, but it did not create a user. I imagine its sending the data not the right way.
Ajax
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/api_v2/api_user_create.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
First, let's get ajax in order:
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
//same url as the form
url: '/crowdhub_api_v2/api_user_create.php',
data: $('form').serialize(),
//we need a variable here to see what happened with PHP
success: function (msg) {
//output to the page
$('#output').html(msg);
//or to the console
//console.log('return from ajax: ', msg);
}
});
});
});
Somewhere on the form page, add a div with id output:
<div id="output></div>
Finally, in api_user_create.php, there is an error:
$user_gender = $_REQUEST['user_gender'];
//these last two do not exist on the form
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
I'd recommend some error-checking on the PHP side, like this
if(!empty($_REQUEST)){
//For developing, you may want to just print the incoming data to see what came through
//This data returns into the msg variable of the ajax function
print_r($_POST);
//once that's good, process data
if(isset($_REQUEST['user_gender'])){
$user_gender = $_REQUEST['user_gender'];
}
//etc... as before
} else {
echo 'no data received';
}
Related
I'm parsing some form data into Ajax and looking to fire a block of php code.
So in the code I'm currently alerting out the email address on submit, I want to parse this into the newsletter_signup function and run the php block of code at the very bottom, with the email address from the form going into the php.
How can I do that?
<form action="/event" method="POST" id="signupForm">
<input type="hidden" name="event" value="mc_newsletter_add">
<input type="hidden" name="data[source]" value="newsletter">
<input checked=checked type="checkbox" name="data[newsletter_onetime]" id="newsletter_onetime" class="newsletter-optins">
<input checked=checked type="checkbox" name="data[promos]" id="promos" class="newsletter-optins">
<input class="modal-newsletter-input" id="EmailAddress" name="data[customers_email_address]" placeholder="Enter your email here" required="required" type="email" value="<?php if(isset($_GET['email'])){echo $_GET['email'];}?>" aria-required="true">
<input class="modal-newsletter-signup" id="newslettersignup" name="Submit" type="submit" value="Yes, sign me up" />
</form>
<script>
$("#signupForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var email = $("#EmailAddress").val();
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function(data)
{
console.log(data); //data contain response from your php script
register_signup();
newsletter_signup(email);
form.replaceWith("<br /><p>Thanks for signing up!</p>");
}
});
});
function register_signup(){
ga( 'send', 'event', 'Newsletter Sign Up', 'submit' );
}
function newsletter_signup(email){
$('#signupForm').load(
"newsletter-call.php",
{
'key1': email,
}
);
}
</script>
Then this calls a php called newsletter-call.php with the following in:
<script type="text/javascript">
alert("Hit the page");
</script>
<?php $sib_tracking = new SIB_Tracking();
$email = $_POST['key1'];
$event = "marketing";
$result = $sib_tracking->track_event($email, $event); ?>
You can simply pass the email address through.
newsletter_signup(email);
And then proceed to use it as a parameter.
function newsletter_signup(email) {
console.log(email);
}
As to using it in the PHP, you could use the ajax request to perform the php action before outputting it to the JavaScript function.
I am trying to get my jQuery to work with CSS animations/class changes and working with an ajax post for this logon forum. I am having trouble reworking the JQuery animation script and incorporating the Ajax port for username and password. It does not seem to be posting the login information.
<form class="login" action="" method="post" autocomplete="false">
<div class="group">
<input id="user" type="username" name="user" class="input" placeholder="Username" required autofocus>
</div>
<div class="group">
<input id="password" type="password" name="password" class="input" data-type="password" placeholder="Password" required>
</div>
<div class="group">
<button>
<i class="spinner"></i>
<span class="state">Log in</span>
</button>
</div>
<div class="hr"></div>
</form>
Here is the jQuery
var working = false;
$('.login').on('submit', function(e) {
e.preventDefault();
if (working) return;
working = true;
var $this = $(this),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "login.php",
success: function(data) {
if (data.status == 'success') {
this.addClass('ok');
$state.html('Welcome back!');
setTimeout(function() {
window.location = "/index.php"
}, 4000);
} else if (data.status == 'error') {
setTimeout(function() {
$state.html('Log in');
$this.removeClass('ok loading');
}, 3000);
}
},
});
});
After using Diego's suggestion and piping the out to the console log I was able to determine that the php function was not returning anything. Adding an echo in with corresponding results resolved my issue along with using 'data' in the if statement instead of 'data.status'.
Form:-
<form name="form">
<div class="formfieldContainer">
<label> Email :</label>
<div class="login_wrapper loginContainer">
<span> </span>
<input type="email" id="email" required name="user_email" autofocus="autofocus" placeholder="Enter Email Address"/>
</div>
</div>
<div class="formfieldContainer">
<label> Password :</label>
<input type="password" name="user_password" placeholder="Enter Password"/>
</div>
<input type="button" name= "submit" value="submit" id="submit_login"/>
</form>
AJAX:-
$("#submit_login").click(function(){
var username=$('input[name=user_email]').val();
var password=$('input[name=user_password]').val();
$.ajax({
type: "POST",
url: "newExam.php",
data:{name: username,
pwd: password},
cache: false,
success: function(dataa) {
if(dataa)
{
console.log(dataa);
if(dataa==0)
{ $('form').effect( "shake" ); $('p.error').show(); $("#submit_login").val('Login')
alert('nodata');
}
else if(dataa==1){
window.location.href="user.php";
}
}
}
});// ajax
});
PHP:-
<?php
include('db.php');
$email_php = $_POST['name'];
$pwd_php=$_POST['pwd'];
$sql = "select name from user where email='$email_php' and password='$pwd_php'";
$result = mysqli_query($conn,$sql);
$num_rows= mysqli_num_rows($result);
if($num_rows>0){
$_SESSION['login_user']= $email_php;
echo '1';
}
else{
echo '0';
}
?>
I need the page to redirect to user.php when logged in successfully. But i am getting the following error:
Notice: Undefined index: name in C:\xampp\htdocs\demo\newExam.php on line 3
Notice: Undefined index: pwd in C:\xampp\htdocs\demo\newExam.php on line 4
How to overcome it?
Yo should be redirecting it from php page (using headers)instead of using window.location.href
You can use this method if you don't want to use php.
$.extend( {
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').submit();
} });
Usage
$.redirectPost("user.php", {'key1': 'data1', 'key2': 'data2'});
Credit - https://gist.github.com/aabril/e6b96379ab0eb151a179
Hello im trying to implement an ajax invitation script which will let the user to invite his/her friends to that event. I use the mostly same javascript in the other parts of the website and they work perfect, but in this case, it doesn't work, i'm sure that the problem persists because of the javascript part, because as i said, i use the nearly exact script and it works perfect, when i post the data, it doesn't send the email, my mail function works good ( in other pages i use the same without ajax and it works ) but i think the javascript part can't post the data in this case.
By the way there is not any problem with getting the values in the hidden parts.
Hope you can help.
the javascript part :
<script type=\"text/javascript\">
$(document).ready(function() {
$('.error').hide(); //Hide error messages
$('#MainResult').hide(); //we will hide this right now
$(\"#button\").click(function() { //User clicks on Submit button
var js_name = $(\"#name\").val();
var js_message = $(\"#message\").val();
var js_username = $(\"#username\").val();
var js_useremail = $(\"#useremail\").val();
var js_eventname = $(\"#eventname\").val();
if(js_name==\"\"){
$(\"#nameLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
if( js_message==\"\"){
$(\"#messageLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
var myData = 'postName='+ js_name + '&postMessage=' + js_message + '&username=' + js_username + '&useremail=' + js_useremail + '&eventname=' + js_eventname;
jQuery.ajax({
type: \"POST\",
url: \"invite.php\",
dataType:\"html\",
data:myData,
success:function(response){
$(\"#MainResult\").html('<fieldset class=\"response\">'+response+'</fieldset>');
$(\"#MainResult\").slideDown(\"slow\"); //show Result
$(\"#MainContent\").hide(); //hide form div slowly
},
error:function (xhr, ajaxOptions, thrownError){
$(\"#ErrResults\").html(thrownError);
}
});
return false;
});
$(\"#gobacknow\").live(\"click\", function() {
$(\"#MainResult\").hide(); //show Result
$(\"#MainContent\").slideDown(\"slow\"); //hide form div slowly
//clear all fields to empty state
$(\"#name\").val('');$(\"#message\").val('');
});
$(\"#OpenContact\").live(\"click\", function() {
$(\"#form-wapper\").toggle(\"slow\");
});
});
</script>
the html part:
<div id="form-wapper">
<div id="form-inner">
<div id="ErrResults"><!-- retrive Error Here --></div>
<div id="MainResult"><!-- retrive response Here --></div>
<div id="MainContent">
<fieldset>
<form id="MyContactForm" name="MyContactForm" method="post" action="">
<label for="name" id="nameLb">Email : <span class="error" style="font-size:10px; color:red;">Error.</span></label>
<input type="text" name="name" id="name" />
<label for="message" name="messageLb" id="messageLb">Message : <span class="error" style="font-size:10px; color:red;">Error.</span></label><textarea style="resize:vertical;" name="message" id="message" ></textarea>
<input type="hidden" name="username" id="username" value="<?php echo get_username($userid); ?>">
<input type="hidden" name="useremail" id="useremail" value="<?php echo get_email($userid); ?>">
<input type="hidden" name="eventname" id="eventname" value="<?php echo $eventname; ?>">
<br><button id="button">Send</button>
</form>
</fieldset>
</div>
<div style="clear:both;"></div>
</div>
invite php file :
$postName = filter_var($_POST["postName"], FILTER_SANITIZE_STRING);
$postMessage = filter_var($_POST["postMessage"], FILTER_SANITIZE_STRING);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$useremail = filter_var($_POST["useremail"], FILTER_SANITIZE_STRING);
$eventname= filter_var($_POST["eventname"], FILTER_SANITIZE_STRING);
invite($useremail, $postMessage , $username, $eventname, $postName); // this is a functipon that i use, it works in other cases, but not working in here
Rather than trying to debug that javascript, here is a much much easier / cleaner way to do this for the javascript AJAX post:
$.post('invite.php',$('#MyContactForm').serialize(),function(data){
if(data.success){
// all your on success stuff here
alert('success!');
}else{
// show error messages
alert(data.e);
}
},'json');
For your PHP part, echo a JSON response array, eg:
$data['success']=false;
$data['e']='Some error';
echo json_encode($data);
I've been trying to figure this out, but it seems to be harder than i first thought. However, what I'm trying to do is make an ajax post request, but the POST seems to be empty when I'm sending it.
My HTML File
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm', 'name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
My Javascript
$('#statusUpdateForm').submit(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
My PHP (Some of my medhod in the controller)
// Check if the input is a ajax request
if($this->input->is_ajax_request()) {
echo $_POST['profileUpdate'];
}
Notice, when i put echo "Hello World" etc in the controller, i do get "Hello World" in the alert box from the javascript.
I've also tried a var_dump on $_POST and it returns array(0){} When I'm trying to output the specific $_POST['profileUpdate'] variable i get an error like this,
I've also done a alert from the seralize function i JS, this is what i got,
Is there anyone who know how i can fix this problem?
Try changing method to type.
I'm guessing the script is performing a GET request, which is the default setting when using ajax(), instead of a POST request. Like this:
$.ajax({ // Starter Ajax Call
// "method" isn't an option of $.ajax
// method: "POST",
type: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
Try The following Code
In View add the following form
<?php echo form_open('welcome/CreateStudentsAjax'); ?>
<label for="roll">Student Roll Number</label>
<input type="text" id="txtRoll" value="" name="roll"/>
<label for="Name">Students Name</label>
<input type="text" id="txtName" value="" name="name"/>
<label for="Phone">Phone Number</label>
<input type="text" id="txtPhone" value="" name="phone"/>
<input type="submit" name="submit" value="Insert New Students" />
<?php echo '</form>'; ?>
The JQuery Part is below
$(document).ready(function(){
$('form').submit(function(){
//alert('ok');
$.ajax({
url:this.action,
**type:this.method,**
data:$(this).serialize(),
success:function(data){
var obj = $.parseJSON(data);
if(obj['roll']!=null)
{
$('#message').text("");
$('#message').html(obj['roll']);
$('#message').append(obj['name']);
$('#message').append(obj['phone']);
}
else
{
$('#message').text("");
$('#message').html(obj);
}
},
erro:function(){
alert("Please Try Again");
}
});
return false;
});
});
</script>