Apologies for this question if something out there covers this. I searched and found many relevant posts which has allowed me to get to this point.
I have a form snippet with 1 input box and a button and a div for a status message:
<div>
<div>
<div>
<input id="discount_code"name="discount_code" placeholder=" Enter discount code."></input>
</div>
<div>
<a class="btn btn-xs btn-primary" id="btn-validate">Validate</a>
</div>
</div>
<div id="status_msg" style="border: 1px solid black"></div>
</div>
Then I have the following bits of javascript:
The bit that triggers based on the click:
$('#btn-validate').on('click', function(e) {
e.preventDefault();
validateCode(11); // "11" is a php-provided ID variable
});
The javscript with the ajax call:
function validateCode(eventID) {
var codeValue = $("#discount_code").val();
if (FieldIsEmpty(codeValue)) { // outside function that exists/works fine
$('#status_msg').html('Enter a discount code.').fadeIn(500);
$('#status_msg').fadeOut(2500);
//bootbox.alert("Please enter discount code to validate.");
} else {
$.ajax({
type: 'POST',
cache: false,
async: true,
url: '/include/discount_validation.php',
dataType: 'json',
data: {
event_id: eventID,
discount_code: codeValue
},
beforeSend: function() {
$('#status_msg').html('');
$('#status_msg').fadeIn(0);
},
success: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
});
}};
And I have a PHP file that, suffice it to say, is working and producing the following json outputs based on the input:
// do php database things...
header('Content-Type: application/json');
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => "$message"));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => "$message"));
}
In the above, I have bootbox.alert lines commented out but when they are active, the box appears and the message is as I would expect it to be.
And lastly, the first condition that triggers if the input box is empty, both fires the alert (when not commented) AND changes the text of #status_msg.
I put the border in to verify visibility and #status_msg is visible but just is not set when either success or error fires.
First check if you getting an object in the response
in the success add
alert(JSON.stringify(data));
If it shows the object then you are good to go else check the php file where you creating the object.
If object is recieved in the success of ajax then you need to parse the json object using jQuery.parseJSON
For Eg:
response = jQuery.parseJSON(data);
Now you have a javascript object with name response.
Now use it
response['status'] or response['message'] in the success of the ajax.
check the code
first discard : " from php code $message variable
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}
then use the response on font end success function :
success: function(data) {
$('#status_msg').html(data.message);
$('#status_msg').fadeIn(0);
},
Set your data like this inside ajax().
success: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
AND
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}
Related
I have a php code that post value using ajax to another php page , but the value provided is not reflecting in UI nor in console .
$(document).ready(function() {
$('#CustomerName').click(function() {
customername = $(this).text();
load_data(customername);
// console.log(customername); // works
});
function load_data(Customername) {
// console.log(Customername); // works
$.ajax({
url: "getvalueafterclick.php",
method: "POST",
data: {
Customername: Customername,
EnvironmentType: "BA"
},
success: function(data) {
$('#result').html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
}
});
<?php
// perform actions for each file found
foreach (glob("CustomerConfigFiles/*.json") as $filename) {
echo ' <a href="#" id ="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.substr(substr($filename,20), 0, -5).'</a>';
}
?>
So when i give console.log in function and onclick , it returns value but when i try to pass CustomerName , it just returns null .
getvalueafterclick.php
<?php
$pat =$_POST['EnvironmentType'];
$lat =$_POST['Customername'];
echo "<script>console.log('Customer Name: " . $lat . "');</script>";
echo "<script>console.log('ENVIRON: " . $pat . "');</script>";
?>
Here is output i get :
Change id to class for CustomerName , I have added/ changed your code, see if it helps to solve your problem.
$(document).ready(function() {
// changed # to . for class
$('.CustomerName').click(function() {
customername = $(this).text();
load_data(customername);
// console.log(customername); // works
});
function load_data(Customername) {
// console.log(Customername); // works
$.ajax({
url: "getvalueafterclick.php",
method: "POST",
data: {
Customername: Customername,
EnvironmentType: "BA"
},
success: function(data) {
$('#result').html(data);
// console added to check what it is giving
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
}
});
<?php
//your code
// perform actions for each file found
// here in link change id to class for customer name
foreach (glob("CustomerConfigFiles/*.json") as $filename) {
echo ' <a href="#" class="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.substr(substr($filename,20), 0, -5).'</a>';
}
// my testing code
$data =["a","b","c","d","e","f","g","h"];
// perform actions for each file found
// here in link change id to class for customer name
foreach ($data as $filename) {
echo ' <a href="#" class="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.$filename.'</a>';
}
?>
getvalueafterclick.php
<?php
$pat =$_POST['EnvironmentType'];
$lat =$_POST['Customername'];
echo "Customer Name:" . $lat . "-";
echo "ENVIRON: " . $pat ;
?>
I am searching this and other sites for hours now, so I'm getting pretty desperate. No code from many questions with the same topic here works.
I need to insert data into the database and display a message after it is done. Also, I am using AJAX with jQuery so it would be asynchronous. It works just fine, the data gets inserted, but no response message shows.
I am a beginner at PHP and can't understend why this won't work. Relevant code below.
PHP function call:
if(isset($_POST["function"]) && !empty($_POST["function"]) && $_POST["function"] == "cl-add") {
$dbb->addMember("MyUsername", $_POST["name"]);
//$dbb is a DataBaseBroker instance
}
PHP function from the Broker:
function addMember($username, $ime) {
$query = "INSERT INTO clan";
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
$result = $this->mysqli->query($query);
if ($result) {
echo("You added a member: ".$ime);
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: ".mysqli_error($connection);
echo $response;
}
}
JQuery function declarations:
var addMember = function(name, responseFn) {
if (name === "") {
alert("Please enter a name");
return;
}
$.ajax({
type : 'POST',
url: '../includes/layout/cl.php',
dataType : 'json',
data : {
'name' : name,
'function' : 'cl-add'
},
success : function(data) {
responseFn(data); //not working, should alert
}
});
}
var responseCallback = function(data) {
alert(data);
}
And inside $(document).ready():
$(document).on('click', '#cl-add', function(evt) {
var name = $("#cl_frm input").val();
addMember(name, responseCallback);
});
On your code:
dataType : 'json',
The Ajax request is waiting for a JSON response but you are giving a text response.
You should change the dataType: to text or html depending on your needs.
dataType : 'html',
or
dataType : 'text',
PHP changes:
<?php
function addMember($username, $ime)
{
$query = "INSERT INTO clan";
$query .= " (username, ime) ";
$query .= "VALUES ('" . $username . "','" . $ime . "');";
$result = $this->mysqli->query($query);
$response = null;
if ($result) {
$response = "You added a member: " . $ime;
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: " . mysqli_error($connection);
}
echo $response;
exit;
}
Change dataType parameter to 'text'. Also you can alert an object in JavaScript, actually you are not trying to alert an object but i just wanted to mention it.
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";
}
I have a form with an id or 'display'. It has one value to send which is a select item that I gave an id of 'services' to.
I want to send the value of 'services' to a function I have created in a seperate php page. The page is called 'functs.php' and the function name is called 'searchResults'.
The 'searchResults' function works, this much I know. It queries a database and outputs 8 seperate php echo statements. I have ran the PHP function and know it works. I know the issues is with my javascript because, well, I am not the greatest at JavaScript and usually shy away from it.
As of right now, the code is not doing anything. My form has its own action to post to a seperate php page.
<form id="display" action="resultPage.php" method="POST">
I am trying to use the javascript/ajax to instantly update the contents of a div BUT if the user has jscript turned off, I want the form to ppost to the alternate page. Here is my jscript.
$(document).ready(function() {
$('#display').submit(function(e) {
var formData = $('#services');
$.ajax({
type: "POST",
url: functs.php,
data: '$formData',
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
e.preventDefault();
return false;
});
});
PHP CODE:
<?php
function searchResults()
{
require 'db_config.php';
$sql= "SQL CODE HERE"
$theStyle = <<<HERE
"height:100%;
width:70%;
margin:4% AUTO 0;
padding:1.75em;
font-size:1.25em;
border-radius:5em;
color:white;
background-color:#b72027;
;"
HERE;
while ($row = mysql_fetch_array($result))
{
echo ("<div style = $theStyle>");
echo ("<table>");
echo ("<tr><td>" . $row["0"] . "</td></tr>");
echo ("<tr><td>" . $row["1"] . "</td>");
echo ("<tr><td>" . $row["2"] . ", " . $row["3"] . " " . $row["4"] . "</td></tr>");
echo ("<tr><td>Phone: " . $row["5"] . "</td></tr>");
echo ("<tr><td>" . "" . $row["6"] . "" . "</td></tr>");
echo ("<tr><td>" . $row["8"] . " " . $row["9"] . ", " . $row["10"] . "</td></tr>");
echo ("<tr><td>" . $row["11"] . "</td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td>" . $row["7"] . "</td></tr>");
echo ("</table>");
echo ("</div>");
echo ("<br />");
}
}
?>
Your JS code has a couple of issues. The PHP script name needs to be a string inside of quotation marks, and the formData variable has an unnecessary "$." Try this:
$(document).ready(function() {
$('#display').submit(function(e) {
e.preventDefault();
var formData = $('#display').serialize();
$.ajax({
type: "POST",
url: 'functs.php',
data: formData,
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
});
});
I would like to show the geozone in the registration account step as dropdown menu, just like the zone (region). But the value of the geozone is dependent to what customer choose in the zone (region).
The Picture
In the process, I already did some modifications to the controller, view, including controller. Just like in the pic below :
The geozone field is Kotamadya/Kabupaten.
But when I choose the region Aceh, the geozone field is not refreshed.
Error Message
I got error message like below :
SyntaxError: Unexpected token <
OK
<br />
<b>Fatal error</b>: Call to a member function
getGeozonesByZoneId() on a non-object in <b>
/home/........../catalog/controller/account/register.php
</b> on line <b>513</b><br />
The Code
In ../controller/account/register.php, I added some modifications as below :
public function zone() {
$json = array();
$this->load->model('localisation/zone');
$geozone_info = $this->model_localisation_zone->getZone($this->request->get['zone_id']);
if($geozone_info)
{
$this->load->model('localisation/geo_zone');
$json = array(
'country_id' => $geozone_info['country_id'],
'name' => $geozone_info['name'],
'code' => $geozone_info['code'],
'zone' => $geozone_info['zone_id'],
'geozone' => $this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id']),
'status' => $geozone_info['status']
);
}
$this->response->setOutput(json_encode($json));
}
line 513 is :
'geozone' => $this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id'])
I don't know what's wrong with the getGeozonesByZoneId function, because I think I already write the function correctly in ../model/localisation/geo_zone.php as below :
<?php
class ModelLocalisationGeozone extends Model {
public function getGeozone($zone_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "geo_zone WHERE geo_zone_id = '" . (int)$geo_zone_id . "'");
return $query->row;
}
public function getGeozonesByZoneId($zone_id) {
$geozone_data = $this->cache->get('geozone.' . (int)$zone_id);
if (!$geozone_data) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE zone_id = '" . (int)$zone_id . "'");
$geozone_data = $query->rows;
$this->cache->set('geozone.' . (int)$zone_id, $geozone_data);
}
return $geozone_data;
}
}
?>
and I already added javascript to register.tpl in view as below :
$('select[name=\'zone_id\']').bind('change', function(event, first_time) {
$.ajax({
url: 'index.php?route=account/register/zone&zone_id=' + this.value,
dataType: 'json',
beforeSend: function() {
$('select[name=\'zone_id\']').after('<span class="wait"> <img src="catalog/view/theme/default/image/loading.gif" alt="" /></span>');
},
complete: function() {
$('.wait').remove();
},
success: function(json) {
var html = '<option value=""><?php echo $text_select; ?></option>';
var selected = false;
if (json['geozone'] && json['geozone'] != '') {
for (i = 0; i < json['geozone'].length; i++) {
html += '<option value="' + json['geozone'][i]['geo_zone_id'] + '"';
if (json['geozone'][i]['geo_zone_id'] == '<?php echo $geo_zone_id; ?>') {
html += ' selected="selected"';
selected = true;
}
html += '>' + json['geozone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'geo_zone_id\']').html(html);
if(typeof first_time === "undefined" && selected) {
$("#register_details_form").validate().element('#register_details_form select[name="geo_zone_id"]');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
$('select[name=\'zone_id\']').trigger('change', ['first_time']);
anyone can help me to resolve this issue? or maybe have same experiences with me and willing to share your solutions to me?
thanks before in advance.
Use model_localisation_zone (defined variable) instead of model_localisation_geozone (not defined), or make sure the latter is defined.
if i am not wrong you are forgetting to load model Geozone in your register.php controller file add this line
$this->load->model('localisation/geozone');
to register.php
before calling function
$this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id'])