I am trying to hide the submit button if the email is the same with the one in the database from action.php. How could I implement this in my following code:
<form onsubmit="return submitdata();">
<input type="text" id="mail">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('mail').value;
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
console.log(data);
$('#msg').html(data);
}
});
return false;
}
</script>
action.php:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "Response: ".$email;
$hide = 1;
}else{
echo 'hmmmm';
}
?>
When the email coincide I get the correct message, but how could I call back $hide to determine to hide my submit button?
Instead of returning a message, return an indication.
(In the JS script write the message accordingly)
A detailed json string would be a good idea but for simplification see the following.
PHP:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "already_exists";
}else{
echo 'not_exists';
}
?>
JS:
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
if(data == 'already_exists'){
$('#buttonId').hide();
} else if(data == 'not_exists'){
$('#msg').html('Response: ' +name);
}
}
});
Related
I have an image with the Coupon code in Front End/Homepage of my website but when I try to click that nothing happens and click is not working.
The Html is below
<a class="coupon_click text-no-decoration" href="javascript:void(0);" id="coupon_id_<?php echo $couponBanner->getId(); ?>">
jQuery code is below
jQuery(document).ready(function () {
jQuery('.coupon_click').click(function () {
console.log('here');
jQuery.ajax({
type: 'POST',
url: '<?php echo url_for('#blog_couponClicked') ?>',
data: {videoId: <?php echo $video_id ?>, couponId: <?php echo $couponBanner->getId(); ?>},
success: function (res) {
if (res) {
window.location.href = res;
}
}
});
});
});
Hi my advise don't mess the JQuery Code and PHP and make it clean as much as possible,
<a class="coupon_click text-no-decoration" href="javascript:void(0);" c-id="coupon_id_<?php echo $couponBanner->getId(); ?>" v-id="<?php echo $video_id ?>">Click</>
jQuery(document).ready(function() {
jQuery('.coupon_click').on('click', function () {
console.log('here');
var cid= jQuery(this).attr('c-id');
var vid= jQuery(this).attr('v-id');
dataCall(vid,cid);
})
function dataCall(vId, cId){
jQuery.ajax({
type: 'POST',
url: 'your_url',
data: {videoId: vId,couponId:cId},
success: function (res) {
//do whatever you want to do
},error:function(err){
console.log(err);
}
})
}
})
hope it's what u want
<a id="coupon" class="" href="javascript:void(0);" id="coupon_id">coupon</a>
$("document").ready(function()
{
$("#coupon").click(function ()
{
sendS();
});
});
function sendS()
{
var couponID="abc123";//anythg u like
var userID="hahaha#mail.com";
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{cID:couponID,uID:userID},
success: function(data)
{
alert(data)
},
error: function ()
{
alert("Error!");
}
});
}
I am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});
I tried to receive Ajax response but the response is null.
My HTML Looks like this
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<select class="form-control" class="form-control" id="choose_country">
<option value="">Select a prefered language</option>
<option value="en">EN</option>
<option value="fr">FR</option>
<option value="de">DE</option>
<option value="nl">NL</option>
</select>
</form>
<div id="table_load"></div> <!-- loads search table -->
My Javascript looks like this
<script>
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
$("#choose_country").change(function(){
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {choose_country: choose_country},
dataType: 'json',
async: false,
success: function (response) {
if(response.success == true){
alert('success');
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
}else{
alert('fail');
}
},
});
});
</script>
My controller looks like this
public function search(){
$choose_language = $this->input->post('choose_country');
$this->load->view('admin/manage_article/search');
}
}
I want to pass the value of select box to the controller and return back the selected value in the page $this->load->view('admin/manage_article/search');
I have tried the above code but the response alerts "fail".
I am new to ajax so pardon me if there are any mistakes in coding.
Try this, in your controller
public function search() {
$choose_language = $this->input->post('choose_country');
$result = ($choose_language) ? true : false;
$this->output->set_content_type('application/json')->set_output(json_encode(array('choose_country' => $choose_language, 'result' => $result)));
}
your jquery will be as below
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {
choose_country: choose_country
},
dataType: 'json',
async: false,
success: function(response) {
if (response.result) {
alert('success');
$('#table_load').html(response.choose_country);
} else {
alert('fail');
}
},
});
});
});
</script>
I dont know why you are using the ajax, you might have business logic in controller, which you have not shown. If not then you can simply load the value of choose_country in table_load, as below.
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$('#table_load').text(choose_country);
});
});
</script>
There is no reason to make two calls to the server - once for the ajax call and then again to load html.
To return and load html into the browser via AJAX do this in your javascript.
$("#choose_country").change(function () {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url('admin/manage_article/search'); ?>",
type: "post",
data: {choose_country: choose_country},
dataType: 'html',
// Forcing synchronous strongly discouraged,
// as it can cause the browser to become unresponsive.
//async: false,
success: function (response) {
$('#table_load').html(response);
},
error: function(xhr, textStatus, errorThrown){
console.log(textStatus, errorThrown);
}
});
});
Your controller will work the way you show it in the question except I don't see where the posted var is used, so you may not receive the language specific html what you want (If that is what you're trying to do).
If you really feel the need to have the return contain a property called result that you can check using if (response.result) {... then you will need a variation on parth's answer to your question. You can add the html to the returned json with this in your controller.
public function search()
{
//What do you do with this?
//You don't show how this is used so I'm mostly going to ignore it.
$choose_language = $this->input->post('choose_country');
$result = !empty($choose_language) ? true : false;
///get the view file as a string of html markup
$html = $this->load->view('admin/manage_article/search', NULL, TRUE);
$out = array('result' => $result, 'html' => $html);
$this->output
->set_content_type('application/json')
->set_status_header('200')
->set_output(json_encode($out));
}
Then your success function would be like this
success: function(response) {
if (response.result === true) {
alert('success');
$('#table_load').html(response.html);
} else {
alert('fail');
I have very very little knowledge of javascript but somehow I managed to post form data to a php file.
Now I am facing a little problem, there are some validations on php file, what I want is if there is any validation fails and the php file returns $error = 'Invalid data'; I want this ajax request to simply display the error message.
Or, if it returns no error, or $error = ''; this ajax request redirect to thankyou.php page.
HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if (data == 'true') {
window.location.href="thankyou.php";
};
if (data !== 'true') {
$("#status").html(data);
};
},
error: function(){
}
});
}));
});
<form id="frmContact" action="" method="post">
<div id="status"></div>
<div>
<label>Email</label>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="demoInputBox">
</div>
<div>
<input type="submit" value="Send" class="btnAction" />
</div>
</form>
data.php
<?php
// PHP code above...
//Lets add $error variable for test purpose...
$error = 'Invalid data';
?>
Change only success function like this
success: function(data){
if (data === 'Invalid data') {
$("#status").html(data);
}
else {
window.location.href="thankyou.php";
}
}
and in php you should echo $error
Echo out "Success" if everything goes according to what you wanted in the posted data i.e all validations passed or echo out any specific validation error. The echoed response will be the response according to which our JS will act accordingly.
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false
})
.done(function(response){
if(response=="Success")
window.location.href="thankyou.php";
else
$("#status").html(response);
});
}));
});
I am new with jquery and ajax, so please be patient.
I have this link:
<a href="#message" style="text-decoration:none" class="common2 simple3" >Message</a>
that shows this pop up when clicked:
<div id="message" class="modalDialog">
<div>
<h3>Create A Message</h3>
<form id="msgForm" name="msgForm" action="#" method="post">
<textarea id = 'msgContent' cols="48" rows="10" ></textarea>
<br>
<div id="create_btn">
<a href='' id = 'send' class="common simple2" style='margin-left:50px;text-decoration: none;'>Send</a>
</div>
<div id="cancel_btn">
<a href="#close" class="common simple2" style='margin-left:40px;text-decoration: none;'>cancel</a>
</div>
</form>
</div>
</div>
when I entered text in the textarea and show its content by alert(msgContent) in the script below, it shows
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'message.php?message='+ msgContent,
type: 'GET',
dataType: 'json',
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
but when I try to pass it to a php page through ajax, it won't pass. What could be wrong?
this is message.php
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,$message)";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
You need to read the value from $_GET:
$message = $_GET['message'];
Or use the post method, with data attribute:
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'subscribe.php',
type: 'POST',
data: {message: msgContent},
//dataType: 'json', from your php I don't that that you are looking for json response...
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
Your JS should be this:
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
var msgContent = $("#msgContent").val();
$.ajax({
url: 'message.php',
type: 'POST',
dataType: 'json',
data: {message: msgContent},
context: this,
success: function(result) {
alert('Message has been sent');
}
});
});
});
And your PHP this:
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,'$message')";
if (!mysqli_query($connection,$sql)) {
die('Error: ' . mysqli_error($connection));
}