send data with ajax multi input - php

I try to use INSERT INTO to Database using AJAX with multi input data, but I Face some Problem when I send data more than one Input Data. Did I Missed something?
This's JS file
JAVASCRIPT
function ajaxSaveTitle() {
'use strict';
var vTitle = document.getElementById('inputTitle').value;
var vPrice = document.getElementById('inputPrice').value;
var vTitlev = "vTitlev=" + vTitle;
var vPricev = "vPricev=" + vPrice;
var tXhr = new XMLHttpRequest();
tXhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById('linputTitle').innerHTML = this.responseText;
}
};
tXhr.open("POST","uploadfile.php","true");
tXhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
tXhr.send(vTitlev,vPricev);}
This is PHP file
PHP
<?php
session_start();
include_once('connect.php');
$currID = $_SESSION['user_id'][0];
if(!empty($_POST['vTitlev']) && !empty($_POST['vPricev'])) {
$fileTitle = $_POST['vTitlev'];
$fileTitle = stripslashes($fileTitle);
$fileTitle = mysqli_real_escape_string($con, $fileTitle);
$filePrice = $_POST['vPricev'];
$filePrice = stripslashes($filePrice);
$filePrice = mysqli_real_escape_string($con, $filePrice);
$qfileTitle = "INSERT INTO file (usr_ID, fileName, prc) VALUES
('$currID','$fileTitle','$filePrice')";
if(mysqli_query($con, $qfileTitle)) {
echo "Berhasil di Simpan";
} else {
echo("Error description: " . mysqli_error($con));
};
mysqli_close($con);}
?>

you should use send like that:
tXhr.send(vTitlev+'&'+vPricev);
it accepts a string as params: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

You have to send more data with use of &
change your send code
tXhr.send(vTitlev,vPricev);}
to
tXhr.send(vTitlev+"&"+vPricev);}

In case of post requests, your data should be bind with "&". Comma is invalid as send accept only one parameter.
Look at this https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
Data should be like this
xhttp.send("fname=Henry&lname=Ford");
not this
xhttp.send("fname=Henry,lname=Ford");

Related

Ajax JSON.parse JSONarray

I am trying populate a form from a mysqli database when an option is selected from a drop down. I am trying to do this with an ajax 'get' call to a PHP page. The PHP page does the SQL query and returns the results, then I do a json_encode of the data. This puts the JSON into an array. Then the ajax function attempts to parse the JSON. However this is where the problem lies. The JSON data comes in as an array and the JSON.parse(xhr.response) fails to parse.
[{"id":"12","accountnum":"2148","name":"Blah","address":"123 Dan Hwy","city":"ANY Town","state":"IA","zip":"11111","phonenumber":"555-555-5555","brand":"Dan","create_date":"2021-06-14 15:47:36"}]
//////////////////////////////////////////////////
<script>
const selectElement = document.querySelector('.accountnum');
selectElement.addEventListener('change', (event) =>{
const result = document.querySelector('.result');
var eventResponse = `${event.target.value}`;
result.textContent = 'the account num is ' +eventResponse;
loadAccounts(eventResponse);
});
</script>
///////////////////////////////////////
function loadAccounts(eventResponse){
var xhr = new XMLHttpRequest();
var url = "users.php";
var geturl = xhr.open('GET', url+"?accountnum="+eventResponse, true);
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE) {
if(this.status == 200){
console.log(xhr.response);
var accounts = JSON.parse(xhr.response);
console.log(accounts.id);
console.log(accounts.name);
var output = '';
for(var i in accounts){
output += '<div class="form-group">' +
'<label for="accountname">AccountNum*</label>' +
'<input type="text" class="form-control" id="accountnum" name="accountnum" value= '+accounts[i].accountnum+ '>' +
'</div>'
}
document.getElementById('accounts').innerHTML = output;
}
}
}
xhr.send()
}
</script>
////////////////////////////////////////////////
<?php
$accountnum = $_GET['accountnum'];
$query = "SELECT * FROM accounts WHERE accountnum = $accountnum";
$result = mysqli_query($conn, $query);
$accounts = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($accounts);
?>
Your response is an array, not an object. Try reassigning the accounts variable like accounts = accounts[0];. Or make your php script extract the first element from the result set and json encode it loke echo $accounts[0] ?? null;

How to pass value into .post Serialize using jQuery?

I have these jQuery code.
I generate 6 digits random number and I need to pass it into .post Serialize every time button is clicked. I want the number generate inside jQuery click function.
Somehow I cannot pass the value of "var tac_no" into .post Serialize.
Here's my code for jQuery
$('#request_code').click(function(e){
var tac_no = Math.floor(100000 + Math.random() * 900000);
var data_tac = $("#form-tac").serialize()+"&type="+"updateTable";
$.post("php/ajax-request-tac.php",data_tac).done(function( data ){
if(data==true)
{
alert('Request Success');
}
else if(data==false)
{
alert('Request failed');
}
});
return false;
});
And here's my php code
<?php
require 'conn.php';
function oracle_escape_string($str)
{
return str_replace("'", "''", $str);
}
if((isset($_POST['type'])) && ($_POST['type']=='updateTable'))
{
$sqlNextSeq = "SELECT SEQ_TAC.nextval AS RUNNO FROM DUAL";
$stid2 = oci_parse($ociconn,$sqlNextSeq);
oci_execute($stid2);
$row = oci_fetch_array($stid2, OCI_RETURN_NULLS);
$query = "insert into table
(
ID,
TAC_NO
)
values
(
'".$running_no."',
'".oracle_escape_string($_POST['tac_no'])."',
)
";
oci_execute(oci_parse($ociconn, $query));
echo true;
}
?>
Any idea how to do that ?
Appreciate if someone can help me. Thanks.
Personally, I'd generate the random number in PHP, but I think the issue is that you're not passing the data properly into PHP with thepost() function:
$.post("php/ajax-request-tac.php",data_tac).done(function( data ){
Instead you should pass it in as an object:
$.post("php/ajax-request-tac.php",{data_tac: data_tac, tac_no: tac_no}).done(function( data ){
Append that number to tac_no directly,
$('#request_code').click(function(e) {
var tac_no = Math.floor(100000 + Math.random() * 900000);
var data_tac = $("#form-tac").serialize() + "&type=" + "updateTable"+"&tac_no="+tac_no;
$.post("php/ajax-request-tac.php", data_tac).done(function(data) {
if (data == true) {
alert('Request Success');
} else if (data == false) {
alert('Request failed');
}
});
return false;
});
Anyway its front end code, user can always see what you are sending, so security won't be covered.

ajax request not posting form data

I have a problem where the values entered (email and password) into my login form are not being parsed to my server php script.
My ajax request:
function signin(){
var loginEmail = gebi("loginEmail").value;
var loginPass = gebi("loginPass").value;
if(loginEmail == "" || loginPass == ""){
gebi("loginEmail").style.borderColor = "red";
gebi("loginPass").style.borderColor = "red";
} else {
gebi("signinBtn").style.display = "none";
//Declare ajax request variables
hr = new XMLHttpRequest();
url = "main.php";
vars = "email="+loginEmail+"&pass="+loginPass;
//Open the PHP file that is receiving the request
hr.open("POST", url, true);
//Set content type header info for sending url ecncoded variable in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Trim string data before sending it
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
//Access the onreadystatechange event for the XMLHttpRequest
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var responseText = hr.responseText.trim();
if (responseText != "signin_failed") {
console.log(responseText);
} else {
console.log(responseText);
gebi("signinBtn").style.display = "block";
gebi("loginEmail").style.borderColor = "red";
gebi("loginPass").style.borderColor = "red";
}
}
}
//Send the data to the PHP file for processing and wait for responseText
hr.send(vars);
}
}
and when the php script returns a value using this code:
if (isset($_POST["email"])) {
echo 'email = '+$_POST["email"];
}
the return value that is logged to the console is '0' even tho there is data present in the forms fields.
What is going wrong?
The problem is in your PHP script. If you are trying to concatenate string in PHP use dot .. + is used to concatenate string in languages like javascript.
echo 'email = ' . $_POST["email"];

Ajax script not working

I know I should be more specific about the problem but I don't know what it is but once I have an answer I fix the post.
Here is the problem simple ajax script but somehow it isn't working. I can't see any error on the code =/
jQuery part:
$(document).ready(function()
{
var addFavPhp = '../functions/addfav.php';
var orange = 'orange';
var favLinkError = false;
var favNameError = false;
$('#addFavButton').click(function()
{
var favLink = $('.favLinkInput').val();
var favName = $('.favNameInput').val();
var fileName = $('.file').val();
if(favLink=="")
{
$('.favLinkInput').css('border-color',orange);
favLinkError = true;
}
if(favName=="")
{
$('.favNameInput').css('border-color',orange);
favNameError = true;
}
if((favLinkError==false) && (favNameError==false))
{
$.post(addFavPhp,{favLink:favLink,favName:favName,fileName:fileName},function(addFav)
{
$('.favLinkInput,.favNameInput').val('').css('border-color','');
$('.file option[value=""]').attr("selected", "selected");
location.reload();
});
}
});
});
and php part:
<?php session_start();
include('../functions/connect.php');
if(!empty($_SESSION['username']))
{
$username = $_SESSION['username'];
}else
if(!empty($_COOKIE['PHPCOOKID']))
{
$cookie = htmlspecialchars(trim($_COOKIE['PHPCOOKID']));
$explode = explode('-', $cookie);
$username = $explode['0'];
}
$favLink = htmlspecialchars(trim($_POST['favLink']));
$favName = htmlspecialchars(trim($_POST['favName']));
$fileName = htmlspecialchars(trim($_POST['fileName']));
$d = array($username,$favLink,$favName,$fileName);
$req = $DB->prepare('INSERT INTO favs (username,favLink,favName,favFile) VALUE (? , ? , ? , ?)');
$req->execute($d);
?>
What I figure out is that it stop working around $.post but I can't figure out why. And it works find on local server.
Thanks for any help.
looks like the line var addFavPhp = '../functions/addfav.php'; is wrong. you have to use http urls when doing ajax. somthing like /path/to/addfav.php

Ajax and php when inserting into MySQL

Simple question guys , i have AJAX that pickup all data from page and it suppose to open new php page to update MySQL database , its only updating last row of data , BUT when i use alert from javascript just to check all data i got he does update whole table ... is there any chance that AJAX is not working fast enough or something?
here is my code
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var MatchID = '';
var HomeTeam = '';
var AwayTeam = '';
var TipID = '';
var arrayMaxValues = 3;
var myArray = new Array(3);
var i = 0;
$('#teams_table input[type=text]').each(function () {
myArray[i] = $(this).val();
if (!!myArray[2])
{
MatchID = myArray[0];
HomeTeam = myArray[1];
AwayTeam = myArray[2];
if (HomeTeam > AwayTeam) {
TipID = 1;
}
else if (HomeTeam == AwayTeam) {
TipID = 2;
}
else if (HomeTeam < AwayTeam) {
TipID = 3;
}
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' +
TipID + '&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, true);
http.send(null);
myArray = new Array(3);
i=0;
}
else
{
i++;
}
});
It is kinda odd to me when i use
alert('MatchID = ' + MatchID + ' HomeTeamScore = ' + HomeTeam + ',
AwayTeamScore = ' + AwayTeam)
Inside of AJAX code i get whole table updated , without it just last row
And my php page
<?php
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$HomeScore = $_GET['HomeTeam'];
$AwayScore = $_GET['AwayTeam'];
$query="update probatip1.matches set ResultTipID=".$tipID.",HomeTeamScore = "
.$HomeScore.",AwayTeamScore= ".$AwayScore." where MatchID =".$matchID;
$UpdateGame= mysql_query($query) or die(mysql_error());
mysql_close()
?>
Try encoding the data. i.e:
MatchID = encodeURIComponent(myArray[0]);
HomeTeam = encodeURIComponent(myArray[1]);
AwayTeam = encodeURIComponent(myArray[2]);
in php use
function escapedata($data) {
if(get_magic_quotes_gpc()) {
$data= stripslashes($data);
}
return mysql_real_escape_string($data);
}
to escape your data before updating the table. i.e:
$query="update probatip1.matches set ResultTipID=".escapedata($tipID).",HomeTeamScore = ".escapedata($HomeScore).",AwayTeamScore= ".escapedata($AwayScore)." where MatchID =".escapedata($matchID);
Hope this works.
Not really a direct answer, just something that you can base your answer from. What the code does is to submit a whole object using the $.post method in jquery which takes in 2 parameters and a callback function which is executed once the request is done.Not really sure by: open new php page to update MySQL database but I assume that you're simply using that page to update the database and not actually open it.
<script src="js/jquery.min.js"></script>
<script>
var obj = {
'teams' : [
{'name' : 'teamA', 'grade' : 'A'},
{'name' : 'teamB', 'grade' : 'B'}
]
};
$.post('access.php', {'obj' : obj}, function(data){
var d = JSON.parse(data);
for(var x in d){
console.log(d[x].name);
}
});
</script>
access.php:
<?php
$post = $_POST['obj']['teams'];
$array = [];
foreach($post as $row){
$name = $row['name'];
$grade = $row['grade'];
$array[] = ['name'=>$name, 'grade'=>$grade];
}
echo json_encode($array);
?>
So you only have to modify the php page, and put your database query inside the loop. This way you won't need to perform so many ajax request by putting it inside $.each
Then utilize $.each to build the object that you're going to submit via ajax through $.post method:
var obj = {};
$().each(function(index){
var myArray[i] = $(this).val();
var MatchID = myArray[0];
var HomeTeam = myArray[1];
var AwayTeam = myArray[2];
obj[index] = [];
obj[index]['match_id'] = MatchID;
});
The problem is with your logic in the way you are sending requests to php file to update the MYSQL. Actually you are running the ajax request in a loop and the loop is too fast that kills the previous update request.
Solution
You can compose an array and send it to the php outside the loop. That will work for you.
Guys with your help i managed to fix my problem
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' + TipID +
'&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, false);
http.send(null);
var response = http.responseText;
So basicly with this line i told http request not to go for next line of code until update in table is not completed , when http has done his job then it moves on next line of code.
Thank you for help

Categories