userName verification with jQuery - javascript

Username Availability
I want to make an Ajax call that will read data from an input box in html, then call taken.php, which checks if this username is already taken.
My idea is that it will write to GET parameter like this:
taken.php?value=something
Does anybody know how to this with jQuery?
$(document).ready(function(){
$("#userName").change(function () {
var userName = $("#userName").val().trim();
if (userName != "") {
$("#userNameError").show();
$.ajax({
url: 'checkUserName.php',
type: 'get',
data: {key: "userName"},
});
}
});
});
This is what I've done so far.

pass username to checkUserName.php using get request
var userName = $("#userName").val().trim();
$.ajax({
type: "GET",
url: "checkUserName.php",
data: {
key: userName
},
success: function (data) {
alert(data);
}
});
in PHP file you can get like this
<?php
$name = $_GET['key'];
echo $name;
?>

it looks like you have everything but the return there. I personally prefer post but what you have with a boolean return should suffice
$(document).ready(function(){
$("#userName").change(function () {
var userName = $("#userName").val().trim();
if (userName != "") {
$("#userNameError").show();
$.ajax({
url: 'taken.php',
type: 'get',
data: {key: "userName"},
}).done(function(d){
//this is your callback.
//this will return the value echod by taken.php
//with a get of key = username
});
}
});
});
I would prefer a post like:
$.post('taken.php',{
key:$("#userName").val().trim();
},function(d){
// this is your callback
}

Related

Laravel 8 and ajax

Never used ajax before and I'm quite new to Laravel as well.
I'm running a function where it gets the information from the form and i have no idea how to do the request with the information that I need.
function myFunction() {
var x = document.getElementById("frm1");
//console.log(x.elements.personSearch.value);
var details = x.elements.personSearch.value;
document.getElementById("personValidation").innerHTML = "";
if (
!details.match(
/\b[a-zA-Z ]*\\[a-zA-Z ]*\\[0-3][0-9][0-1][0-9][0-9]{4}\b/g
)
) {
document.getElementById("personValidation").innerHTML =
"Your search does not match the required format";
return;
}
$.ajax({
url: "/api/pnc/person",
type: "POST",
dataType: "json",
success:function(amount) {
console.log(amount);
}
});
``` Javascript
public function person(Request $request)
{
$request->validate([
'search' => 'required'
]);
return "test";
}
You need to Follow 3 steps for Ajax Request-
1. Setup Ajax Header bottom of your code. I mean before </html> add below code.
<script>
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
2. If you don't use Header Then you can use.
<script>
$(document).ready(function () {
$("#your_form_id").submit(function(e) {
var details = $('#details_input_id').val();
if(your_condition){
$.ajax({
url: "api/url",
type: "post",
data: {"_token": "{{csrf_token()}}", 'details':details},
success:function(data){
//Your response
if(data){
consol.log("Print what you want to print");
}
}
});
}else{
alert("Your search does not match the required format")
}
});
});
</script>
3. Your Route will be like ajax url
Route::post('api/url', [YourController::class, 'functionName'])->name('functionName');

No data receive in Jquery from php json_encode

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>
Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];
Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>
A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

Serialzing form and posting ajax to function

I am trying to pass the form field values to a php function located into a file. The problem is that I can't understand how to pass that serialized form data to the function from this ajax to a function in php.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
$('#insert_news').serialize(); // how do I add this data here?
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
This ajax passed the values to the file ajax.php right beyond. And from ajax.php is called the function located in functions.php.
ajax.php
if (isset($_POST['action']) && $_POST['action'] == 'insert_news') {
$cp->insert_into_table('newss', array(
'NewsTitle' => $_POST['title'],
'NewsDescrption' => $_POST['description'],
'Date' => date('Y-m-d H:i:s'),
'status' => '1'
)
);
}
function.php
public function insert_into_table($table_name, array $data){
foreach($data as $col=>$value) {
$cols[] = $col;
$values[] = '\''.$value.'\'';
}
$cols = implode(', ', $cols);
$values = implode(', ', $values);
$this->db->query("INSERT INTO $table_name ($cols) VALUES ($values)");
echo "INSERT INTO $table_name ($cols) VALUES ($values)";
}
The issue is serialize() produces a URL encoded key value paired string, so you can't mix that with your data object.
You can use serializeArray() to get an array of objects, representing the form elements, then iterate over them and add them to a data object:
var data = { action: 'insert_news' };
$.each($('#insert_news').serializeArray(), function(){
data[this.name] = this.value;
});
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: data,
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
Side note: your PHP code is vulnerable to SQL Injection. Consider using a Prepared Statement instead of concatenating user input into the SQL.
You can pass serialized data via ajax to a function the way you are doing but your code needs slight modification.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
serializedData: form // use variable to assign data here
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
I think you can use alternate like this
First : add hidden input for action on your form
<input type="hidden" name="action" value="insert_news"/>
Then your ajax post like this
$('#insert_news').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: $(this).serialize(), // $(this) is from <form id="insert_news">
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
And then use print_r on your ajax.php
print_r($_POST);
$('#insert_news').submit(function(event) {
var name = $("#t1").val();
var pass = $("#t2").val(); //add more var as u need
var key = 0;
var formName = new FormData();
formName.append(key++,name)
formName.append(key++,pass) //append the the var to formdata
$.ajax({
url : 'includes/ajax.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formName,
type : 'post',
success : function(data){
$('#message').html(data).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
this works fine for me :-)

What's wrong with this jQuery Ajax/PHP setup?

I'm building a search app which uses Ajax to retrieve results, but I'm having a bit of trouble in how exactly to implement this.
I have the following code in Javascript:
if (typeof tmpVariable == "object"){
// tmpVariable is based on the query, it's an associative array
// ie: tmpVariable["apple"] = "something" or tmpVariable["orange"] = "something else"
var sendVariables = {};
sendVariables = JSON.stringify(tmpVariable);
fetchData(sendVariables);
}
function fetchData(arg) {
$.ajaxSetup ({
cache: false
});
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
});
}
And within script.php:
<?php
$data = json_decode(stripslashes($_GET['data']));
foreach($data as $d){
echo $d;
}
?>
What is it that I'm doing wrong?
Thanks.
Your PHP script is expecting a GET var called 'data'. With your code you're not sending that.
Try this:
if (typeof tmpVariable == "object"){
var data = {data : JSON.stringify(tmpVariable)}; // Added 'data' as object key
fetchData(data);
}
function fetchData(arg) {
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
success: function(response){
alert(response);
$("body").html(response); // Write the response into the HTML body tag
}
});
}

jQUery ajax code alerts an empty string

I send an ajax request when the user fills the email input, here is the code:
_email.blur(function(){
$.ajax({
url : base_path("user/register/ajax/email"),
type: "POST",
data: ({ email : _email.val() , }),
success: function(message)
{
alert(message);
},
});
}); // end of email blur
Then the php returns a string on success, and one on failure (CodeIgniter Controller)
if($param == "email")
{
$this->form_validation->set_rules("email", "required | email");
$this->form_validation->set_rules("email", "is_unique[users.email]");
if($this->form_validation->run !== FALSE)
{
echo (json_encode("thanks"));
}
else
{
echo (json_encode("Ranks"));
}
}
PROBLEM: it seems ajax request is successful, but the message it alerts is not appropriate since it alerts an empty string.
i'd look at this:
json_encode("thanks")
I havent coded any PHP for a long time but shouldnt json_encode be for encoding associative arrays? eg
json_encode(array("message" => "thanks"))
as you are using json_encode you could try this after the if else statement
exit(json_encode($respond));
return $this->output->set_output(json_encode($respond));
where $respond is the message you want to display.
_email.blur(function(){
$.ajax({
url : base_path("user/register/ajax/email"),
type: "POST",
data: ({ email : _email.val() , }),
success: function(message)
{
alert(message);
}
});
});
if($param == "email")
{
$this->form_validation->set_rules("email", "required | email");
$this->form_validation->set_rules("email", "is_unique[users.email]");
if($this->form_validation->run !== FALSE)
{
echo "thanks";
}
else
{
echo "Ranks";
}
exit;
}
For resonse in json you should use data type like:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
php code:
json_encode(array("content" => "thanks"));
js code:
success: function(message)
{
alert(message.content);
}

Categories

Resources