Jquery - fill input if user exist - javascript

I'm trying to fill a form if I find that the name and the firstname input by the user already exist in my database.
For the moment, I would like to check if the name and the firstname already exist in the database but my javascript program doesn't work. It's seems that the part..." "$.post("../modules/verifier_staff.php",{ nom: ..." is not correct.
Then I would like to fill my form with the data that my database give (array).
Can somenone help me to find my mistakes and to tell me how I can use the data i receive from database to fill my form?
$(document).ready(function(){
var form_nom = $("#staff_nom");
var form_prenom = $("#staff_prenom");
$(form_nom).change(function() {
checkvariable();
});
$(form_prenom).change(function() {
checkvariable();
});
function checkvariable(){
if((form_nom.val().length >0)&&(form_prenom.val().length>0)){
prenom_staff = form_prenom.val();
nom_staff = form_nom.val();
//alert(nom_staff);
$.post("../modules/verifier_staff.php",{ nom: nom_staff, prenom: prenom_staff},
function(data){
if(data)
{
alert('ok');
}
else alert('nok');
});
}
}
});

var form_nom = $("#staff_nom");
var form_prenom = $("#staff_prenom");
$(form_nom).change(function() {
checkvariable(form_nom,form_prenom); //pass arguments into the function
});
$(form_prenom).change(function() {
checkvariable(form_nom,form_prenom);
});
function checkvariable(form_nom,form_prenom){ //innclude argument in function definition
//......
}

thank for your help. Yes I'm sure that the path is correct.
Here is my code from ../modules/verifier_staff.php
<?php
include('../inc/settings.php');
include('../inc/includes.php');
//$_POST['nom']='Doe';
//$_POST['prenom']='John';
$nom=$_POST['nom'];
$prenom=$_POST['prenom'];
$Dbcon = new Db;
$personne_manager = new PersonneManager($Dbcon->dbh);
$personne = $personne_manager->get(array('conditions'=> array('nom' => strtolower($nom),'prenom' => strtolower($prenom))));
if($personne)
{
$result = true;
}
else
{
$result = false;
}
return $result;
?>
this part works well (I tested it) so I think the problem come from my javascript code. I'm a newbie in javascript/jquery.

Related

Passing Javascript Input Values to a PHP file to Post to SQlite

I wanted to ask how can i get the values of the Javascript Input and store it into a php value so i can post this data into Sqlite3. Im receiving user inputs from the Javascript Prompts. Is there another way to accomplish this also. Any help would be greatly appreciated.
function myFunc(){
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
if(code==""||code==null||code!="1234"){
//Handle Error
window.location.href="error.html";
}
}
document.onreadystatechange = () => {
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
myFunc();
}
});
}
Using jquery you can use the $.post method:
function myFunc() {
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
var url = "phpToGetInputs.php";
var data = {
code: code,
email: email
}
$.post(url, data); // "send the data to the php file specified in url"
// code...
}
document.onreadystatechange = () => {
// code...
}
Then, in your PHP file (that you specified as the url)
phpToGetInputs.php:
<?php
if(isset($_POST['email'])) {
$email = $_POST['email']; // get the email input (posted in data variable)
$code = $_POST['code']; // get the code input (posted in data variable)
// do code that requires email and code inputs
}
?>
Use a jQuery post request to send the variable from javascript to php.
$.post([url], { "data" : text });
Look at this website for more information: https://api.jquery.com/jquery.post/

Pass coordinates via ajax to php server-side, and retrieve to javascript after they were processed

I want to transfer some coordinates to php (server-side) from javascript (client-side) via Ajax, and after processing (filter, etc) I want to retrieve the result to javascript, for use. The pass to php working, but I don't know how get and use the processed result from php. Any help is highly appreciated.
The php part script is:
$dbconn = pg_connect ("host=localhost port=5432 user=postgres password=xxxxxxx dbname=yyyyyyyy") or die('can not connect!'.pg_last_error());
//The nearest point of Start point
$ss='';
if (isset($_POST['kuldes_st'])){
$kuldes=$_POST['kuldes_st'];
$latk=$_POST['lat_st'];
$lngk=$_POST['lng_st'];
$query = "SELECT ST_X(the_geom), ST_Y(the_geom) FROM tbl_mypoints ORDER BY ST_Distance(the_geom, ST_GeomFromText('POINT($latk $lngk)', 4326)) LIMIT 1";
//$result = pg_query($query) or die('The query failed: ' . pg_last_error());
$result = pg_query($dbconn,$query);
if (!$result) {
die('The query failed: ' . pg_last_error());
}
else {
while ($line =pg_fetch_row($result))
{
$latitude=$line[0];
$longitude =$line[1];
$ss .= "L.latLng(".$latitude.", ".$longitude.")";
}
}
echo json_encode($ss);
}
Javascript code:
map.on('click', function(e) {
var container = L.DomUtil.create('div'),
startBtn = createButton('Start from this location', container),
destBtn = createButton('Go to this location', container);
nearestBtn = createButton('Find and go to nearest parking', container);
//Start
L.DomEvent.on(startBtn, 'click', function() {
control.spliceWaypoints(0, 1, e.latlng);
var lats=e.latlng.lat;
var lngs=e.latlng.lng;
$.ajax({
url : 'index.php',
type : 'POST',
async : true,
data : { 'kuldes_st':1,
'lat_st': lats,
'lng_st': lngs
},
success: function(data,response) {
if (response == 'success') {
alert("Post working fine");
alert(response);
console.log(data);
} else {
alert("Post don't working");
console.log(data);
}
}
});
map.closePopup();
});
I think the main problem is how to use return value.
in index.php file , you can return value without html tags. for example, if you wants to return array of number, just use code like this:
echo implode($array,",");
the data that return by ajax function is some things like this:
1,2,4,2
you can split this string to a javascript array with code like this:
var result = data.split(",");
after it, you can use the array result every where you want in jquery code.
My PHP is a bit rusty but I think the issue is that you are returning a string that is not JSON but trying to pack it up like JSON.
I think you want something more like
$ss = array();
while ($line =pg_fetch_row($result))
{
$latlng = array();
$latlng["lat"] = $line[0];
$latlng["lng"] = $line[1];
array_push($ss,$latlng);
}
echo json_encode($ss)
Forgive my PHP if it's wrong, but hopefullly from this you get the idea. At this point, the thing the server will return should look like real JSON like (
[
{"lat":46.5,"lng":24.5},
{"lat":46.5,"lng":24.5},
...
]
Then in the javascript, you can just deal with it like an array.
var latitudeOfTheFirstEntry = data[0].lat;
var longitudeOfTheSecondEntry = data[1].lng;
Do you know what L.latLng is supposed to be providing. This solution I've outlined is not using that and if that is needed, there maybe more work to figure out where that is supposed to happen.
Hope this helps

Form submited two times (ajax with jquery)

i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});

How to display Colorbox popup in "jQuery ajax() Method" in following scenario?

I'm using PHP, Smarty, jQuery, AJAX, Colorbox - a jQuery lightbox, etc. for my website. There is some old code done using jQuery AJAX method to display the message in popup using standard jQuery library functions. Now I want to replace that typical popup using Colorbox popup. In short Iwant to change the design part only the message part is as it is. I tried to do this but couldn't succeeded yet. Can you help me in doing the necessary changes to the existing old code in order to show the messages in Colorbox popup instead of typical popup? For your reference I'm putting the old code below:
Code from smarty template to give a call to the jQuery AJAX function is as follows:
<span class="submit edit_user_transaction_status" value="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</span>
The code from js file which contains the existing AJAX code is as follows:
$(document).ready(function() {
//This function is use for edit transaction status
$(document).on('click', '.edit_user_transaction_status', function (e) {
e.preventDefault();
$.colorbox.close();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('value');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
Now the code snippet from PHP file which contains the PHP code and success message is as follows:
case "edit_user_transaction":
$transaction_no = $request['txn_no'];
$transaction_status_update = $request['transaction_status_update'];
$transaction_data_assign = $request['transaction_data_assign'];
$user_id = $request['user_id'];
$from_date = $request['from_date'];
$to_date = $request['to_date'];
$page = $request['page'];
if($request['transaction_no']!=''){
$query = "&transaction_no=".$request['transaction_no'];
}
// If public transaction status is entered
if($request['transaction_status']!='') {
$query .= "&transaction_status=".$request['transaction_status'];
}
// For checking transaction no is empty, blank, and numeric
if($transaction_no!='' && !empty($transaction_no)) {
$objUserTransactions = new UserTransactions();
$objUserPackages = new UserPackages();
//if transaction status update to success and transaction data not yet assign
if(empty($transaction_data_assign) && $transaction_data_assign == 0 && $transaction_status_update == "success") {
$user_transactions = $objUserTransactions->GetUserTransactionsDetailsByTransactionNo($transaction_no, $user_id);
$i = 0 ;
$j = 0 ;
//Create array related study and test
foreach($user_transactions['transaction_details'] as $my_cart) {
if(!empty($my_cart['pack_id'])) {
if($my_cart['pack_type'] == 'study') {
$data['study'][$i] = $my_cart['pack_id'];
$i++;
}
if($my_cart['pack_type'] == 'test') {
$data['test'][$j]['pack_id'] = $my_cart['pack_id'];
$data['test'][$j]['pack_expiry_date'] = $my_cart['pack_expiry_date'];
$data['test_pack_ids'][$j] = $my_cart['pack_id'];
$j++;
}
}
}
if(!empty($data['study'])) {
$objUserStudyPackage = new UserStudyPackages();
//Update packages sold count & purchase date in package table
$objUserStudyPackage->UpdateStudyPackagePurchaseData($data['study']);
//For insert packages related data to package_user table
foreach($data['study'] as $study_pack_id) {
$objUserPackages->InsertStudyPackagesToPackageUser($study_pack_id, $user_id);
}
}
if(!empty($data['test'])) {
$objUserTestPackage = new UserTestPackages();
//Update packages sold count & purchase date in test package table
$objUserTestPackage->UpdateTestPackagePurchaseData($data['test_pack_ids']);
//For insert test related data to test_user table
foreach($data['test'] as $test_pack_data) {
$objUserPackages->InsertTestPackagesToTestUser($test_pack_data['pack_id'], $test_pack_data['pack_expiry_date'], $user_id);
}
}
//This function is use for update status inprocess to success and transaction_data_assign flag 1
$user_transactions = $objUserTransactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update, '1');
} else {
// This function is use for update status
$user_transaction_details = $obj_user_transactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update);
}
//Email functionality when status update
include_once("transaction_status_update_email.php");
**$reponse_data['success_massage'] = "Transaction status updated successfully";
$reponse_data['title'] = "Transaction";
$reponse_data['href'] = "view_transactions.php?page=".$page."&from_date=".$from_date."&to_date=".$to_date.$query;
$reponse_data['login_error'] = 'no';
$reponse_data = json_encode($reponse_data);
echo $reponse_data;
die();**
}
break;
The code shown in bold font is the success response message. Can you help me in this regard, please? Thanks in advance.
Yo, you asked for help in PHP chat. Hopefully this helps:
So the dialog portion at the bottom needs to change to support colorbox. Firstly, load all your colorbox stuff. Second, you'll need to create your colorbox content dynamically by either grabbing content from an element on the page or building it on the fly.
You might need to debug some of this but here's generally how you do this...
Delete the entire $dialog variable
var $dialog = .....
And change that to something that will look similar to:
var $dialog = $('<div>').addClass('ui-state-success').append($('<p>').addClass('ui-state-error-success').html(dialog_message));
Then you'll need to do something like this:
$.colorbox({html: $dialog});
If you're having trouble seeing the content that is dynamically built inside your colorbox try calling $.colorbox.resize() on the opened callback:
opened: function(){
$.colorbox.resize();
}
If that doesn't work you may also need to pass a innerWidth/innerHeight or width/height property inside the resize method.

$("#submit").click not working :/

I've tried everything I can think of to get this "send" button to work, but I'm not very good at javascript :(
http://www.kimscakes.biz/contactme.php
Prehaps someone here can tell me where i'm going wrong?
Many thanks
Gem
You are binding the submit before the element exists, move the code after the form or put it inside $(document).ready:
jQuery(document).ready(function () {
jQuery("#submit").click(function () {
console.log("button clicked");
// declare these vars
var name = jQuery("#name");
var email = jQuery("#email");
var message = jQuery("#message");
var human = jQuery("#human");
var success = jQuery("#success");
var error = jQuery("#error");
// reset these vars
success.html("");
error.html("");
// ajax call to script.php
jQuery.getJSON("mailer.php", {
name: name.val(),
email: email.val(),
message: message.val(),
human: human.val()
}, function (html) {
// if html from script.php == 1, happy days
if (html == '1') {
jQuery("#contact").hide()
success.html("Thank You, your message has been sent.")
error.show()
}
else {
error.html(html)
}
});
});
});

Categories

Resources