ajax post method error - javascript

In the following example I am able to pass JSON representation of the country list and display it but I cannot display the message "Could not find any countries". Could you please check the code below:
Controller:
if ($this->model_abc->did_get_country_list($user_id)) {
$country["results"]= $this->model_abc->did_get_country_list($user_id);
echo json_encode($country);
}
else {
$country = array('message' => "Could not find any countries" );
echo json_encode($country);
}
JS file:
$.post('cont/get_country_list', function (country) {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
},
"json").error(function() {
$( "#country_list_is_not_got").text(country.message);
});
Update:
I changed my code as following and now I get thise error from console: Uncaught TypeError: Cannot read property 'length' of undefined.
JS file:
$.post('cont/get_country_list', function (country) {
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});

The error-function is only called when the server responses with a 500-HTTP code (or 404, 403 or a timeout etc.). You are returning just valid JSON with a normal HTTP status-code, so the success-function is called. Within that success-function you should check if there was a message or not:
$.post('cont/get_country_list', function (data) {
if (data.message !== undefined) {
$( "#country_list_is_not_got").text(data.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});

You're not setting an error reply code in the case where no countries are found, so it's not treated as an error by jQuery.
else {
header("HTTP/1.1 500 Error");
$country = array('message' => "Could not find any countries" );
echo json_encode($country);
}
Also, your error function needs to get the data from its parameter:
.error(function(xhr) {
country = $.parseJSON(xhr.responseText);
$( "#country_list_is_not_got").text(country.message);
});

Related

$.post never receives a response

I'm a fairly inexperienced coder, and am seeking help on why I'm not receiving a response to my $.post command.
From the output, (i think) the post is correctly submitting the PHP page, and the PHP correctly creates a JSON file with the values I expect. The issue is that my callback never seems to fire.
I never receive a log message of "Function Response", therefore, I don't think the post is ever entering the callback.
I've read lots and lots, and attempted a bunch of solutions, including some AJAX. But after about 10 hours, I'm stumped. My $.post is based on the this guide: Save JavaScript variables to PHP/MySQL DataBase Securely with Ajax Post
Thanks for any help you can shed on this.
I'm testing the code on a Windows most recent WAMP Server.
index.php (relevant bit)
$('#radarDropdown').change(function () {
currentRadarId = $('#radarDropdown').val();
var radSel = document.getElementById('radarDropdown');
var currentRadarName = radSel.options[radSel.selectedIndex].text;
document.getElementById('radarSelectedLabel').innerHTML = currentRadarId;
document.getElementById('radarSelectedName').innerHTML = currentRadarName;
getBacks(currentRadarName, processResponse);
// getBackground(currentRadarName);
console.log('Start request');
// document.getElementById('returnBackground2').innerHTML = back1;
// get background image filename for this radar.
});
function getBacks(currentRadarId, callbackFn) {
console.log('Enter getBacks');
$.post(
"getBackgrounds.php",
{radarBOMId: currentRadarId},
function(response) {
console.log('function response');
processResponse(response);
},'json');
};
function processResponse(response){
console.log('Entered processResponse');
console.log(response);
var backgroundFile = response.background;
var locationsFile = response.locations;
var roadsFile = response.roads;
var riversFile = response.riverBasins;
var railFile = response.rail;
var rangeFile = response.range;
var topoFile = response.topography;
var catchFile = response.catchments;
var wthrDistrictsFile = response.wthrDistricts;
var waterwaysFile = response.waterways;
document.getElementById('returnBackground2').innerHTML = backgroundFile;
};
});
getBackrounds.php:
<?php
header('Content-type: application/json');
require_once('dbconnect.php');
$typesArray = array(
'background',
'catchments',
'locations',
'rail',
'range',
'riverBasins',
'roads',
'topography',
'waterways',
'wthrDistricts',
);
$idval = mysqli_real_escape_string($connection, $_POST['radarBOMId']);
foreach ($typesArray as $i => $value) {
$sql = 'SELECT backfilename, backtype FROM InUseRadarsBackgroundsView WHERE productidbom ="'. $idval. '" and backtype = "'.$value.'"';
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$value] = $row["backfilename"];
//console.log('Processed row ' & $i);
}
echo json_encode($response);
} else {
echo " 0 results";
}
}
?>
POST response:
{"background":"IDR503.background.png"}{"catchments":"IDR503.catchments.png"}{"locations":"IDR503.locations.png"}{"rail":"IDR503.rail.png"}{"range":"IDR503.range.png"}{"riverBasins":"IDR503.riverBasins.png"}{"roads":"IDR503.roads.png"}{"topography":"IDR503.topography.png"}{"waterways":"IDR503.waterways.png"}{"wthrDistricts":"IDR503.wthrDistricts.png"}
This is not the complete answer, but try to add other callbacks (e.g. fail callback) to check if some errors occur when you make this POST. Here is an example of how this can be done :
$.post( "example.php", function(data) {
alert( "success" );
})
.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
})
.always(function() {
alert( "finished" );
});

Get specific section of AJAX response

When i inspect the response from my AJAX request to index.php, I get back some data that i want (some json, a return value i need the value of) but also a load of HTML as the index.php class is used to call a view which is responsible for loading up some HTML.
Here is the first two lines of the response:
{"returnVal":"registered"}<!DOCTYPE html>
<html lang="en">
Due to my code being MVC, i cannot just create a separate file to handle the AJAX request, so i need a way for my login.js class (where the AJAX request is generated) to go through the whole response and find the value of "returnVal" that I need. Do you know of a way I can do this?
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
if(!document.getElementById("usernameField")) { // If we have no username field on this page, we are just logging in
loginData = "email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "loggingIn";
urlPath = "index.php";
} else { // we are registering
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
}
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert(result); // i need to get the value of 'returnVal' from the response
if(result.returnVal=="registered") {
document.getElementById('notification').innerHTML = "You have been registered";
} else if (result.returnVal=="username") {
document.getElementById('notification').innerHTML = "Username already taken";
} else if (result.returnVal=="email") {
document.getElementById('notification').innerHTML = "Email already taken";
} else if (result.returnVal=="notRegistered") {
document.getElementById('notification').innerHTML = "Please enter registered email";
} else if (result.returnVal=="loginFail") {
document.getElementById('notification').innerHTML = "Please enter correct password";
} else if (result.returnVal=="loggedIn") {
$('#myModal').modal('hide');
document.getElementById('loginButton').innerHTML = "Account Settings";
} else { // Something wrong, tell us
//alert(result);
}
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
})
})
}
index.php
<?php
ini_set("log_errors", 1);
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
}
}
$view->Begin();
?>
Ultra simple way is just exit() after you echo the json so the view never gets sent. If this controller is never intended to render a view get rid of $view->Begin();
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
exit();
}
}
This is a (messy but still) way to extract the data you need.
But please consider my first comment. You should do it the other way round.
var result = '{"returnVal":"registered"}<!DOCTYPE html>someother grap';
var n = result.indexOf("<!DOCTYPE");
var jsonString = input.substring(0, n);
var json = JSON.parse(jsonString);
console.log(json);
// your values are here:
// json.returnVal;
This relies on the strict convention, that every return has a '

How to check if page is published

to check if page is published using server side code i should use this snippet:
PublishingPageCollection pages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
foreach (PublishingPage page in pages)
{
if(!page.ListItem.File.Level == SPFileLevel.Published)
return;
// logic
}
How could i do the same but using Javascript in SharePoint?
According to SP.Publishing.PublishingWeb Methods the method GetPublishingPages is not supported in JSOM API.
But you could consider the following example to determine whether page is published or not using JSOM API
function getPublishingPages(success,error)
{
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Pages');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ctx.load(items,'Include(File)');
ctx.executeQueryAsync(function() {
success(items);
},
error);
}
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
getPublishingPages(printPagesInfo,logError);
});
function printPagesInfo(pages)
{
pages.get_data().forEach(function(item){
var file = item.get_file();
var pageStatus = file.get_level() === SP.FileLevel.published ? 'published' : 'not published';
console.log(String.format('Page {0} is {1}', file.get_name(),pageStatus));
});
}
function logError(sender,args){
console.log('An error occured: ' + args.get_message());
}

asynchronous HTTP (ajax) request works in script tag but not in js file

I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});

send data (POST) from jquery to controller in cakephp

Well,
The problem is that I always get the same error "anonymous function" is because when I want to send data via post these never find the Controller or the path to the Controller, I have proven with three ways to send data in the JS.
validate.js
$(document).ready(function(){
var route ="<?php echo Router::Url(array('controller' => 'soyaproductorcompras','action' => 'validate_form', 0 => $this->request->params['pass'][0], 1 => $this->request->params['pass'][1]));?>";
$('#proveedor_carnet').blur(function(){
$.post(route,
{
field: $('#proveedor_carnet').attr('id'),
value: $('#proveedor_carnet').val()
},
handleNmeValidation
);
});
function handleNmeValidation(error){
if(error.length > 0){
if($('#proveedor_carnet-notempty').length === 0){
$('#proveedor_carnet').after('<div id="proveedor_carnet-notEmpty" class="error-message">' + error + '</div>');
}
}else{
$('#proveedor_carnet-notEmpty').remove();
}
}
});
here Ihave the code that I am Using for my validation the problem is the route.
first option:
var route ='/cake/soyaproductorcompras/validate_form';
second option
var route ='http://localhost:8080/cake/soyaproductorcompras/validate_form';
and the last
var route ="<?php echo Router::Url(array('controller' => 'soyaproductorcompras','action' => 'validate_form', 0 => $this->request->params['pass'][0], 1 => $this->request->params['pass'][1]));?>";
I see similar problems but do not apply, like this.
this is the controller validate form:
public function validate_form()
{
$this->loadModel('SoyaProductorCompra');
$this->loadModel('SoyaProveedor');
$this->autoRender = FALSE;
if ($this->request->is('ajax')) {
$proveedor=$this->data['SoyaProductorCompra'][$this->params['form']['field']]=$this->params['form']['value'];
$existe = $this->SoyaProveedor->find(
'first',
array(
'fields' => array(
'SoyaProveedor.id'
),
'conditions' => array(
'SoyaProveedor.id' => $proveedor
)
)
);
if(empty($existe)){
//return false;
echo "no existe el usuario";
}else{
//return true;
echo "el usuario existe";
}
}
}
error complete
POST http://localhost:8080/cake/soyaproductorcompras/%3C?php%20echo%20Router::Ur…pass%27][0],%201%20=%3E%20$this-%3Erequest-%3Eparams[%27pass%27][1]));?%3E 404 (Not Found) jquery.js:9666
jQuery.ajaxTransport.send jquery.js:9666
jQuery.extend.ajax jquery.js:9211
jQuery.each.jQuery.(anonymous function) jquery.js:9357
(anonymous function) VM811 validation.js:4
jQuery.event.dispatch jquery.js:4624
jQuery.event.add.elemData.handle

Categories