I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};
Related
I want to get the value of jquery in php form in popup.
my jquery is
$(document).ready(function(){
$("#submit").click(function() {
var mobileNumber = $("#mobileNumber").val();
if(mobileNumber=="")
{
alert("Please Enter Mobile Number");
}
else
{
$.ajax({
type: "POST",
url: "<?php echo base_url('test'); ?>",
data: {mobileNumber: mobileNumber},
success: function(result){
if(result){
$("#enter-otp").modal('show');
}
}
});
}
return false;
});
});
I want to print var mobileNumber value in enter-otp id popup in same page
so i write
<?php echo $mobileNumber; ?>
but it is not showing
If you want to enter value in enter-otp id popup in same page. You dont want any PHP script you can do it by jquery only. (Although You can write in success of ajax). Suppose you have div tag with id of otp-div inside enter-otp. You can write following code
success: function(result){
if(result){
$("#enter-otp").modal('show');
$("#otp-div").html(mobileNumber);
//OR ifotp-div inout attribute then use `val()`
$("#otp-div").val(mobileNumber);
}
}
depending on what gives you back your "result"-variable, you can output data.
so if your "result"-variable gives you back something useful, you can take this data and put it in the html like this.
success: function(result){
if(result){
$("#enter-otp").html(result).modal('show');
}
}
regarding to your edit, this would be a simple solution:
success: function(result){
if(result){
$("#enter-otp").html(mobileNumber).modal('show');
}
}
i picked up your code and run it on localhost. and after few changes, i got it working. to try following:
test.php
<form action="" method="post">
<input id="mobileNumber" type="text" name="mobileNumber" value="" placeholder="">
<input id="submit" type="submit" name="" value="submit">
</form>
<div id="enter-otp" style="display: none; border: 1px solid red;"></div>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var mobileNumber = $("#mobileNumber").val();
if (mobileNumber == "") {
alert("Please Enter Mobile Number");
} else {
$.ajax({
type: "POST",
url: "result.php",
data: { 'mobileNumber': mobileNumber },
success: function(result) {
if(result){
$("#enter-otp").show();
$("#enter-otp").html(result);
} else {
alert("no data received");
}
}
});
}
return false;
});
});
</script>
result.php
<?php
if( isset($_REQUEST['mobileNumber'] )){
echo $mobileNumber = $_REQUEST['mobileNumber'];
} else {
echo "no data";
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('form.ajax-form').onclick('login_submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[user_email]').each(function(index, value) {
// console.log(value);
var obj = $(this),
email = obj.attr('user_email'),
value = obj.val();
data[email] = value;
});
obj.find('[user_pass]').each(function(index, value) {
// console.log(value);
var obj = $(this),
pwd = obj.attr('user_pass'),
value = obj.val();
data[pwd] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
// $("#feedback").html(data);
}
});
// console.log('Trigger');
return false; //disable refresh
});
});
</script>
<?php echo form_open('welcome/login', array('class' => 'ajax-form','style'=>'z-index: 202')); ?>
<input name="user_email" type="email" class="login_email" placeholder="Email address" required autofocus>
<br />
<input name="user_pass" type="password" class="login_pass" placeholder="Password" required>
<label class="checkbox">
Forgot login details?
<button class="btn btn-lg btn-info" id="login_submit" style="margin-left:20px;">Sign in</button>
</label>
</form>
<?php if(isset($login_error) && $login_error !=='') { ?><div class="alert alert-danger login_err"><?php echo $login_error; ?></div> <?php } ?>
<!-- </div>-->
Hi i am trying to pass the email and password to the controller in codeigniter.
Any idea how to do that please help?
You could simplify a big deal by doing:
$('#ajax-form').submit(function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(response) {
console.log(response);
// $("#feedback").html(data);
}
});
return false;
});
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
I want to pass the jquery value "selected" to fetchdata.php without reloading the page.
How can I do this?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.min.js" type="text/javascript">
</script>
<script>
$(document).ready(function() {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass() {
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if (selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" + selected, //The data your sending to some-page.php
success: function()
{
console.log("AJAX request was successfull");
},
error: function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
} else
{
alert("Please at least one of the checkbox");
}
}
</script>
</head>
<body>
<div id="checkboxlist">
<div><input type="checkbox" value="1" class="chk"> Value 1</div>
<div><input type="checkbox" value="2" class="chk"> Value 2</div>
<div><input type="checkbox" value="3" class="chk"> Value 3</div>
<div><input type="checkbox" value="4" class="chk"> Value 4</div>
<div><input type="checkbox" value="5" class="chk"> Value 5</div>
<div>
<input type="button" value="Get Value Using Class" id="buttonClass">
</div>
</html>
fetchdata.php
<?php
foreach($_GET['val'] as $r)
{
print_r($r);
}
?>
I am using the GET method to receive the data and the for-each loop to print the array, but I am not getting any values in the PHP file.
change the ajax function like below and make sure about the fectdata.php in the same folder or give the correct path.
$.ajax({
url: 'fetchdata.php',
type:'GET',
data: {val:selected},
success: function(data) {
console.log("AJAX request was successfull");
}
});
Check if the path to your script is correct:
url: 'fetchdata.php',
Is this script in your doc root?
change the following in your code,
in fetchdata.php
<?php
$valArray = explode('#',$_GET['val']);
foreach($valArray as $val){
echo $val."<br/>";
}
?>
In html File,
$(document).ready(function () {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass(){
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if(selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" +selected.toString(), //The data your sending to some-page.php
success: function(data1) {
$("#resultDiv").html(data1);
console.log("AJAX request was successfull");
},
error:function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
}else
{
alert("Please at least one of the checkbox");
}
}
include the div after a button like
<div id="resultDiv"></div>
Trying to do a simple web app with jquery mobile. I have put together a simple log in form with ajax results to be displayed. Problem is my ajax is not getting a result even when I alert out to see if the URL is valid. Is there something special I need to do using jquery mobile?
Any thoughts/answers much appreciated!
Here is the HTML code:
<div data-role="page" id="login" data-theme="a" data-add-back-btn="true">
<div data-role="header">
<h2>Log in</h2>
</div>
<div data-role="content" data-theme="a" data-add-back-btn="true">
<form action="mobilelogin.php" method="post">
Email: <input type="text" name="email" id="useremail">
Password: <input type="password" name="password" id="userpassword">
<input type="submit" value="Enter">
</form>
<div id="loginresult"></div>
</div>
<div data-role="footer"><h4>Chris Sherwood Design 2012</h4></div>
</div>
Js file:
$(document).ready(function() {
$('form').submit(function() {
var emailchecker = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var email = $("#useremail").val();
var userpassword = $("#userpassword").val();
var checklength = userpassword.length;
if(email == ""){
alert('Please fill in email field');
return false;
}else if(userpassword == ""){
alert('Please fill in password field');
return false;
}else if((!emailchecker.test(email))){
alert('Please use a valid email');
return false;
}else if(checklength < 6 || checklength > 6){
alert('Password must be six characters');
return false;
}else{
var datastring = $(this).serialize();
alert(datastring);
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
}
});
PHP
<?php
echo 'nothing special here...';
?>
From your code:
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
You are returning false before the ajax request.
EDIT (assumed it was a simple mistake, have added more explanation)
You will need to either move that return false; to below the ajax() call, or use the event object like so:
$('form').submit(function(e) {
e.preventDefault();
The problem with just using return false; is that if there is an error in something before it it will not stop the default action. So if your ajax request errors it will miss the return false; and start loading the action page.