Insert data in sql with ajax not working - javascript

I'm trying to insert data in a sql table using ajax and php, but it's not working. My ajax give me the result like it works, but when i look at the table, there's not in it. Doing it without ajax works fine, so i guess my php is working ok.
Here's the code:
HTML:
<form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>
<input type="submit" value="Enviar"/>
</form>
PHP:
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
switch($passo){
case "cadUsr":
cadUsr();
break;
default:
getRetorno();
break;
}
function getRetorno(){
echo "Este texto foi escrito via PHP";
}
function cadUsr(){
require("dbCon.php");
require("mdl_usuario.php");
$usr = $_POST["txtNome"];
$idade = $_POST["txtIdade"];
$resultado = usuario_cadastrar($con,$usr,$idade);
if($resultado){
echo "Cadastro efetuado com sucesso";
} else {
echo "O cadastro falhou";
}
}
?>
OBS: I need to pass the action of the form with the url parameter as cadUsr, so it call the function in php.
AJAX:
window.onload = function(){
var xmlhttp;
var frm = document.querySelector("#frmCadUsr");
var url = frm.getAttribute("action");
var nm = document.querySelector("#txtNome").value;
var idade = document.querySelector("#txtIdade").value;
frm.addEventListener("submit",function(e){
e.preventDefault();
try{
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("POST",url,true);
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//alert("Deu certo");
console.log(xmlhttp.responseText);
}
}
} catch(err){
alert("Ocorreu um erro.<br />"+ err);
}
});
}
The PHP function to insert the data:
function usuario_cadastrar($conexao,$nome,$idade){
if($nome == "" && $idade == ""){
return false;
}
$sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);
$resultado = mysqli_query($conexao,$sql);
return $resultado;
}

I think the problem is here servico.php?p=cadUsr. You copy the action-attribute from the form with a querystring. If you cut the querystring from it, I think it will work.
The main problem is being called by Hossein:
This :
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
Will not work. You're doing a post, you can't get GET variables.
You call value on value which will result in undefined and that will put no data in your database.
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
So remove value and add the cadUsr variable to the querystring in the send function. Update PHP to:
$passo = (isset($_POST['p'])) ? $_POST['p'] : "";
And it will work!
You can see your callback codes by adding console.log(xmlhttp.responseText); to your readystate success function.
Also you need to set the requestheader content-type to x-www-form-urlencoded when sending post.

Related

PHP not able to read JSON but writes extra lines in SQL

I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits

Receiving data from JavaScript into PHP

Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.

Passing values from ajax to php class functions

Q. Is there a way to pass values from ajax to a certain php class having functions? Let's say validating a username on the registration form whether the user exist or not.
This is a simple form that will accept username and has a span tag to display the message.
<form action="" method="POST">
<input type="text" name="username"><span class="check"></span>
<input type="submit" name="signup">
</form>
And for the php class:
<?php
class User {
function isUserExist($username) {
$query = mysql_query("SELECT username FROM users WHERE username='$username'");
$result = mysql_num_rows($query);
return ($result !== 0 ? true : false);
}
}
?>
It is initialized on the php class that established connection to the database.
So calling to the php page will become like this: $user->isUserExist($_POST['username']);.
So is it possible to pass values from the form to ajax and send it to the php class function?
From Html to ajax
var username = $("input[name='username']").value;
Fetch in ajax & Send it to php(server)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//set your span to this -> xhttp.responseText;
}
};
xhttp.open("POST", "your php script url", true);
xhttp.send("username="+username);
Receive it on the server(php)
$mUsername = $_POST['username'];
echo $mUsername;
Read this tutorial for more help
Tutorial on PHP + AJAX
Try this,
<script type="text/javascript">
$(document).ready(function(){
$("input[name = 'signup']").click(function(e) {
var username = $("input[name = 'username']").val();
$.ajax ({
url: "isUserExist_function_existing_file.php",
data: { username : username },
success: function( result ) {
if(result)
alert("Name allready Exist");
else
alert("Name available");
}
});
});
});
</script>

AJAX email form will not submit

I have an email sign-up form on my site that I recently added validation to.
Now, the form will not send or provide an error message. When I check the inspector I see the following error:
TypeError: null is not an object (evaluating 'document.getElementById(update[0]).innerHTML = update[1]')
This is my contact.php file
<?php
$to = "hello#interzonestudio.com";
$subject_prefix = "";
if(!isset($_GET['action']))
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to,$subject,$message,"From: ".$email."");
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>';
else {
echo("$email is not a valid email address");
}
?>
This is my form in HTML
<div id="contactarea">
<span style="font-family: 'Old Standard TT', serif;">Newsletter</span>
<form id="contactform" name="contactform" >
<input class ="email" type="text" name="email" id="inputbox" value="E-Mail"
onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
<input type="submit" value="Submit" name="send" onclick="sendemail(); return false; " class="signup" >
</form>
</div>
and this is my javascript
<script language="javascript">
function createRequestObject() {
var ro;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} else {
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sendemail() {
var email = document.contactform.email.value;
document.contactform.send.disabled = true;
http.open('get', 'contact.php?email=' + email + '&action=send');
http.onreadystatechange = handleResponse;
http.send(null);
setTimeout(function() {
jQuery(document).find("#thanks").fadeOut();
}, 3000);
}
function handleResponse() {
if (http.readyState == 4) {
var response = http.responseText;
var update = new Array();
if (response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById(update[0]).innerHTML = update[1];
}
}
}
</script>
Any insight would be greatly appreciated.
I think this is what you are looking for:
document.contactform.send.disabled=false;
add another div in html page with id = "msg"
replace
document.getElementById(update[0]).innerHTML = update[1];
with
you can add conditions here
depending on what you want to display upload[0] or upload[1]
document.getElementById('msg').innerHTML = update[0]+update[1];
and in contact.php
there is '}' missing before else.
Multiple errors, client and server-side.
Changes to javascript. Your form data wasn't being sent in the php call.
I have made changes to your call type get/post and used new FormData(). If you want to add more to your call formdata.append("ParamName", Value/Variable); and use $something=$_POST['ParamName']; to get the post in PHP.
var formdata = new FormData();
formdata.append("email", email);
formdata.append("action", "send");
http.open('POST', 'contact.php');
http.onreadystatechange = handleResponse;
http.send(formdata);
Changes to PHP. You missed the opening/closing of the if statements.
The way you have your javascript setup, you split the php reply (|) if the email posted wasn't valid you would cause a JS error because you didn't have the divID and bar(|) in your echo.
$to = "hello#interzonestudio.com";
$subject_prefix = "";
if(isset($_POST['action'])){ // ***** Missing ({)
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_POST['email']); //The senders subject
$email = trim($_POST['email']); //The senders email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)===false) {
mail($to,$subject,$message,"From: ".$email."");
// **** Div ID Missing with Bar (contactarea|)
echo 'contactarea|<div id="thanks">Thank you. We promise you won\'t regret it.</div>';
// **** Else missing (})
}else {
echo("contactarea|$email is not a valid email address");
}
}// **** Close if issset (})
I hope I have covered all your problems in this answer.
If you don't understand anything please leave a comment below, i will update the answer to help you understand anything within this answer. I would rather you take this source code understand it, not just a copy paste. You won't learn from copy/paste.
Tip: Clean your php string before putting them into mail().
I hope this helps. Happy coding!

How to pass large array value from javascript to php

My requirement is to make multiple xml request and to store the data in an array so that if i get say for example 4000 records I can display 40 records in a page and can do pagination. So if i goto page2 I can get the data from the array instead of making the xml request again.
Currently I am using a php array variable to store large amount of data and on click a button javascript function will call the same php page again using ajax request through query string. The problem is that the query string can't hold large arrays.
Here is my code -
Passing php array to javascript variable
echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var allProd = '.json_encode($allProd);
echo '/* ]]> */</script>';
Using form calling javascript function through button click
<form id="new_page" name="new_page" method="post" action="" >
<td> Jump to page <input name="neggPage" id="neggPage" class="pageText" style="height:20px; width:40px"/></td>
<input type="hidden" name="hideProd" value="<?php echo htmlentities(serialize($allProd)); ?>" />
<td><input type="Submit" name="neggBut" value="Go" class="pageButton" onClick="get_results(document.getElementById('neggPage').value, <?php echo $sInd; ?>, <?php echo $rndTot; ?>, <?php echo $totEnt; ?>, allProd);">
Total pages <?php echo $rndTot; ?></td>
<td height="40"> </td>
</tr></table>
</form>
Javascript function
<script>
function get_results(PageNo, SelIndex, totPage, totEnt, allProd)
{
var allProd1 = '';
for (i=0; i < allProd.length; i++)
{
allProd1 += '&q[' + i + ']=' + encodeURIComponent(JSON.stringify(allProd[i]));
}
if (PageNo > totPage || isNaN(PageNo))
{
alert ('Please enter the available pages');
}
else
{
var neggProd = sessionStorage.getItem('Product1');
var cntryCode = sessionStorage.getItem('Cntry');
var sortType;
var ordType;
if (SelIndex == 0) {sortType = 'bestmatch';}
else if (SelIndex == 1) {sortType = 'bestseller';}
else if (SelIndex == 2) {
sortType = 'pricehigh';
ordType = 'dsc';
}
else if (SelIndex == 3) {
sortType = 'pricelow';
ordType = 'asc';
}
document.getElementById("sl_api").innerHTML="";
document.getElementById("sl_api1").setAttribute("style","background: url('KartEazy/loading.gif') #edeeee no-repeat center center; background-size:20px 20px;");
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("sl_api").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET",'KartEazy/Skimlinks/Skimlinks.php?PageNum=' + PageNo + '&neggProd=' + neggProd + '&cntryCode=' + cntryCode + '&sortType=' + sortType + '&ordType=' + ordType + '&totEnt=' + totEnt + allProd1, true);
xmlhttp.send();
setInterval(function() {
document.getElementById("sl_api1").setAttribute("style","background: #edeeee;")},4500);
}
}
</script>
In the same page now I am trying to get the array
if(isset($_REQUEST['q']))
{
$totEnt = $_REQUEST['q'];
}
I tried using hidden form variable but even $_POST also not accepting large arrays. Could any of you please give me a solution or suggestion. It will be very helpful for me.
Even storing the data in database or session variable will not solve my requirement. Because if I use database I can't retrieve data for multiple queries and even php session variable will be overwritten if the user uses multiple tabs for the same url.
I was in a similar situation where I was passing several MEG of data from Javascript to PHP.
I don't have the code with me, so I can only give you a p-code solution, but it will give you the idea.
// JavaScript:
var bigstring = "...."; the data to pass
var chunkSize = 100*1024;
// http://stackoverflow.com/questions/7033639/javascript-split-large-string-in-n-size-chunks
var chunks = splitString(bigstring);
var chunkIdx = -1; // Prime the pump
function sendNextChunk() {
chunkIdx++;
if (chunkIdx < chunks.length) {
// Your AJAX call here
var data = {
piece: chunkIdx
ofpieces: chunks.length;
}
// set your onsuccess method to call
// sendNextChunk again
}
}
sendNextChunk(); // start it.
Now, for your PHP code:
// Read in each chunk, and the piece number.
// The way I've got the code written, then come in sequentional order
// so open up a temporary file and append the data.
// when piece === ofpieces
// you have the whole file and you can then process it.

Categories

Resources