JSONP SyntaxError: missing ; before statement - javascript

I have on a controller a function on codeigniter which gets and checks image for my templates.
I have place a id="template" just after my thumbnail bootstrap div id template works with my script code.
Currently when I select theme I get a firebug error
Error Pop Up
SyntaxError: missing ; before statement
OK
{"image":"<img src=\\\"http:\/\/localhost\/codeigniter\/codeigniter-cms\/image\/templates\/default.png\\\" alt=\\\"\\\"\/>"}
Controller Image Function
public function template() {
$this->load->helper('html');
if (file_exists(FCPATH . 'image/templates/' . $this->configs->get('config_template') . '.png') == FALSE) {
$img = addslashes(img('image/no_image.png'));
echo json_encode(array('image'=>$img));
} else {
if($this->input->post('config_template') !== FALSE) {
$img = addslashes(img('image/templates/' . basename($this->input->post('config_template')) . '.png'));
echo json_encode(array('image'=>$img));
}
}
}
View
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-setting" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" for="input-template"><?php echo $entry_template; ?></label>
<div class="col-sm-10">
<select name="config_template" id="input-template" class="form-control">
<?php foreach ($templates as $template) { ?>
<?php if ($template == $config_template) { ?>
<option value="<?php echo $template; ?>" selected="selected"><?php echo $template; ?></option>
<?php } else { ?>
<option value="<?php echo $template; ?>"><?php echo $template; ?></option>
<?php } ?>
<?php } ?>
</select>
<div class="form-group">
<div class="col-lg-4">
<div class="img-thumbnail">
<div id="template"></div>
</div>
</div>
</div>
</form>
<script>
console.log('Jquery is working');
$('select[name="config_template"]').on('change', function () {
var template_name;
template_name = encodeURIComponent(this.value);
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: '<?=base_url('admin/setting/template');?>' + '/',
data: { config_template: template_name
},
complete: function () {
$('.fa-spin').remove();
},
success: function (data) {
$('.fa-spin').remove();
$('#template').html(data.image);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
})
</script>

Found out issue it was addslashes
old
public function template() {
$this->load->helper('html');
if (file_exists(FCPATH . 'image/templates/' . $this->configs->get('config_template') . '.png') == FALSE) {
$img = addslashes(img('image/no_image.png'));
echo json_encode(array('image'=>$img));
} else {
if($this->input->post('config_template') !== FALSE) {
$img = addslashes(img('image/templates/' . basename($this->input->post('config_template')) . '.png'));
echo json_encode(array('image'=>$img));
}
}
}
new
public function template() {
$this->load->helper('html');
if (file_exists(FCPATH . 'image/templates/' . $this->configs->get('config_template') . '.png') == FALSE) {
$img = img('image/no_image.png');
echo json_encode(array('image'=>$img));
}else
{
if($this->input->post('config_template') !== FALSE)
{
$img = img('image/templates/' . $this->input->post('config_template') . '.png');
echo json_encode(array('image'=>$img));
}
}
}

You are outputting JSON. Not JSONP. Change dataType: 'jsonp', to dataType: 'json',
Adding slashes to some HTML will break that HTML. You'll be putting \ characters in your image URLs and making them wrong. Remove all uses of the addslashes function. encode_json will do all the escaping you need.

Related

Ajax : response value is not the same as in the php file

I am currently working on a Wordpress project and I have a issue during an ajax request:
On my view, I have this button for displaying more articles on my page :
<input type="hidden" name="nbPages" value="<?php echo $nb_pages;?>">
<input type="hidden" name="pageActive" value="1">
<input type="hidden" name="termSlug" value="<?php echo $term_query->slug;?>">
.
.
.
<div class="product-bottom">
<img src="<?php echo get_template_directory_uri();?>/img/ajax-loader.gif" alt="" id="ajax-loader" style="display:none;">
<button class="btn btn-site-1" id="loadmore_bt">See more</button>
</div>
On my js file, I have this part that is called when the button is used
add_action('wp_ajax_ajax_loadmore', 'ajax_loadmore');
$(function () {
'use strict';
//AJAX LOAD MORE PRODUCTS
jQuery('body').on('click', '#loadmore_bt', function (e) {
e.preventDefault();
$('#ajax-loader').fadeIn(500);
var nbPages = jQuery('input[name="nbPages"]').val();
var activePage = jQuery('input[name="pageActive"]').val();
var termSlug = jQuery('input[name="termSlug"]').val();
jQuery.ajax({
type: 'POST',
dataType: "JSON",
data: {
'action': 'ajax_loadmore',
'nbPages': nbPages,
'activePage': activePage,
'termSlug': termSlug
},
url : ajaxurl,
success : function(response){
console.log('cool!');
console.log(response.newPageToDisplay);
}
})
In function.php , I have this function which is called :
function ajax_loadmore(){
.
.
// set query arg as $args_products
.
.
$products = new WP_Query($args_products);
$rendering = '';
if ($products->have_posts()) {
foreach ($products->posts as $key => $prod) {
$rendering .= "
<div>
<h2 class="card-title main-title-2">' . $prod->post_title . '</h2>
<p class="card-subtitle">' . get_field('reference', $prod->ID) . '</p>
</div>
<div class="card-txt">' . get_field('desriptif_court', $prod->ID) . '</div>
<button class="btn btn-site-1">More info</button>
</div>";
}
$json = array(
'reponse' => 'success',
'newPageToDisplay' => $rendering,
'pageloaded' => $pageToLoad,
'activePage' => $activePage,
);
echo json_encode($json);
}else{
echo "error";
echo json_encode(array(
'reponse' => $reponse
));
}
die();
}
My issue is: $rendering has not the same value than in the js response (as response.newPageToDisplay).
For exemple, on the first element of $rendering is $prod->post_title = 'PA80MP' , while the first element of response.newPageToDisplay is 'PA95'. Both are indeed existing values in my database.
TLDR : Ajax doesn't have the same value of variables as in the php file function that it calls.
Hope I explain well my problem ...thank you for helping!

ajax jquery form stopped sending emails

I have a form which was sending emails from the server before but all of a sudden it stopped working. I cant seem to figure out the issue. When I use the form without ajax then email works perfectly. I saw http 200 code in the dev tools and no errors. Any help would be much appreciated. Thank you.
html:
<form id="form1" class="form-action" action="" method="POST">
<input type="text" name="name" id="name" class = "name" required />
<input type="email" name="email" id="email" required />
<input type="text" name='company' id="company" class="company" required />
<textarea class= "message" name="message" id="message" required />
</textarea>
<script src="https://www.google.com/recaptcha/api.js"></script>
<div class="g-recaptcha" data-sitekey="x" data-callback="recaptcha"></div>
<button type="submit" id="submit-button">Submit</button>
<span class="success_message font-weight-bolder text-center hide" style="margin-left: 30px;">
message received.</span>
</form>
<script>
function reset_form(){
$("#form1")[0].reset();
}
function reset_success_message(){
$('.success_message').addClass('hide');
}
$(document).ready(function(){
$('#name').click(function () {
$('.success_message').addClass('hide');
});
$('.email').click(function () {
$('.success_message').addClass('hide');
});
$('.company').click(function () {
$('.success_message').addClass('hide');
});
$('#message').click(function () {
$('.success_message').addClass('hide');
});
$('#form1').submit(function (e) {
$('.success_message').addClass('hide');
e.preventDefault();
$.ajax({
url: 'serverside.php',
type: 'post',
data: $('#form1').serialize(),
success: function (response) {
if(response == 'submitted'){
reset_form();
$('.success_message').removeClass('hide');
}
}
});
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
serverside.php
<?php
$email_to = 'x#domain.com';
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true) {
mail($email_to, $email_subject, $email_content, "From:" . $email);
}
else
{
}
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
You seem to be missing the Recaptcha secrets. Removing the Recaptcha if condition it works fine.
<?php
$email_to = 'ahmed_rises#hotmail.com'; //-----------> Invalid Email Id was added here
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
//Recaptca Secrets are Missing?????? Random string passed!
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret="
.$recaptcha_secret."&response=".$_POST['g-recaptcha-response']); //-----> Also Recapta response from
//the form is also missing since there its not working and neither getting passed
$response = json_decode($response, true);
//Printed the Output in which it shows the recapta Error
echo "<pre>";
print_r($response);
//If you ae to remove the Recapta Condition, the mail will be send!
// if($response["success"] === true) {
echo "==========";
echo "email_subject:".$email_subject.", email:".$email.",email_to:".$email_to;
mail($email_to, $email_subject, $email_content, "From:" . $email);
echo "==========";
// }
// else
// {
// echo "Failed";
// }
echo "<br>";
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
Hope it helps :)

AJAX Post request working only on Web Console (Preview)

I have a really simple ajax request to "send" the ID of an element the user clicks on the webSite. The script is working only on the Web Console (in the Network -> Preview section). This happens in every browser.
here's the code:
AJAX REQUEST
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {
var itemid = event.target.id;
$.ajax({
type: 'post',
//url: "index.php",
data: {'itemid' : itemid},
cache : false,
async : true,
dataType: 'html',
success: function(data) {
alert('success');
},
failure: function(data) {
alert('failure');
}
});
});
</script>
PHP Function
<?php
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo "success";
$itemid = (int)$itemid;
echo $itemid;
} else{
echo "failure";}
?>
Can you help me with this?
Just adding the image to let you understand better.
UPDATED: Here's the full code, hope it's not too confusionary (still a beginner):
I'm getting the response correct but echo json_encode($d); is not printing.
Btw thank you very much for your support :)
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include '../includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n";
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "</script>";
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo "<script type='text/javascript'>\r\n";
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>
Here is what can work for you. If it does not work then please share your entire code and the response from PHP too.
// jQuery AJAX call should be something like this
$.ajax({
url: 'index.php',
data: {
"itemid": itemid
},
type: "post",
dataType: "json",
success: function(json) {
if(json.success) {
alert("Item ID is " + json.itemid);
} else {
alert("Item ID is " + json.itemid);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error :: " + textStatus + " :: " + errorThrown);
}
});
// PHP code can be like this
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo json_encode(['success' => true, 'itemid' => $itemid]);
} else {
echo json_encode(['success' => false, 'itemid' => 'Not available']);
}
Consider the following.
JavaScript
$("[class*='point']").click(function(e) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
PHP
<?php
$d = array();
if(isset($_POST['itemid'])){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
?>
In a lot of cases, it's better to pass JSON data back. It's easier for JavaScript to handle it. So we build an array of data that we want to pass back to AJAX request and encode it as JSON.
When we make the AJAX Post, PHP will result in a Successful response. You're welcome to catch an error, this would happen with 400 or 500 Status result from the PHP call. You can also see this in your Web Console.
We're going to get a JSON Object back from PHP, either:
{
result: "success",
itemid: 2
}
Or:
{
result: "error",
error: "'itemid' was not set."
}
In JavaScript, we can use dot notation to access the elements of the object. You can also access it like this:
if(data['result'] == "success")
Dot notation is advised.
Update 1
In your PHP File, you will want a different structure. You're going to have to perform some actions before the HTML is presented to the Browser.
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$itemid = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
$d;
// Connect to SQL
// Query DB for Table Data ...WHERE itemId = '$itemid'
// Store resultset to $d
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once "../grid.asp";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include 'includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n"
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>
Hope this helps.

How to insert PHP row record into AJAX url

I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});

Trouble w/ Form Processing using jQuery + PHP

I'm having the hardest time getting a simple form to process using jQuery and PHP. I've tried getting the data via $_POST, $_GET, and $_REQUEST but I guess I'm missing a simple line of code or a complete process altogether.
app.js
$(document).ready(function() {
$('#sucMsg').hide();
$('#errMsg').hide();
$('form').on('submit', function(event) {
event.preventDefault();
var form = $(this);
alert(form.serialize());
$.ajax(form.attr('action'), {
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: form.serialize(),
success: function(result) {
form.remove();
$('#sucMsg').append(result);
$('#sucMsg').fadeIn();
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
$('#errMsg').append(thrownError);
$('#errMsg').fadeIn();
}
});
});
});
formProcess.php
<?php
if ($_POST) {
echo "Posted something.";
} elseif ($_GET) {
echo "Getted something.";
} else {
echo "Nothing is working...";
}
$tagNumberPost = $_POST['inputTagNumber'];
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
$tagNumberRequest = $_REQUEST['inputTagNumber'];
$priceRequest = $_REQUEST['inputPrice'];
$makeRequest = $_REQUEST['inputMake'];
if (isset($_REQUEST['inputTagNumber'])) {
echo '$_REQUEST works...\n';
} elseif (isset($_POST['inputTagNumber'])) {
echo '$_POST works...\n';
} elseif (isset($_GET['inputTagNumber'])) {
echo '$_GET works...\n';
} else {
echo "Nothing is working...";
}
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
?>
What I'm expecting to get back is the all the echo's in my formProcess.php to print out in my #sucMsg div.
Why are you setting your contentType: as application/json? You do not need that. Remove it.
contentType: 'application/json', // remove this line
Just leave it to its default as application/x-www-form-urlencoded if your request is POST.
And in your PHP, $tagNumber is undefined.
if (isset(
$_POST['inputTagNumber'],
$_POST['inputTagNumber'],
$_POST['inputMake'],
)) {
$tagNumber = $_POST['inputTagNumber']; // define tagNumber
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
}

Categories