not working form and form variable validation? - javascript

my form
<div class="input-holder">
<input type="text" class="search-input" id="string" placeholder="Искать" />
<button class="search-icon" onclick="searchToggle(this, event);"><i class="fas fa-search"></i></button>
</div>
api.php
case 'metafind': {
$string = $_GET['string'];
$list = mysqli_query($connect, "SELECT * FROM `sub_meta` WHERE `meta_key` = 'Название'&& `meta_value` ");
while ($item = mysqli_fetch_assoc($list)) {
if ($item['meta_value'] == $string) {
$id = $item['post_id'];
$arrr[] = array('post_id' => $item['post_id'], 'coords' => $find['meta_value']);
}
}
echo json_encode($arrr);
} break;
when you click on the form gives an error in the console:
(index):121 Uncaught ReferenceError: searchToggle is not defined
at HTMLButtonElement.onclick ((index):121)
it is necessary that when a word is entered into the form it was
searched for a name in the column meta_value by meta_key and then
displayed please help I'm new to php

You should try something like my below example :
1) I created textbox where i will write data then it will search in array and get the value from there where i have made array for example purpose and display the data in #div1
<div class="input-holder">
<input type="text" class="search-input" id="string" placeholder="Искать" />
<button class="search-icon"><i class="fas fa-search"></i>Go</button>
<div id="div1"> </div>
</div>
2) When button click we have to do ajax call then we will get data from there and get that data in response and we will show that response where we want to display
<script>
$(document).ready(function(){
$("button").click(function(){
var stringval = $("#string").val();
$.ajax({data: {val : stringval} , url: "democode.php", type: 'post', success:
function(result){
var data = JSON.parse(result);
console.log(data);
$("#div1").html(data);
}});
});
});
</script>
3) Ajax call on democode.php so in that file we will get data there(you can get data from database if you want) and we will return the data
==democode.php==
<?php
$test['data'] = array("Aleaxa"=>"I'm Beutiful","john"=>"I'm Evil","mishel"=>"baby, I'm Bad Boy!","mohini"=>"I'm MAstana");
if (array_key_exists( $_POST['val'], $test['data'])) {
$key = $_POST['val'];
echo json_encode($test['data'][$key]);
}
?>
So above example work like if i will search Aleaxa and click go button then it will give value of Aleaxa from array and output will be I'm Beutiful
Please checked my demo you will get idea how to do the code with your requirements

Related

Returning two variables to two different divs from another php on onClick

This is the Index.php file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="submit.js"></script>
<div class="container-fluid">
<div class="row" id="formsett">
<div class="col-sm-4">
<div id="div1">
</div>
</div>
<div class="col-sm-4">
<div id="idform">
<form id="idform" method="POST">
<p>
<label> <b> Enter NIC No: </b> </label> <br/>
<input type="text" id="idno" name="idno" />
</p>
<p>
<input type="button" id="btn" onclick="SubmitFormData();" value="Submit" />
</p>
</form>
</div>
</div>
<div class="col-sm-4">
<div id="div2">
</div>
</div>
</div>
</div>
This is the Submit.php file
$idno = ($_POST['idno']);
$gen='';
$img='';
if($idno>=12345){
$gen="ABC";
$img="<img src= 'abc.jpg'>";
}else{
$gen="DEF";
$img="<img src= 'def.jpg'>";
}
echo "$img";
echo "$gen";
This is the Submit.js file
function SubmitFormData() {
var idno = $("#idno").val();
$.post("submit.php", { idno: idno },
function(data) {
$('#div1').html(data);
});
}
I want to see the $gen value in Div1 and $img value in Div2 when click on the button without refreshing the Index.php page.
Now, using this Js code, I can see both $gen and $img values in a same div. I tried so many times by changing this js code and submit.php code, but didn't work.
How can divide that two values into two divs?
There are some things to make it cleaner but i will go for the least invasive method:
in Submit.php
...
echo $img . ";" . $gen;
in Submit.js
function(data) {
var responseArray = data.split(";");
$('#div1').html(responseArray[0]);
$('#div2').html(responseArray[1]);
});
The data that you send and receive to and from the server is send as text. While text itself does not have any meaning, the way it is formatted can.
Introducing JSON. JSON stands for JavaScript Object Notation and is a format that can be read by multiple languages. This makes it incredibly useful to exchange information between such platforms. JSON is represented as a string (text) which the language can transform into data that it can use.
Sidenote: although JavaScript is in the name it has nothing to do with it. The structure JSON uses resembles what objects and arrays in JS look like.
PHP for instance has the json_encode (data to JSON) and json_decode (JSON to data) functions to transform the data.
JavaScript has the JSON.stringify (data to JSON) and JSON.parse (JSON to data) methods to do the same thing but on its own side.
Let's apply this to your case. So you've got more than 1 value to send to the client. But you can only send once. This calls for the use of an array() to send a list of items. In this array put your $gen and $img values.
Now call json_encode to transform your array into JSON and send it to the client.
<?php
$idno = ($_POST['idno']);
$gen = '';
$img = '';
if($idno >= 12345) {
$gen = "ABC";
$img = "<img src= 'abc.jpg'>";
} else {
$gen = "DEF";
$img = "<img src= 'def.jpg'>";
}
$response = array($gen, $img);
echo json_encode($response);
die();
?>
Now on the receiving end. The response that you now get is a string with a JSON structure. Convert this string to usable data with JSON.parse.
At this point you have received an array with two values in it. You can loop over the array or manually select something from it to output in your document.
function SubmitFormData() {
var idno = $("#idno").val();
$.post("submit.php", { idno: idno },
function(response) {
var data = JSON.parse(response);
// data is now an array with two items.
var gen = data[0];
var img = data[1];
$('#div1').html(img);
}
);
}

using serializeArray, trying to insert from ajax multiple inputs, each with ID

I'm trying to submit an ajax call for a form where I have added functionality to dynamically add inputs to a form. My forms are created based on an array loop so sometimes I just have one form, sometimes more.
Regardless, I'm able to dump the proper input values from each form with a console on the button, but I'm getting a 500 error on the ajax submit.
One issue is that if I have 4 inputs in the form, I'm dumping all 4 and then my one hidden input value 'tickerID', but I'm calling a sql insert where I need to insert each value with that hidden input value.
My console log for data right now is this:
but I need to insert these as
insert into ticker_content (ticker_id, content)
values (1, 'one'), (1, 'two');
If that makes sense.
Here's my addticker.php that's being called for the insert:
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO ticker_content (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
So basically for every Items[] value, I need to insert with the same hidden field.
Here's my form and JS code for reference. The first JS block is mainly for the functionality of dynamically adding inputs, but the last JS block is the ajax using serializeArray();
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/> <!--form starts with one input-->
<button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->
<input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
<input type="submit" name="saveTickerItems" value="Save Ticker Items"> <!--submit button-->
</form>
<?php endforeach;?>
<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: $("#Items").serializeArray(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
$value = "";
foreach ($items as $item){
$value .= "('$tickerID', '$item'),";
}
$addTicker = "INSERT INTO ticker_content (tickerID, content)
values {$value}";
$mysqlConn->query($addTicker);
Use this code

load/safe html form with mysql stored data

I build a simple html/js math-form where some calculations are beeing made with.
To simplify things I shortened the form to make it easier to understand:
function output(){
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
var value3 = document.getElementById('value3').value;
document.getElementById('result1').innerHTML = (parseInt(value1) + parseInt(value2)) * parseInt(value3);
}
<select>
<option value="volvo">Simple Addition</option>
</select><button type="button">Load</button> <button type="button">Save</button> <button type="button">Cancel</button>
<br>
<br>
<br>
Title: <input id="Title" type="text"/>
<br>
<br>
<br>
<input id="value1" type="text" onchange="output();" />
<span> + </span>
<input id="value2" type="text" onchange="output();" />
<span> * </span>
<input id="value3" type="text" onchange="output();" />
<p>Result: <a id="result1"></p>
So, it's basically just a simple calculation. But I'm struggling to get the data stored with a mysql backend. The goal is:
a.) with a new calculation/form (non existing name in title-field), a new table should be created in mysql-db. Let's say we call the calculation "Simple Addition".
Simple-Addition should then be selectable via dropdown menu so others can load this calculation and even change/save/overwrite/correct it.
b.) So I want to be able to load, save and change any calculation to a mysql table and make it work that others can populate every stored calculation from a dropdown menu
c.) The maths should be named after the "Title" textfield
d.) autorefresh (kind of live collaboration like google sheets) all fields from database, let's say autorefresh every 5 seconds
I know this probably isn't a 5 min task, so I appreciate any of your help very very much. Thanks in advance!
Javasrcipt is a client-side language, it is won't communicate with MySQL server.
The possible solution is use AJAX call on client-side to save data by back-end PHP method.
this is only answer for the Save method. The load is similar like this, but you should use 'GET' instead of 'POST'.
AJAX call:
<button onclick="Save();">Save</button>
<script>
function Save()
{
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
var value3 = document.getElementById('value3').value;
var value4 = document.getElementById('title').value;
var inputsAndResult= [value1, value2, value3, title ];
$.ajax({
url : 'YOUR_URL',
method : 'POST',
data :{
arrayData:inputsAndResult
},
success : function(response)
{
alert("succes");
},
error : function(e)
{
alert("error")
}
});
}
</script>
on the backend side:
<?php
$server = "localhost";
$db = "myDB";
$conn = mysqli_connect($server, $db);
$sql = "INSERT INTO MyGuests ( number1, number2, result, name ])
VALUES ($_POST[dataArray[0]], $_POST[dataArray[1]], $_POST[dataArray[2]], $_POST[dataArray[3]])";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
These pages really good to get the basic about all of these thing like AJAX,PHP, database posting.
PHP:
https://code.tutsplus.com/courses/php-fundamentals
https://www.w3schools.com/php/default.asp
AJAX:
https://www.w3schools.com/xml/ajax_intro.asp
AJAX posting into MySQL:
https://www.w3schools.com/php/php_ajax_database.asp

post image, selected values to php via Javascript

Hello as part of my website project I am writing an item input form, the website itself is very simple, the user will:
Write item name
Select some values
Write item description in textarea
Upload item image
the page will collect this info using JS and then sent to PHP page where it will be checked and then inserted into database. I am not sure what is wrong with the code --php page gives no errors-- as it is not responding after submission, tried resolving by process of elimination, deleting the image part in JS seems to make the button respond though no output is given.
<!DOCTYPE HTML>
<html>
<header>
<title> Results </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</header>
<body>
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>Add item form.. </legend>
<p> fill out the below details </p>
<p> Item name will be publicly viewed by users: <input type="text" id="itemID" name="itemName" placeholder="Enter item name.." /> </p>
location:
<select id="locSelect"> //4 options for every select
<option id="mountainID" value="mountain"> Mountain </option>
</select>
Category:
<select id="catSelect">
<option id="appliancesID" value="appliances"> Appliances </option>
</select>
Price range:
<select id="rangeSelect">
<option id="range1ID" value="range1"> 0-$50 </option>
</select>
<p> <input type="textarea" id="descriptionID" name="descriptionName" style="height:185px;width:400px;" placeholder="Please enter any item relevant info in this area..." /> </p>
<p> Upload Image: <input type="file" id="itemImageID" name="itemImage" /> </p>
<p> <input type="button" id="addID" name="add" value="Add item" onClick="runAdd();" /> </p>
</fieldset>
</form>
<div id="addResult"></div>
<script type="text/javascript">
function runAdd()
{
var item = $("#itemID").val();
var location = document.getElementById("locSelect"); //id of select
var selectedLoc = location.options[location.selectedIndex].text;
var category = document.getElementById("catSelect");
var selectedCat = category.options[category.selectedIndex].text;
var range = document.getElementById("rangeSelect");
var selectedRange = range.options[range.selectedIndex].text;
var textArea = document.getElementById("descriptionID").value;
var itemImg = document.getElementById("itemImageID");
$.post("itemDatabase.php", {
itemDB: item,
locationDB: selectedLoc,
categoryDB: selectedCat,
rangeDB: selectedRange,
textareaDB: textArea,
itemImgDB: itemImg },
function(data)
{
if(data == "int echoed by php page"){
$("#addResult").html("item/text is blank..");
//php will echo back to addResult <div> if input is not set
}
}
);
}
</script>
</body>
</html>
I believe I am sending the textarea, select and image parts wrongly, as php echos nothing for them when they are empty. I looked up codes online though they were separate from my case usually involving AJAX or PHP exclusively.
<?php
session_start(); //for userID, different page stores it
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project_database");
if (isset($_POST['add'])){
if(empty(trim($_POST['itemDB']))) { // if(!($_POST['itemDB'])) not working
echo "0"; }
else { $item = mysql_real_escape_string($_POST['itemDB']); }
if(isset($_POST['locationDB'])){
$location = $_POST['locationDB'];
} else {
echo "1"; }
if(isset($_POST['categoryDB'])){
$category = $_POST['categoryDB'];
} else {
echo "2"; }
if(isset($_POST['rangeDB'])){
$range = $_POST['rangeDB'];
} else {
echo "3"; }
if(empty(trim($_POST['textareaDB']))) {
echo "4"; }
else { $description = mysql_real_escape_string($_POST['textareaDB']); }
if(getimagesize($_FILES['itemImgDB']['tmp_name']) == FALSE)
{
echo "5";
}
else
{
$image = addslashes($_FILES['itemImgDB']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
}
$query = "INSERT INTO item (item_name, item_description, item_price_range, item_img, item_location, user_id, category_id) VALUES ('".$item."', '".$description."', '".$range."', '".$image."', '".$location."', '".$_SESSION["userID"]."', '".$category."')";
$itemAdded = mysql_query($query);
if($itemAdded) {
echo " Item " .$item. " has been added successfully "; }
else { echo " something went wrong "; }
}
?>
category_Id and user_id are foreign keys,
Image is stored as BLOB in database (checked code working on different page)
I understand some functions are deprecated, but this is how I was instructed to complete my task, I am using notepad.
I have posted most of the code to ensure I understand what is wrong or how I can improve it in the future, I appreciate any pointers or tips just to get me on the right path at least so I can fix this.
Thank you again for any help in advance.
To answer your question about uploading images via AJAX, this was not possible before but it is now possible via FormData objects (but it is a relatively new feature and is not compatible with older browsers, if that matters to you).
You might either want to upload the image separately (old fashioned), or I suggest you look into using FormData.
This link below should be helpful (I hope):
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Hope this helps :)

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

Categories

Resources