Update status into input field - javascript

Type a random email address into my form and notice the ajax updates at the top - http://goo.gl/DwvdY
How do I put those updates directly in the input box where you typed your email address? This is driving me crazy
There is an empty div named #response that first gets filled with this JS text update:
$('response').innerHTML = 'Adding email address...';
Then that same div gets the status returned to it and a newer update is echoed with PHP.
<span id="response">
<? require_once('inc/store.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>

it should be:
$('#response').html('Adding email address...');
To store it the the textbox directly do this:
$('#email').val('Adding email address...');
This should do it:
$('#signup').submit(function() {
// update user interface
//store the value first to another variable before setting a new one
var email = $("#email").val();
$('#email').val('Adding email address...');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape(email),
success: function(msg) {
$('#email').val(msg);
}
});
return false;
});

Related

Dynamically post post_id and user auth id for comment like system where comment form display as popup to comment each post

I am creating a comment system where user can comment each post, when user click comment button popup box will appear with multiple field, form is posted to db from jquery, i have a problem that i can't store post_id and user auth id to db through jquery formData method
#foreach($customerposts as $customerpost)
<button type="button" class="btn btn-info" data-toggle="modal" data-
target="#maskup-{{$customerpost->id}}" style="float:right; margin-
top:50px;" id="bidnow" value="{{$customerpost->id}}">Comment
Now</button>
#include('forms.commentform')
#endforeach
comment form
created form field
display correct post id and user id here
passed through hidden field also it doesn't work
</form>
>jquery
$( 'form' ).submit(function ( e ) {
var data;
data = new FormData();
data.append('message', $("#message").val());
data.append('hidden', $("#hidden").val()); can't get this value from
controller
// console.log(data);
alert(data);
$.ajax({
url: 'api/comment/',
data: data,
processData: false,
contentType: false,
type: 'POST',
});
i want to post post_id and user id dynamically for each post
my controller
public function Bidpost(Request $request)
{
$validator = \Validator::make($request->all(), [`enter code here`
'message'=>'required'
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
$bidon = new ContributerBidOn();
$bidon->user_id = '5'; //can;t het user id from hidden field
$bidon->post_id = '8';
$bidon->Guarantee_Of_Product = $request['message'];
$bidon->save();
return response()->json(['success'=>'Data is successfully added']);
}
}
Route api
Route::post('/bidon/','BidController#Bidpost');
It is a bit difficult to understand what you wanted to do here. But I guess you are unable to send post id and authenticated user id in ajax.
My suggestion will be while you click for the comment you can get the post id from the button as you have the id present in button value="{{$customerpost->id}}" value by
add btnForComments class to your button inside for loop and remove the id attribute
$(".btnForComments").click( function() {
var postId = $(this).val();
});
Remove id bidnow from the button in your for a loop. As id should be unique inside DOM.
For authenticated user-id you do not have to send it or keep it hidden inputs in ajax as you can get it from Session in your Controller directly.
Else you can assign the id to a javascript variable and pass it in ajax. The authenticated use id will be the same for all comments though.

Codeigniter: Validate data before going to controller

I m validating a data by clicking the submit button and then again loading the views. I want just to show the errors on the page before loading the controller. Its is not a form validation. it is just a data validiation.
I think you can do the validation using AJAX.
in view page
<script type="text/javascript">
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function(){
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.test(email_val)){
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/user/email_check", {
email: email_val
}, function(response){
$('#loading').hide();
$('#message').html('').html(response.message).show().delay(4000).fadeOut();
});
return false;
}
});
});
</script>
in controller function
public function email_check()
{
// allow only Ajax request
if($this->input->is_ajax_request()) {
// grab the email value from the post variable.
$email = $this->input->post('email');
// check in database - table name : tbl_users , Field name in the table : email
if(!$this->form_validation->is_unique($email, 'tbl_users.email')) {
// set the json object as output
$this->output->set_content_type('application/json')->set_output(json_encode(array('message' => 'The email is already taken, choose another one')));
}
}
}

Send form data via email on submit

I have a form that submits data to parse.com using the code below:
<script>
function validateForm() {
Parse.initialize("xxxx", "xxxxxx");
var TestObject = Parse.Object.extend("Event");
var testObject = new TestObject();
testObject.save({
Name: document.forms["myForm"]["fname"].value,
Date: document.forms["myForm"]["date"].value,
success: function(object) {
$(".success").show();
},
error: function(model, error) {
$(".error").show();
}
});
}
</script>
however I was wondering if there was a way that I could simultaneously send an email with the contents of the form. Is this possible?
You would need some type of server side script to send email.
If you use PHP, you could use the mail function.
In the JavaScript, you would just send an AJAX request to the server-side file containing the code that sends the email.
Yes you can, use AJAX to send it. Here's an example code:
JavaScript
var name = "Test";
var last_name = "Last Test";
$.ajax({
type:"POST",
url:"your_php_file.php",
data:{
name : name,
lastname : last_name
},
success:function(data){
// TODO when success
}
});
And your PHP file would look like:
$name = $_POST['name'];
$lastName = $_POST['lastname'];
Note i've used different last name's on purpose.
EDIT: Forgot to mention, once in PHP you can send email either by using mail, PHPMailer or whatever you wish

Passing session variable through AJAX to PHP file

My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;

Cake PHP database check

I was trying to figure out how to check if the value entered in text box is existing in
database or no as soon as it is entered or on tab event using cakePHP and javascripts. I am new so please can someone help?
Thanks,
Create a validation for Unique on the field. It will check the value of the field before it saves it. If it exists, it will tell the user that the value already exists.
assumptions:
table: posts
model:Post
controller:Posts
and the field about which you need notification of pre-existence is post_title
Now do something like this
In view:
let id of text field for post_title is PostPostTitle
$('#PostPostTitle').bind({
blur:function(){
var newTitle = $(this).val();
if(newTitle){
$.ajax({
url:'Posts/checkTitle/',
type:'POST',
data:{title:newValue},
dataType:'JSON',
success:function(data){
if(data.ok==1){
//dont show any error and let the user submit
}else {
//show error notification in desired format
}
}
})
}
}
});
Now in your controller make an action with name checkTitle
controller code will be like this
public function checkTitle(){
//fetch the vlaue of title from appropriate key of the controller class
//variable $this->params (in cake v<2) or from $this->reuest (cake v2.x+)
$this->layout = 'ajax';//or json or null what ever you prefer
$this->autoRender = false;
//assumig that you have fetched value of newTitle in $newTitle from requestVar
//make a database query to post table
$response = array('ok'=>0);
$data = $this->Post->find('count',array('conditions'=>array('post_title'=>$newTitle)));
if($data==0) {
$response['ok']=1;
}
echo json_encode($response);
exit;
}

Categories