Loading / executing .php file - javascript

I have been at this for a few hours now, i'm pretty sure it's a syntax error from my side, i'm trying to call a .php file and execute the contents, i'm passing through a textarea value to be used in the .php code.
HTML:
<div id="mainContent"></div>
<div class="panel panel-primary">
<div class="panel-heading">Your article rewriter API is - (<span class="results"><b>http://www.example.com/api.php?spinner=1&key=<?php echo $user['api_key']; ?></b></span>)</div>
<div class="panel-body">
<form id="frmAjax" action="spinner.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-4 text-right">
<label for="txtLanguage" class="control-label">Language:</label>
</div>
<div class="col-sm-8">
<select id="txtLanguage" name="txtLanguage" class="form-control" required="required">
<?php
$level = array("syn/en.syn" => "English", "syn/de.syn" => "German", "syn/pl.syn" => "Polish");
?>
<?php foreach ($level as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4 text-right"><label for="txtBody" class="control-label">Article:</label></div>
<div class="col-sm-8"><textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea></div>
</div>
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="spinText" class="btn btn-default">Spin!</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Paste in an article above and hit <b>Spin</b>!</div>
</div>
<script>
$(document).ready(function() {
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val();
$.ajax({
url: "ajax-rewriter.php",
type: "POST",
data: { textData : text }
})
});
});
$("#mainContent").load('ajax-rewriter.php')
e.preventDefault();
</script>
ajax-rewriter.php
<?php
include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
if (isset($_REQUEST['textData')) {
$articleBody = strtolower($_REQUEST['textData']);
echo $articleBody;
echo "<pre><b>Original:</b><br /><br /><p>" . $articleBody . "</p></pre>";
$word = "";
$length = strlen($articleBody);
$OutputBody = "";
for ($i = 0; $i < $length; $i++) {
$word = $word . $articleBody[$i];
if ($i == $length - 1)
$comeCha = " ";
else
$comeCha = $articleBody[$i + 1];
$retStr = getWordPattern($word, $comeCha, "syn/en.syn");
if ($retStr != "") {
$OutputBody .= $retStr;
$word = "";
}
}
echo "<br>";
echo "<pre><b>Spun:</b><br /><br /><p>" . $OutputBody . $word . "</p></pre>";
}
?>
Pretty basic code, nothing is happening at all once i press the "Spin!" button, i'm still learning Ajax, i don't see any obvious errors, is there also a way i can debug what the issue is, normally php throws you an error to work from, any help is appreaciated!

Your Ajax should be like this.
$(document).ready(function() {
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val();
$.ajax({
url: "ajax-rewriter.php",
type: "POST",
data: text,
success: function(html) {
$("#mainContent").html(html); //This will load the data at ID "#mainContent".
}
});
});
});

if($_SERVER["REQUEST_METHOD"] == "POST")
{
$data = $_POST['txtbody'] //where txtbody is the name in input form
}

Related

SyntaxError: expected expression, got '<' - first line

I’m using CodeIgniter framework and I want to make a chained drop-down with JavaScript code. Then I get this error:
SyntaxError: expected expression, got '<' //first line
But my first line is <!DOCTYPE html> and my file type is PHP not JavaScript, here is my JavaScript code:
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputBody">Body Number</label>
<select name="inputBody" id="inputBody" onchange="javascrip: ambildata(this.value);" class="form-control" required="required">
<?php foreach ($body as $bd) { ?>
<option value="<?php echo $bd->bodynumkids ?>" ><?php echo $bd->bodynumkids ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-6">
<label for="inputKiddie">Kiddies Name</label>
<!-- <div class="form-label-group"> -->
<input type="text" name="inputKiddie" id="inputKiddie" class="form-control" placeholder="ex. Super Cop" required="required">
<!-- </div> -->
</div>
<script type="text/javascript">
function ambildata(x) {
$.ajax({
type:'POST',
url :'<?php echo base_url("Repairpaint/chained"); ?>',
jsonp : 'callback',
dataType: 'jsonp',
data :{ '#inputBody' : x},
success: function(response){
console.log(response);
var len = response.length;
if(len > 0){
var tampil = response[0].namakids;
$('#inputKiddie').text(tampil);
} else {
$('#inputKiddie').text('wek');
}
}
})
}
</script>
</div>
</div>
And here the controller :
public function chained()
{
$dataKiddie = $this->input->post('inputBody');
$where = array('bodynumkids'=> $dataKiddie);
$response = $this->Model_repairpaint->chaincb('kiddiejadi', $where)->result();
echo json_encode($response);
}
I have searched similar questions and solutions around Stack Overflow but I found nothing. Can anyone help me find out the solution?

AJAX call PHP same page and reload option values

i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you

Email input is not taking email address as valid input in newsletter subscribe box

I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.

How can i submit hidden values to php using AJAX

i am trying to send some values from html form to php page.
here in the form i have some values which are hidden.and one text field which its value has to be passed to php page.
index.php:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="friend-invite.php" method="get">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="submit" name="submit" value="Invite" class="btn btn-primary">
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
friend-invite.php:
<?php
include('_header.php');
$user_email = $_GET['friendemail'];
$invited_by = $_GET['invitename'];
$invite_link = $_GET['invite-url'];
$product_name = $_GET['invite-product-name'];
if (isset($user_email, $invited_by, $invite_link, $product_name)){
sendInvitation($user_email,$invited_by,$invite_link,$product_name);
} else {
echo "Are you trying to do something nasty??";
}
function sendInvitation($user_email,$invited_by,$invite_link,$product_name)
{
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined(EMAIL_SMTP_ENCRYPTION)) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->IsHTML(true);
} else {
$mail->IsMail();
}
$mail->From = EMAIL_VERIFICATION_FROM;
$mail->FromName = $invited_by;
$mail->AddAddress($user_email);
$mail->Subject = SHOP_INVITE;
$link = $invite_link;
$mail->Body = $invited_by." ".FRIEND_INVITE_PRODUCT."<a href='".$link."'>".$product_name."</a>";
if(!$mail->Send()) {
$this->errors[] = MESSAGE_VERIFICATION_MAIL_NOT_SENT . $mail->ErrorInfo;
return false;
} else {
return true;
}
}
?>
AJAX function:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
the friend-invite.php page is getting the values that has been passed to it and check if the values has been set, if it has been set then it will call the php function sendInvitation() with the parameters. now all these things are happening pretty good.but i want to do it through AJAX. how can i do that.
You forgot to give your hidden fields an id:
echo '<input type="hidden" name="invitename" id="invitename" value="'.$_SESSION["user_name"].'">' ;
...
Change your index.php as:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="button" id="btn-submit" name="submit" value="Invite" class="btn btn-primary" />
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
And change AJAX function as:
$(function () {
$('#btn-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
We do not need a submit button in form if we using AJAX.
Dude you are simply making your code complex ... you are doing form submit + ajax submit .I think there you are going wrong.
Just try these:
Remove action="friend-invite.php" from your form tag and try . if this does not help than make your button input type button or use button tag. just try all these it should work.
If all this does not work than give id and name to your form ,,and use to submit as:
$(function() {
$("#form_id").on("submit", function(event) {
Try all these

AJAX improvement for validation

SO i have this piece of AJAX that work as it should be but i want to add some validation to it.I dont want it to send empty information.The AJAX is done for a comment system.It takes the value from the form and then with php it inserts it to the databse. The Problem i am haveing is that it just insert empty comment to the database
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm()
{
var comment = document.getElementsByName('comment').value;
if (comment == "" )
{
alert("Please fill in all the fields");
return false;
}
else
{
return true;
}
}
</script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" onsubmit="return validateForm();">
<label>New Comment</label>
<textarea name="comment" class="comment"> </textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
My AJAX code.I have tried to do some validation but it doesnt work properly and i dont know what is wrong with it.I am quite new to AJAX so not rlealy able to debug it myself.
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('.comment');
if (!comment.val()){
alert('You need to write a comment!');
}
else{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
});
});
My php code to insert into the database.
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
include('connection.php');
$connection = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['username'];
$postId = $_POST['postid'];
$comment = $_POST['comment'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tblcomments`
(`Content`,`UserID`,`PostID`,`Timestamp`)
VALUES (
'$comment','$userId','$postId',
CURRENT_TIMESTAMP)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>
You never call the function validateForm()
And this part
if (!comment.val()){
alert('You need to write a comment!');
}
will always pass if there is a input field with the class comment, even if it's empty. You could do something like:
//send ajax request
if(validateForm()===false){
alert('You need to write a comment!');
return false;
}
else{
....
You could try to change the comment.val() to comment.text() since you are using a textarea and see if that solves your problem. The change is to be modified in your js code

Categories

Resources