I was making a form for inserting products for admin in an e-commerce project. During validation of the form data, I tried to check if the form data is empty or not.
Thus I introduced an if statement and checked the values of all the parameters passed from the form and in the if block wrote an echo statement.
Here is my code:
<? php
//text variables
if(isset($_POST['insert_product'])){
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_brand = $_POST['product_brand'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$product_status = 'on';
$product_keywords = $_POST['product_keywords'];
//images variables
$product_img1 = $FILES['product_img1']['name'];
$product_img2 = $FILES['product_img2']['name'];
$product_img3 = $FILES['product_img3']['name'];
//temp names
$temp_name1 = $FILES['product_img1']['tmp_name'];
$temp_name2 = $FILES['product_img2']['tmp_name'];
$temp_name3 = $FILES['product_img3']['tmp_name'];
//validation and insertion query
if($product_title == '' OR $product_cat == '' OR $product_brand == '' OR $product_keywords == '' OR $product_img1 == '' OR $product_price == ''){
echo"<script>alert('you have not entered all the values')</script>";
exit();
}
}
?>
It is producing an output like
(...alert('you have not entered all the values');"; exit();} } ....)
Please help me to solve this problem.
I am using Sublime text and checked the same in Notepad++ but it’s giving the same error.
This works fine for me. Try iterating through $_POST in a loop, checking values that way. It'll condense your code and make things easier to read in the future:
<?php
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
if (!isset($_POST[$key]) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
}
}
That said, you should try to preserve $_POST and use a cleaned string if you're using data provided by the user:
<?php
if (isset($_POST)) {
// Clean a string, making it safe for using with a database.
function clean_string($string) {
global $mysqli;
$string = $mysqli->real_escape_string($string);
stripslashes($string);
return $string;
}
foreach ($_POST as $key => $value) {
if (!isset($_POST) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
// If you're going to be using this $_POST data with a database you should also
// clean the strings before using them in any way.
$Data = new stdClass();
foreach ($_POST as $key => $value) {
if (isset($_POST[$key]) && $_POST[$key] !== "") {
$Data->$key = clean_string($value);
}
}
}
// All of the $_POSTed items are set and cleaned for use. Do what you will with them below.
}
try the following, *note semicolon
echo "<script language='javascript'>alert('thanks!');</script>";
echo"<script>alert('you have not entered all the values');</script>";
use this .....u r forgetting semicon after )
Related
I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js
I have a php function which simply returns a value, I want to assign that value to a variable in my javascript code in my frontend page.
email_data() function in functions.php:
function email_data()
{
$a = 0;
$form_to_DB = WPCF7_Submission::get_instance();
if ( $form_to_DB )
$formData = $form_to_DB->get_posted_data();
$type = implode(',', $formData['type']);
$type = $type . ' ' . $formData['type-other'];
$place = implode(',', $formData['place']);
$place = $place . ' ' . $formData['place-other'];
$Postcode = $formData['Postcode'];
$date = $formData['date'];
$location_long = $formData['cf7-location-lng'];
$location_lat = $formData['cf7-location-lat'];
$location_litter = $formData['cf7-location-url'];
$location_litter = $formData['location-340'];
$comment = $formData['comment'];
if ($formData != null)
{
echo "Hi there! I want to report illegal dumping which consists of $type at $place area. The coordinates of the dumping are Lat: $location_lat, Long: $location_long.";
}
else
{
echo "Please fill the above form first!"
}
return $a;
}
I have some html and javascript code on one of my pages which I am using to display a form. Now, I want the variable returned by the php code to be saved in a JS variable. I have tried doing so many things but nothing works out, I am a newbie in WordPress dev sorry.
Check out wp_localize_script. It allows you to pass PHP variables to the browser, where your javascript can then read.
I am passing some data over to a route when a specific option is selected from the form. I test the value and its coming over but when i try to use a if statement is doesn't work see code below:
$app->post('/fdfd', function ($request, $response) {
$params = $request->getParams();
$val = $params['file']; //value coming over is = "pipe"
$users = $this->db->query("SELECT * FROM `stock`")->fetchAll(PDO::FETCH_OBJ);
foreach ($users as $cat) {
if ($cat->category == $val) {
$name = $cat->name;
echo "<option value='test'>$name</option>";
} else {
echo "False";
}
}
})->setName('lazyy');
I am sure the value is coming over because if i change the if statement to == "pipe and print $val it shows pipe.
Is it that the value is taking long to come over from the form and the code is being run without it? Ive been trying to figure it out any help would be appreciated.
But if i change the value of $val explicitly to pipe it works. The code below works when i change $val to pipe.
$app->post('/fdfd', function ($request, $response) {
$params = $request->getParams();
$val = "pipe";
$users = $this->db->query("SELECT * FROM `stock`")->fetchAll(PDO::FETCH_OBJ);
sleep(2);
foreach ($users as $cat) {
if ($cat->category == $val) {
$name = $cat->name;
echo "<option value='test'>$val</option>";
} else {
echo "False";
}
}
})->setName('lazyy');
See jQuery code below if needed:
$("#catId").on("change", function() {
var category = document.getElementById("catId").value
$.post("{{ path_for('lazyy') }}", {
file:category
}, function(data) {
$("#dift").html(data);
});
})
I am trying to take information taken from a HTML/JavaScript file and I want to add the data ($email = string, $vote = value from radio button) to an empty txt file using php.
What's wrong with my code? I don't think the foreach loop is being run. Thanks!
<?php
$email = $_REQUEST['email'];
$vote = $_REQUEST['player'];
$emailList = file('email.txt');
$voteList = file('votes.txt');
foreach ($emailList as $line => $value) {
if (is_null($value)) {
file_put_contents("email.txt", $email."<br>", FILE_APPEND);
} else if ($value == $email) {
echo "You have already voted!";
} else {
file_put_contents("email.txt", $email."<br>", FILE_APPEND);
echo "Your vote has been stored! Thanks.";
}
}
?>
$foundMail = false;
foreach($emailList as $line => $value){
if(trim(preg_replace('/\n/', '',$value)) == trim($email)) {
$foundMail = true;
}
}
if(!$foundMail) {
file_put_content("email.txt", $email."\n", FILE_APPEND);
echo ('your vote has been stored');
} else {
echo 'you have allready voted';
}
I'm editing a web program in MySQL; unfortunately, I got stuck with the following:
A smarty markup, used to display a form, has the following value:
{php}
$format = $this->get_template_vars("phone_number_format");
$values = explode("|", $this->get_template_vars("VALUE"));
$name = $this->get_template_vars("NAME");
$pieces = preg_split("/(x+)/", $format, 0, PREG_SPLIT_DELIM_CAPTURE);
$counter = 1;
foreach ($pieces as $piece)
{
if (strlen($piece) == 0)
continue;
if ($piece[0] == "x") {
$size = strlen($piece);
$value = (isset($values[$counter-1])) ? $values[$counter-1] : "";
$value = htmlspecialchars($value);
echo "<input type=\"text\" name=\"{$name}_$counter\" value=\"$value\"
size=\"$size\" maxlength=\"$size\" class=\"VOLGENDE\"/>";
$counter++;
} else {
echo $piece;
}
}
{/php}
{if $comments}
<div class="cf_field_comments">{$comments}</div>
{/if}
I need to add some javascript to this, but I cannot manage to get it working. This is the javascript that needs to be added:
$(".VOLGENDE").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.VOLGENDE').focus();
}
});
With this script, I am trying to make sure that the focus will be put on the next field once the maximum amount of characters in a given field is reached.
I am looking for a way to include this javascript into the MySQL database field where the PHP code mentioned above is found. If there is anybody who could help me out with this, then that would be great :)
Thanks in advance!