Passing Javascript result to php [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
Below is my validation function of my registration form. Problem is if the user input all the correct data, how to I trigger my php function with SQL statement to insert it into my database?
<script type="text/javascript">
function validate(){
var school_name = document.formValidation.school_name.value;
var mailing_address = document.formValidation.mailing_address.value;
var city = document.formValidation.city.value;
var state = document.formValidation.state.value;
var postcode = document.getElementById('postcode');
var courier_address = document.formValidation.courier_address.value;
var courier_city = document.formValidation.courier_city.value;
var courier_state = document.formValidation.courier_state.value;
var courier_postcode = document.getElementById('courier_postcode');
var phonenumber = document.getElementById('phonenumber');
var faxnumber = document.getElementById('faxnumber');
var email = document.getElementById('email');
var website = document.formValidation.website.value;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(school_name == "" || mailing_address == "" || city == "" || state == "" || postcode == "" || courier_address == "" || courier_city == "" || courier_state == "" || courier_postcode == "" || phonenumber == "" || faxnumber == "" || email == "" || website == ""){
alert("Please enter fields marked with an asterisk");
return false;
}
if (!/^[0-9]+$/.test(postcode.value)) {
alert("Please enter numbers only for postcode");
postcode.value = postcode.value.substring(0,postcode.value.length-1);
return false;
}
if (!/^[0-9]+$/.test(courier_postcode.value)) {
alert("Please enter numbers only for courier postcode");
courier_postcode.value = courier_postcode.value.substring(0,courier_postcode.value.length-1);
return false;
}
if (!filter.test(email.value)) {
alert("Please enter a valid email address");
email.focus;
return false;
}
else {
alert("Registration Success!");
<?php
?>
return true;
}
}

Javascript runs on the users' browsers. PHP runs on your server. You have to send that data to the server, validate it there as well, then insert into the database.

Next you need a POST or GET action to send the variables to your PHP script on the serverside (this JavaScript is executed on the clientside). JQuery offers some real good and handy functions for that: .post() and .get().
http://api.jquery.com/jQuery.post/
and
http://api.jquery.com/jQuery.get/

Related

sending variable in php to ajax function

How can i push variable to ajax function in php file (witch refers to ajax )
if i have $v in my php . if all is ok it's echo "ok" in php file .So what should i do next
if ($_POST){
for ($j=0; $j< count($row);$j++){
mysql_query("INSERT INTO `".PREFIX_USR."delivery_address` (`id_personl_data`,`country`,`province`,`city`,`street`,`house`,`apartment`)
VALUES ( '12','".$row[$j][0]."','".$row[$j][1]."','".$row[$j][2]."','".$row[$j][3]."','".$row[$j][4]."','".$row[$j][5]."') ");
var count = query['id']; // just an example of what i need to push
}
echo "ok";
}
js
(function(){
function changeData(){
var name = d.getElementById('new_name').value,
surname = d.getElementById('new_surname').value,
email = d.getElementById('new_email').value,
telephone = d.getElementById('new_phone').value,
robot = d.getElementById('spam_change').value,
xml = eventsObj.getXmlHttp();
var arr = [].map.call(document.querySelectorAll('.parent_clone'), function(block) {
return [].map.call(block.querySelectorAll('.left_info_address'), function(inp) {
return inp.value;
});
});
for (var i = 0; i<arr.length-1;i++){
arr[i].push('/');
}
console.log(arr);
if(name === "" || surname === "" || email === "" || (telephone === "")){
alert("fill the fields");
}
else {
xml.open("POST",path_ajax_files+"edit_personal_data.php",true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("name="+encodeURIComponent(name)+
"&surname="+encodeURIComponent(surname)+
"&email="+encodeURIComponent(email)+
"&telephone="+encodeURIComponent(telephone)+
"&robot="+encodeURIComponent(robot)+
"&arr="+encodeURI(arr));
xml.onreadystatechange = function(){
if(xml.readyState === 4){
if(xml.status === 200){
if(xml.responseText !== ""){
alert(xml.responseText);
if(xml.responseText === "ok"){
alert("data will be changed");
}
} else {
alert('try again later');
}
}
}
};
}
}
eventsObj.addEvent(saveData, "click", changeData, false);
})();

jQuery AJAX not working on Firefox

I have a function and an AJAX call. After clicking it gets the function and function works fine, on alert it shows the data, but after that it does not send the data to PHP. Any ideas why this happens on Firefox? It works well in IE and Chrome.
function siparisolustur() {
var toplamsiparis = $('.urunrow').length;
var i = null;
var siparisid = $("#siparis_id").text();
var name = $("#siparisad").val();
var surname = $("#siparissoyad").val();
var tel = $("#siparistel").val();
var adres = $("#sepetadres").val();
var semt = $("#sepetilce").val();
var sehir = $("#sepetsehir").val();
var notlar = $("#siparisnotu").val();
var odeme = $('input[name="odemeyontemi"]:checked').attr("id");
bilgiDataString = '&siparisid=' + siparisid + '&name=' + name + '&surname=' + surname + '&tel=' + tel + '&adres=' + adres + '&semt=' + semt + '&sehir=' + sehir + '&notlar=' + notlar + '&odeme=' + odeme;
alert(bilgiDataString);
$.ajax({
type: "POST",
url: "https://www.xxxxx.com/procc/xxxxxxxxxx.php",
data: bilgiDataString,
cache: false,
success: function (html) {
}
});
$("#payForm").submit(function (e) {
var siparisdurdur = 0;
var ad = $("#siparisad").val();
var soyad = $("#siparissoyad").val();
var tel = $("#siparistel").val();
var adres = $("#sepetadres").val();
var ilce = $("#sepetilce").val();
var sehir = $("#sepetsehir").val();
var sepeturunadetget = parseInt($("#sepeturunsayisi").text());
if (ad == "" || soyad == "" || tel == "" || adres == "" || ilce == "" || sehir == "" || sepeturunadetget < 1) {
siparisdurdur = 1;
}
if (ad == "") {
e.preventDefault();
$("#siparisad").css("border- color", "#cd2828")
} else {
$("#siparisad").css("border-color", "#d1d2e6");
}
if (soyad == "") {
e.preventDefault();
$("#siparissoyad").css("border-color", "#cd2828")
} else {
$("#siparissoyad").css("border-color", "#d1d2e6");
}
if (tel == "") {
e.preventDefault();
$("#siparistel").css("border-color", "#cd2828")
} else {
$("#siparistel").css("border-color", "#d1d2e6");
}
if (adres == "") {
e.preventDefault();
$("#sepetadres").css("border-color", "#cd2828")
} else {
$("#sepetadres").css("border-color", "#d1d2e6");
}
if (ilce == "") {
e.preventDefault();
$("#sepetilce").css("border-color", "#cd2828")
} else {
$("#sepetilce").css("border-color", "#d1d2e6")
}
if (sehir == "") {
e.preventDefault();
$("#sepetsehir").css("border-color", "#cd2828")
} else {
$("#sepetsehir").css("border-color", "#d1d2e6")
}
if (blocksubmit == 1) {
e.preventDefault();
$("#personalinfosubmit").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
}
if (sepeturunadetget < 1) {
e.preventDefault();
$("#shoppingcost").css("color", "#cd2828");
$("#shoppingcost").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
}
if (blocksubmit == 0 && siparisdurdur == 0) {
siparisolustur();
}
});
I solved the problem.. Submit goes to other page before ajax is done proessing the data.. I delayed the redirect for like half second and it worked.. Its about speed of FF
I see that you've posted a solution already:
Submit goes to other page before ajax is done proessing the data.. I delayed the redirect for like half second and it worked.
Seriously, you should not be relying on a solution like this.
Timing issues like this are known as a "race condition", ie where two events are effectively in a race to see which one will finish first; you're expecting one to always win, and you get a bug if they finish in the wrong order.
It's a very well defined category of bug (even if Ajax is fairly new, situations like this have existed since the begining of computer science), and the solution is not to slow down one of the events in the hope that you'll force it to always lose. That is always the wrong solution.
The correct solution is usually to trigger the second event only after the first one has finished. In your case, this would mean firing the submit event from inside the ajax success method.

POST php headers failing

When I call a script from Javascript
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var conf = document.getElementById('confirm').value;
var code = document.getElementById('code').value;
if(code.length == 0 || pass.length == 0 || user.length == 0 || conf.length == 0) {
alert("Entries empty");
} else if(pass != conf) {
alert("Passwords don't match");
}
window.location = "scripts/changepassword.php?Username="+user+"&Password="+pass+"&Code="+code;
changepassword.php in my scripts folder has the following headings its refreshing the current page and not passing the parameters into the script. any ideas?
it gives me error2.
scripts/changepassword.php
if (isset($_GET['Username']) && isset($_GET['Password'])&& isset($_GET['Code'])) {
...
} else {
$response = array('result'=>"error2");
echo json_encode($response);
echo "hi";
}
the window.location changes the page location (url). If you want to execute the php script without refreshing the page, use AJAX

What is the value of ajax.responseText when there is no response being sent?

I wrote a javascript function that checks if a username is available in a database. If the username is NOT available the ajax send a text response back which changes some css and adds an error message. When the username is available the ajax doesn't send a response, which is fine but I just need to know what is being returned from ajax.responseText since there is no value. I've tried '' and null.
function _(x) {
return document.getElementById(x);
}
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function verifyEmail(){
var email = _("email").value;
var status = _("estatus");
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.signupform.email.value.search(emailRegEx) == -1) {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
status.innerHTML = "<br />Please enter a valid email address";
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
status.innerHTML = "";
if (email != "") {
status.innerHTML = "checking. . . ";
var ajax = ajaxObj("POST", "fan_signup_local.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
status.innerHTML = ajax.responseText;
console.log(status.innerHTML);
if (status.innerHTML !== '') {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
console.log(ajax.responseText);
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
}
}
}
ajax.send("email="+email);
}
}
}
There's always a response, unless the request times out. If the server script exits without printing anything, the response will be an empty string.

Call PHP program as popup overlay?

I am trying to use fancybox iframe to call a PHP program for payment processing from a javascript program as part of a landing page. The page also calls another PHP program that writes date to a file. I tried to simulate a click to start the fancybox function but never got it to work. I keep getting this error - $("a.hiddenclicker").fancybox is not a function. I'm not sure whether to attempt to just add this logic to the PHP file or figure out how to get fancybox to work. Here is my page. The call to fancybox is in ProcessForm().
function WriteData(url) {
var j1 = document.getElementById("hiddenclicker");
var Request2 = false;
if (window.XMLHttpRequest) {
Request2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
Request2 = new ActiveXObject("Microsoft.XMLHTTP");
}
if (Request2) {
Request2.open("GET", url, true);
Request2.onreadystatechange = function() {
if (Request2.readyState == 4 && Request2.status == 200) {
}
}
Request2.send(null);
}
}
function ProcessForm(form) {
var j1 = document.getElementById("hiddenclicker");
var firstname = "";
var lastname = "";
var payment = "";
var email = "";
var phone = "";
var donation = "";
firstname = form.firstname.value;
lastname = form.lastname.value;
email = form.email.value;
phone = form.phone.value;
donation = form.donation.value;
if (firstname == "") {
alert("You must fill in the first name");
form.firstname.focus();
return false;
}
else {
if (lastname == "") {
alert("You must fill in last name");
form.lastname.focus();
return false;
}
else {
if (email == "") {
alert("You must fill in email address");
form.email.focus();
return false; }
}
}
WriteData("writedata.php?firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&phone=" + phone + "&donation=" + donation);
if (donation == "now") {
jQuery(document).ready(function(){
$("a.hiddenclicker").fancybox(
{
'width' : 600,
'height' : 400,
'hideOnContentClick' : false,
'type' : 'iframe'
});
});
j1.href = "http://www.ccyakids.org/donation_logic/donation_start.php#form";
$('#hiddenclicker').trigger('click');
}
}
// End hiding JavaScript statements -->
HTML needed to trigger hiddenclicker
Hidden Clicker
After looking at your code you reference your link 2 different ways:
$("a.hiddenclicker") // class
$('#hiddenclicker') // ID
Which is it? Make them both the same and i am sure your problem goes away.
Hope this helps

Categories