Trouble receiving Javascript variable when sent to PHP - javascript

Problem: Trouble receiving what is being sent to my PHP document.
Javascript:
$('#form_id').submit(function(event){
event.preventDefault();
event.stopPropagation();
var message;
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
}else{
var code = (urlToValidate).slice(-22)
var request = new XMLHttpRequest();
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if (this.status ==200){
console.log (this.status);
}else{
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'php/submit.php', true);
request.setRequestHeader('Content-Type', 'text/plain');
request.send("code=" + code);
}
});
Then I'm using this code on my php/submit.php:
if (!empty($_POST['code'])) {
$code = $_POST['code'];
echo $code;
};
I feel like I'm not using the right tag names for PHP because I'm new to all of this. I'll note that I'm using form id but getting the value from an input.
Ramblings
I'm trying to send a user input that has been validated and sliced to mySQL database.
I achieved the string I wanted with javascript and passed it to a variable.
I'm trying to send it to a separate php file in another folder with a request.send(the_javaS_variable).
Now in the console I can see the variable holds the correct text value and I see it sending with state 4 and 200.
But it never shows up on the submit.php page.

try this and remove the console.log()
$('#form_id').submit(function(event){
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
// failed
}else{
var code = 'code='+(urlToValidate).slice(-22);
$.post('php/submit.php', code, function() {
// success stuff
});
}
return false;
});

Related

PHP is shown on wrong page

I'm recently working on a website project. Therefor I have a website.php with all html code, a function.php and saveArray.js . In website.php I'm printing a html table with a button at the bottom. Through the button click I'm getting to the saveArray.js, where I save all the table data in an array.
With this code
var arrString = JSON.stringify(tableData);
var request = new XMLHttpRequest();
request.open('post', 'function.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-
urlencoded');
request.send('daten=' + arrString);
I post the JS array to function.php. In function.php I do something with the array and in an if statement I want to show a modal.
The modal itself works, but I want to show it on website.php page. Which doesn't happends, because I'm currently on function.php .
How can I solve this ?
EDIT: In my array is an ID and I want to check if this ID is already in my database or not. Depending on this result I want to show the modal and upload the data if necessary. All the checking is happening in function.php
I suppose you want to inject the string returned (the modal PHP code) by your function in function.php in your current page ('website.php').
To do this, you'll have to inject the response given by the XMLHttpRequest when the request is finished.
Let's suppose we want to add all the contents within
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
See, You are not handling the response of the request.So handle the response.and restuern the status of the request from function.php and if data is saved the open the model. You need not go to the function.php page. See the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is response of the request //now check it
//Suppose you returned " data saved" as response from function.php
if(this.responseText='data saved'){
//Open model here
}
}
};
xhttp.open("POST", "function.php", true);
xhttp.send();

Data not displaying in JavaScript API

I am making a Pokedex API as a side project and I can not display the data needed to display in the different text boxes. I am using a GET request to request the height, weight, type, and ability.
<script>
$("button").click( function(){
var pokemonName = $('pokemon').val(pokemon);
event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName){
var request = new XMLHttpRequest()
//GET request with link
request.open('GET','https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload =function(){
var data = JSON.parse(this.response)
if(request.status >= 200 && request.status <= 400)
{
// outputs data
$(pokemonheight).val(response.height)
$(pokemonweight).val(response.weight)
$(pokemonAblity).val(response.ability)
$(pokemonType).val(response.type)
}
else
{
alert ("Error");
}
request.send();
}
}
</script>
</html>
I have tried setting a variable that would be equal to the response JSON element and then input that into the value of the textbox.
I do not have anything returned as expected or input displayed in the console if declared.
Issue(s)
There were a few issues with your code:
var pokemonName = $('pokemon').val(pokemon); you are setting the value of some element named pokemon (not valid) here
var data = JSON.parse(this.response); where is this.response being set? Shouldn't we be receiving response in the callback?
request.send(); is inside of the onload event, so the request never gets sent
Critiques
My main critique here is that you included a fairly large library (jQuery), and didn't utilize it to make the request. $.ajax is well documented and cleans up a lot of the intricacies of XMLHttpRequest.
The solution
$("button").click(function() {
var pokemonName = $('#pokemon').val();
//event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName) {
var request = new XMLHttpRequest()
//GET request with link
request.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload = function(response) {
var data = JSON.parse(response.currentTarget.response)
if (request.status >= 200 && request.status <= 400) {
// outputs data
console.log(data)
} else {
alert("Error");
}
}
request.send();
}
<input id="pokemon" value="12" />
<button>search</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Taking all the above issues into account, I was able to get a working example of what it should ultimately look like.
Hope this helps!

How to insert form into mysql without leaving the page (javascript+html)

I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});

Validation Form and send data to the php file

I develop a Validation Form with Javascript All think as right
but I want when Al think are accepted send the information to the php file
How I can make that ?
The HTML code :
<?php
if(isset($_GET['submit'])){
$message = '';
$email = '';
$name ='';
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "emailme";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}}
?>
<html>
<head>
<title>Contact</title>
<meta charset="UTF-8">
</head>
<body onload="randNums()">
<form>
<input id="commentName" onkeyup="validateName()" name="name" type="text" placeholder="Name"><label id="commentNamePrompt"></label><br>
<input id="commentMail" onkeyup="validateMail()" name="mail" type="text" placeholder="Mail"><label id="commentMailPrompt"></label><br>
<input id="commentPhone" onkeyup="validatePhone()" name="phone" type="text" placeholder="Phone"><label id="commentPhonePrompt"></label><br>
<textarea id="comment" onkeyup="validateComment()" name="commente" placeholder="Message here"></textarea><label id="commentPrompt"></label><br>
<span id="digit1"></span> +
<span id="digit2"></span> =
<input id="captcha" size="2" onkeyup="validateCaptcha()"><label id="captchaPrompt"></label><br>
</form>
<button href="index.php" name="submit" onclick="validateCommentForm()" > Send</button><label id="commentFormPrompt"> </label>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
js code
function randNums(){
var rand = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
document.getElementById("digit1").innerHTML = rand;
document.getElementById("digit2").innerHTML = rand2;
}
function validateName(){
var name = document.getElementById("commentName").value;
if (name.length == 0){
producePrompt("Name *", "commentNamePrompt", "red");
return false;
}
if(!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
producePrompt("name wrong","commentNamePrompt","red");
return false;
}
producePrompt("accept", "commentNamePrompt", "green");
return true;
}
function validatePhone(){
var phone = document.getElementById("commentPhone").value;
if(phone.length == 0){
producePrompt("phone *", "commentPhonePrompt", "red");
return false;
}
if(phone.length != 10){
producePrompt("10 numbers", "commentPhonePrompt", "red");
return false;
}
if(!phone.match(/^[0-9]{10}$/))
{
producePrompt("phone wrong","commentPhonePrompt","red");
return false;
}
producePrompt("Accept", "commentPhonePrompt", "green");
return true;
}
function validateMail() {
var mail = document.getElementById("commentMail").value;
if(mail.length == 0){
producePrompt("mail *", "commentMailPrompt", "red");
return false;
}
if(!mail.match(/^[A-Za-z._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/))
{
producePrompt("Wrong mail","commentMailPrompt","red");
return false;
}
producePrompt("accept", "commentMailPrompt", "green");
return true;
}
function validateComment(){
var comment = document.getElementById("comment").value;
var required = 30;
var left = required-comment.length;
if (left > 0){
producePrompt(left + " lettre" ,"commentPrompt","red" );
return false;
}
producePrompt("accept", "commentPrompt", "green");
return true;
}
function validateCaptcha(){
var captcha = document.getElementById("captcha").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(captcha.length == 0){
producePrompt("captcha *", "captchaPrompt", "red");
return false;
}
if(!captcha.match(/^[0-9]{1,2}$/) || !captcha.match(sum)){
producePrompt("Captchas wrong","captchaPrompt","red");
return false;
}
producePrompt("Accept", "captchaPrompt", "green");
return true;
}
function submitForm(){
var server = 'http://localhost/test'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/index.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
//
}
else{
//
}
}
});
}
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide form","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function jsShow(id){
document.getElementById(id).style.display = "block";
}
function jsHide(id){
document.getElementById(id).style.display = "none";
}
function producePrompt(message, promptLocation, color){
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
that's is my code, the php code with HTML, And javascript with Ajax but when I click into submit button nothing happens, Any solution ?
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide Form ","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function submitForm(){
var server = 'url'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/api.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
// sucess code
}
else{
// fail code
}
}
});
}
Edit: You need to echo in your php echo a number 1 if sucess or a number 2 if fail.
PHP
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "$email";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}
So AJAX is about creating more versatile and interactive web applications by enabling web pages to make asynchronous calls to the server transparently while the user is working. AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.
The technologies AJAX is made of are already implemented in all modern web browsers, such as Mozilla Firefox, Internet Explorer, or Opera, so the client doesn't need to install any extra modules to run an AJAX website. AJAX is made of the following:
JavaScript is the essential ingredient of AJAX, allowing you to
build the client-side functionality. In your JavaScript functions
you'll make heavy use of the Document Object Model (DOM) to
manipulate parts of the HTML page.
The XMLHttpRequest object enables JavaScript to access the server
asynchronously, so that the user can continue working, while
functionality is performed in the background. Accessing the server
simply means making a simple HTTP request for a file or script
located on the server. HTTP requests are easy to make and don't cause
any firewall-related problems.
A server-side technology is required to handle the requests that come
from the JavaScript client. In this book we'll use PHP to perform the
server-side part of the job.
For the client-server communication the parts need a way to pass data and understand that data. Passing the data is the simple part. The client script accessing the server (using the XMLHttpRequest object) can send name-value pairs using GET or POST. It's very simple to read these values with any server script.
The server script simply sends back the response via HTTP, but unlike a usual website, the response will be in a format that can be simply parsed by the JavaScript code on the client.
The suggested format is XML, which has the advantage of being widely supported, and there are many libraries that make it easy to manipulate XML documents. But you can choose another format if you want (you can even send plain text), a popular alternative to XML being JavaScript Object Notation (JSON).
Simple example with old school style:
The HTML
<html>
<head>
<title>AJAX with PHP: Quickstart</title>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage"></div>
</body>
</html>
The Magician
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() {
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process() {
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "**yourPHPfiletoretrievedata**.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// executed automatically when a message is received from the server
function handleServerResponse() {
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4) {
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200) {
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else {
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}

On ajax success set variable and use the variable in jquery outside ajax

Aim is to set (change) html hidden input field value to 0 after successful execution of ajax.
At first decided on ajax success to define variable and latter to use outside ajax.
But read (JQuery - How to use the return value of an ajax call outside that ajax call) that it is impossible.
Need to find some solution.
Below is code
Ajax (as an example)
<script language="JavaScript" type="text/javascript">
function ajax_post(){
if (window.XMLHttpRequest)
{
var hr = new XMLHttpRequest();
}
else
{
var hr = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "_autosave.php";
var sabt = document.getElementById("date_day1").value;
var prao = document.getElementById("amount1").value;
var vars = "date_day1="+sabt+"&amount1="+prao;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
Here I decided to define variable to use it outside ajax. As read this does not work because script runs over the variable and reaches outside ajax variable before the ajax variable is set.
var ajax_post_success = 1;
Remaining part of code
}
}
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
Then latter (if ajax success set value to 0)
<input type="hidden" name="is_row_changed1" id="is_row_changed1" value="" >
<script>
$(document).ready(function() {
if(ajax_post_success == 1) {
document.getElementById('is_row_changed1').value = 0;
}
});
</script>
Aim of all this is following.
I plan to use table with 10 rows and 19 input fields in each row.
If user enters something in any of fields, value of hidden input field changes to 1 (this is ok).
Then with ajax insert/update user input.
After successful insert/update set hidden field value to 0.
On each php insert/update execution check if hidden field value is 1. If value is 1 insert/update the row. If value is 0 do nothing with the row. Insert/update only rows which hidden field value is 1.
That is the aim of the question.
What would be solution?
I don't think you need to have that variable, you can change the value of the hidden field is_row_changed1 to zero in the onreadystatechange callback of the ajax method
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
document.getElementById('is_row_changed1').value = 0;
}
}
I would suggest using jQuery ajax like
function ajax_post() {
var sabt = $('#date_day1').val();
var prao = $('#amount1').val();
$.ajax({
url : "_autosave.php",
data : {
date_day1 : sabt,
amount1 : prao
}
}).done(function(html) {
$('#status').html(html);
$('#is_row_changed1').val(0);
});
}

Categories