jQuery-Ajax : insert data from php - javascript

I have this code:
for my view:
<b><input type="text" id="pagibigno" onclick="window.location.assign('#')"/></b>
<div id="pagibig_form">
<div class="err" id="add_err"></div>
<form>
<label>Pagibig Number:</label>
<input type="text" id="signpagibigno" name="signpagibigno" value="signpagibigno" />
<input type="text" id="txtpagibigno" name="txtpagibigno" />
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
addField.php
<?php
include 'dbconn.php';
$signpagibigno = $_GET['signpagibigno'];
$txtpagibigno = $_GET['txtpagibigno'];
echo "INSERT INTO `employer_profile` (`id`, `pagibig_no`, `buss_name`, `sss_no`, `div_code`, `address`, `zip_code`, `tin`, `contact_no`)
VALUES (NULL, '$txtpagibigno', NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
$sql = $conn->prepare("INSERT INTO `employer_profile` (`id`, `pagibig_no`, `buss_name`, `sss_no`, `div_code`, `address`, `zip_code`, `tin`, `contact_no`)
VALUES (NULL, '$txtpagibigno', NULL, NULL, NULL, NULL, NULL, NULL, NULL)");
// mysql_query($sql);
$sql->execute();
?>
popup.js
$(document).ready(function ()
{
$("#pagibigno").click(function ()
{
$("#shadow").fadeIn("normal");
$("#pagibig_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function ()
{
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function ()
{
pagibigno = $("#txtpagibigno").val();
$.ajax(
{
type: "GET",
url: "addField.php",
data: data,
success: function (html)
{
if (pagibigno != '')
{
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
}
else
{
$("#add_err").html("Please complete the field");
}
},
beforeSend: function ()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
when I run the dataField.php the data save to my database. but when I use the view, where the ajax takes place the data did not save.
I read this link for this codes Alert in Jquery pagination
Please help. thanks

You are not passing the data to the php page. See the jquery code below :
$(document).ready(function () {
$("#pagibigno").click(function () {
$("#shadow").fadeIn("normal");
$("#pagibig_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function () {
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function () {
txtpagibigno = $("#txtpagibigno").val();//Getting value from text field
signpagibigno = $("#signpagibigno").val();//Getting value from text field
$.ajax({
type: "GET",
url: "addField.php",
data: "txtpagibigno="+txtpagibigno+"&signpagibigno="+signpagibigno,//Passing the values to the php page
success: function (html) {
if (pagibigno != '') {
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
} else {
$("#add_err").html("Please complete the field");
}
},
beforeSend: function () {
$("#add_err").html("Loading...")
}
});
return false;
});
});

Related

Ajax script not function

I have a request with ajax that still loads the php script instead of performing its function without refreshing. Am guessing there is an issue with my ajax Below is anything wrong with the ajax script
HTML
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' value='$ad_id'>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>
Ajax request
$('#connect_form').submit(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
PHP SCRIPT
require_once("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect'])) {
$my_id = $_SESSION['log_id'];
$ad_id = $_POST['conn_id'];
$rand_num = rand();
$hsql = <<<EOF
SELECT COUNT(hash) as count FROM connect WHERE(user_one = '$my_id'
AND user_two = '$ad_id') OR(user_one = '$ad_id'
AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1) {
$response = "Your are already connected to '$ad_id'";
} else {
$csql = <<<EOF
INSERT INTO connect(user_one, user_two, hash) VALUES('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db - > exec($csql);
if (!$cret) {
echo "Error connecting to '$ad_id'";
} else {
echo "Successful";
}
}
}
The form executes but not without refreshing the page. Please what is the issue with the ajax?
I recommend you to send form data serialized, using serialize() method.
Also, use submit event for form: $('form').on('submit', function (e) {}
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: $('form').serialize()
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
$('#connect').click(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
console.log(ad_id);
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
})
.done(function (response) {
console.log(response);
})
.fail(function (data) {
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' />
<input onclick="return;" type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>

Ajax does not return any result

My Ajax function does not return any result
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form >
</div>
</div>
$(document).ready(function(){
$("#ok").click(function() {
var login = $("#login").val();
var password = $("#password").val();
var dataString = 'login='+ login + '&password=' + password;
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userId= $row["id"];
$today=time();
$week=strftime('%W',$today) ;
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
}
The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. It's better practice to hook to the submit event of the form.
Also note that your PHP code will never return 0, it would be better to have a error handler should the AJAX not complete as expected. Finally, your current code is wide open to attack; you should look in to using SSL and using prepared statements to avoid SQL injection.
That said, here's a fix for your AJAX issues:
<div id="container">
<div id="connexion">
<form id="myform" method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form>
</div>
</div>
$("#myform").submit(function(e) {
e.preventDefault(); // stop standard form submission
$.ajax({
type: "POST",
url: 'login.php',
data: {
login: $("#login").val(),
password: $("#password").val()
},
dataType: "json",
success: function(data) {
$('#errormess').html(data);
}
error: function() {
$('#errormess').html("problem");
}
});
});
I think you are giving the data parameter wrongly. It should be like
var dataString = {"login": login,
"password": password}
HTML
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password">
<br />
<input name="Submit" type="button" id="ok" value="OK" class="btn ">;
<br /> <br />
<span id="errormess"></span>
</form >
</div>
</div>
JS
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var login = $("#login").val();
var password = $("#password").val();
var dataString = {"login": login,
"password": password}
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
Also change the input type from submit to button and have and e.preventDefault() in your JS.
javascript code :
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var data = (this.form).serialize(); // added code
$.ajax({
url: 'login.php',
data: data,
dataType:'json',
type:'POST',
async:false,
success: function(data) {
if (data.success == 0) { // added code
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
},
error: function(data) { // if error occured
}
});
});//ok
});//document
php code :
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND
password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userId = $row["id"];
$today = time();
$week = strftime('%W', $today);
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
} else { // added code
$arr = array("success" => '0');
echo json_encode($arr);
}
Please do check. I have modified the response from PHP as well as jquery code.

send text value for ajax popup

here is my javascript
<script>
jQuery(function ($) {
$('.button').on('click', function () {
var id = $(this).data('id');
$.ajax({
url: '/ajax.php',
data: {
id: id
},
method: 'POST',
success: function (html) {
$('body').append(html);
$(html).bPopup();
},
error: function (returnValue) {}
});
});
});
</script>
Here is my html
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty">
<button type="button" class="button small cart-button" data-id="xxxx">Add to Cart</button>
ajax.php
<?php echo $_POST['id']; ?> // show id : xxxx
I want to send qty value for ajax.php file. so how to do it i want to echo it from php.. plz help me for this... thanks
Please try this
<script>
jQuery(function ($) {
$('.button').on('click', function () {
var id = $(this).data('id');
var qtyValue = $("input[type='text'][name='qty']").val();
$.ajax({
url: '/ajax.php',
data: {
id: id,
quantityValue : qtyValue
},
method: 'POST',
success: function (html) {
$('body').append(html);
$(html).bPopup();
},
error: function (returnValue) {}
});
});
});
</script>

ajax is not calling the function from php page

I'm having a problem with my code...
function retmsg isn't returning a value if javascript is implemented
<div id="pop">
Elunika
<div class="txt">Its the way to connect with your friends.</div>
<form action="login.php" method="post" id="login">
<input id="email" placeholder="E-mail" type="text" name="em" />
<input id="email" placeholder="Password" type="password" name="pwd"/>
<div class="txt1"><input type="checkbox" name="check" />Keep me logged in | Forgot Password ?</div>
<input id="loginButton" type="submit" value="Login" name="log" />
</form>
<span>Register</span>
<div id="error1"></div>
<div id="termdiv1"></div>
</div>
value returned from retmsg() function should display in div id="error"
login script...
if (isset($c))
{
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if($r)
{
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
echo retmsg(1,"profile.php");
}
else
{
$_SESSION["Authenticated"] = 0;
die (retmsg(0,"Incorrect Information"));
}
}
function retmsg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
javascript code...
$(document).ready(function(){
$('#login').submit(function(e) {
att();
e.preventDefault();
});
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
error(0);
$.ajax({
type: "POST",
url: "submit.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) {
$('#error').html(txt);
$('#regpop').css('height','419px');
$('#termdiv').css('margin-top','10px');
}
if(!txt) {
$('#regpop').css('height','400px');
$('#termdiv').css('margin-top','-20px');
}
}
function att()
{
hideshow1('loading',1);
error1(0);
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(retmsg){
if(parseInt(retmsg.status)==1)
{
window.location=retmsg.txt;
}
else if(parseInt(retmsg.status)==0)
{
error1(1,retmsg.txt);
}
hideshow1('loading',0);
}
});
}
function hideshow1(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error1(act,txt)
{
hideshow1('error1',act);
if(txt) {
$('#error1').html(txt);
$('#pop').css('height','290px');
$('#termdiv1').css('margin-top','50px');
}
if(!txt) {
$('#pop').css('height','270px');
$('#termdiv1').css('margin-top','-35px');
}
}
in javascript code
retmsg should return txt parameter to the att function.....
att function is passing retmsg.txt value to the error1 function
part of the function error1 is working as retmsg.txt is not returning value...
rest of the javascript code is working fine...
rest of the code is same as of this...
only function names are different....
ANSWER *ANSWER* ANSWER
javascript code was all correct
made changes in the login script
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if(!$r)
{
$_SESSION["Authenticated"] = 0;
die (retmsg(0,"Incorrect Information"));
}
else
{
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
echo retmsg(1,"profile.php");
}
function retmsg($status,$txt)
{
return json_encode(array('status' => $status, 'txt' => $txt));
}

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Categories

Resources