http_response_code() in php - php

I'm kind of new to php, I'm using angularJS on the front end that looks like this
app.controller('customersCtrl', function($scope, $http) {
$scope.element = function(num){
var element_id = num;
$http.get("customers.php",{params:{"id":element_id}}).then(function (response) {
$scope.myData = response.data;
});
};
});
PHP code
http_response_code(404);
header("Content-Type: application/json");
exit();
When element_id = 6 I want to fire the http_response_code. Only thing is I'm not seeing anything. The php was taken from the schools example. What am I doing wrong? How do I get the 404 message to display? Am I even thinking of this in the right context? I've some article online but nothing really helps me much. Thanks in advance.

What am I doing wrong?
You are not handling non-success status codes in your $http request.
If you want to get the 404 message then you need to handle the error in your error callback like so:
app.controller('customersCtrl',
function($scope, $http) {
$scope.element = function(num) {
var element_id = num;
$http.get("customers.php", {
params: {
"id": element_id
}
}).then(function(response) {
$scope.myData = response.data;
}, function(error) {
// this is where you handle your error
console.log(error);
});
};
});

Related

Attempting to delete contact with Axios inside of Vuejs

I am developing an app to store contact information and utilizing Vuejs and Laravel to do it. I am also using the axios library for CRUD functionality.
I have this error on axios.delete() I cannot figure out. This is my Contacts.Vue file:
<script>
export default {
data: function(){
return {
edit:false,
list:[],
contact:{
id:'',
name:'',
email:'',
phone:''
}
}
},
mounted: function(){
console.log('Contacts Component Loaded...');
this.fetchContactList();
},
methods: {
fetchContactList: function(){
console.log('Fetching contacts...');
axios.get('api/contacts').then((response) => {
console.log(response.data);
this.list = response.data;
}).catch((error) => {
console.log(error);
});
},
createContact: function(){
console.log('Creating contact...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.post('api/contact/store', params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
showContact: function(id){
let self = this;
axios.get('api/contact/' + id)
.then(function(response){
self.contact.id = response.data.id;
self.contact.name = response.data.name;
self.contact.email = response.data.email;
self.contact.phone = response.data.phone;
})
self.edit = true;
},
updateContact: function(id){
console.log('Updating contact '+id+'...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.patch('api/contact/'+id, params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
deleteContact: function(id){
axios.delete('api/contact/'+id)
.then(function(response){
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
}
}
}
</script>
I am getting a TypeError message saying that self.fetchContactList is not a function.
I know that its saying that the value is not actually a function. There is no typo in the function name. Did I call the function on the wrong object? Should I be using a different property name?
I used self.fetchContactList(); on adding and updating contacts, why will it not work with deleting the contact?
Do I need to add request headers? I didn't have to for the other requests.
If I simply remove self.fetchContactList() it will not function at all.
Despite the error, when I refresh the page, it deletes the contact, but I want the contact deleted upon clicking the delete button.
You don't have let self = this; line in deleteContact function, obviously you would get an error.
alternatively, you can use ES6 arrow functions to avoid assigning this to separate variable like this:
deleteContact: function(id) {
axios.delete('api/contact/'+id)
.then((response) => {
this.fetchContactList();
})
.catch((error) => {
console.log(error);
});
}

get json object from php to angularjs and print it without duplicate errors

https://localbitcoins.com/sell-bitcoins-online/{contry code}/.json
this is the content i get from my moudle in php and i want to print this list in angular so i can live update it
app.controller('list', function($scope, $http, $interval) {
$http.get('http://localhost/mvcang/list_it/sell/SWISH')
.then(function(response) {
$scope.values = response.data.profile;
});
});
this is the angular code i use to get the info from my localhost
how do i do so it prints the list i get dublicate error and when i do .profile i get nothing!
have any idées or solutions please help:D
app.controller('list', function($scope, $http, $interval) {
$interval(function () {
$http.get('http://localhost/mvcang/list_it/sell/SWISH')
.then(function(data) {
data = data.data;
if($scope.phones != data){
$scope.phones = data;
}
});
}, 1000);
});
worked it out it way a that i didnt understand that it was data in the json object

AngularJS service for php files

i am trying to create a service for angular which should get the data from a php that generates a json. Right now my service looks like this
fixEvents.service('contactService', function($http, $q) {
this.getallContact = function() {
var json = $q.defer();
$http.get('models/contact.getall.json')
.success(function(data) {
json.resolve(data);
})
.error(function() {
json.reject();
});
return json.promise;
};
});
and my controller looks like this
fixEvents.controller('contactCtrl', function($scope, contactService) {
$scope.title = "CONTACT";
$scope.jsonContact = contactService.getallContact();
$scope.showMessage = function() {
alert($scope.jsonContact.length);
}
});
the problem is my jsonContact does not get any result. It seems to be undefined. Is there something i did wrong? And by the way is there a better way to do this ? Thank you, Daniel!
You have to use .then back in the controller to work with the data:
var jsonContactPromise = contactService.getallContact();
jsonContactPromise.then(function(data) {
$scope.jsonContact = data
}, function(error) {
console.log("ERROR: " + error);
});

Backbone.js not rendering JSON -

I have to code:
window.TicketCollection = Backbone.Collection.extend({
model:Tickets,
url:"/index.php/tickets/viewJSON"
});
window.TicketsView = Backbone.View.extend({
tagName:'div',
initialize: function () {
this.model.bind("reset", this.render, this);
},
render:function(eventName){
_.each(this.model.models, function(ticket){
$(this.el).append(new TicketListItemView({model:ticket}).render().el);
},this);
return this;
}
});
window.TicketListView = Backbone.View.extend({
tagName: "li",
template:_.template($('#tickets-list-item').html()),
render:function (eventName){
$(this.el).html(this.template(this.model.toJSON));
return this;
}
});
var AppRouter = Backbone.Router.extend({
routes:{
"":"list"
},
list:function(){
window.alert("alright");
this.ticketList = new TicketCollection();
this.ticketLists = this.ticketList.get();
this.ticketListView = new TicketListView({model:this.ticketList});
$("#ticketListHolder").html(this.ticketListView.render().el);
},
});
var app = new AppRouter();
Backbone.history.start();
});
My php is as follows:
<?php header('Content-type: application/json');
echo json_encode(array("ticketID"=>"test", "ticketName"=>"1"));?>
The response from the php is:
[{"ticketID":"1","ticketName":"Fix the admin system"}]
HTML:
<div id="ticketListHolder">
#
</div>
<script type="text/template" id="tickets-list-item">
<div class="supTicket ticketHolder nobg">
<div class="issueType">
<span class="issueInfo"><%= ticketName %></span>
<span class="issueNum">[ #<%= ticketID %>] - <%= fullName %></span>
</div>
</div>
</script>
I get the error: Uncaught ReferenceError: ticketName is not defined, it appears that it's not parsing the json, instead reading it as one string block. Why is this error occuring, when my JSON is returning the correct data.
You don't use collection.fetch anywhere. Your router probably should look like this
var AppRouter = Backbone.Router.extend({
routes:{
"":"list"
},
list:function(){
window.alert("alright");
this.ticketList = new TicketCollection();
this.ticketListView = new TicketListView({
model:this.ticketList,
el:$("#ticketListHolder") // I directly assigned #ticketListHolder as the el
});
this.ticketList.fetch();
},
});
And a Fiddle with a mostly working version of your code http://jsfiddle.net/Cc9Ad/2/
Some points you should check:
your ListView and your ItemView were the other way round,
as Daniel Aranda said in his answer, try to use collections and models for their intended purpose,
this.model.toJSON should have been this.model.toJSON()
set defaults on your models, fullName is not defined and would break the templating engine if used in this state
The revised code
window.Tickets=Backbone.Model.extend({
defaults: {
fullName :"No full name"
}
});
window.TicketCollection = Backbone.Collection.extend({
model:Tickets,
url:"/index.php/tickets/viewJSON"
});
window.TicketsView = Backbone.View.extend({
tagName:'li',
template:_.template($('#tickets-list-item').html()),
initialize: function () {
},
render:function(eventName){
console.log
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
window.TicketListView = Backbone.View.extend({
initialize: function () {
this.collection.bind("reset", this.render, this);
},
render:function (){
this.collection.each( function(ticket){
$(this.el).append(new TicketsView({model:ticket}).render().el);
},this);
return this;
}
});
var ticketList = new TicketCollection();
var ticketListView = new TicketListView({
collection:ticketList,
el:$("#ticketListHolder")
});
// ticketList.fetch();
ticketList.reset([
{"ticketID":"1","ticketName":"Fix the admin system"},
{"ticketID":"2","ticketName":"The ticket 2"}
]);
Model is not the same than collection.
You are trying to use a Collection as a Model.
Check this example:
http://danielarandaochoa.com/backboneexamples/blog/2012/02/22/real-world-usage-of-a-backbone-collection/
Also to fix your specific issue, pass to your template an object instead of a Backbone.Model
$(this.el).html(this.template(this.model.toJSON()));
You was missing the parenthesis.
But as I said, I recommend you to read the article explaining how to use the collections.
I use JSON.parse() function to parse the data sent by the PHP.
var a = $.ajax({
url:"/index.php/tickets/viewJSON",
async:false,
cache:false
}).responseText;
jsonData = JSON.parse(a);
then use _.each to loop jsonData then push each data to your model.

jquery wont send with post method

nothing is being sent with $.post
function clicked()
{
var $contact_title=$("#contact_title");
var $contact_summary=$("#bbcode");
alert($contact_title.val());// How do I get the contents of the title
alert($contact_summary.val());// How do I get the contents of the textarea
$.post('jquery_send_admin.php',{ title:$contact_title, content:$contact_summary }, function(data){ alert("Message was sent") }, 'html');
}
I get exceptions in my console error..like the following:
UPDATE:
no data is inserted on the next page..why?!?
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
The following error happens:
Error: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no]
UPDATE:
Thats what I request from the page, which is triggered by jquery:
<?php
echo 'outside';
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
echo 'inside';
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
?>
You need to extract the values using the .val() method:
var $contact_title = $('#contact_title').val();
var $contact_summary = $('#bbcode').val();
var dataToPost = { title: $contact_title, content: $contact_summary };
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
var $contact_title=$("#contact_title").text();
var $contact_summary=$("#bbcode").text();
try to get the value/text instead of just the control.
var $contact_title=$("#contact_title").text();
or
var $contact_title=$("#contact_title").val();
Edit:
Not sure how it works in PHP but I use it with vb.net and there I need to give my controller name(aka file) and function so it becomes
$.post('myFile/myJSONFunction', {all-your-parameters});
So maybe thats why it wont post your data.
Something else you might want to look at is that your php might return different data than you are actually expecting him to return.
function clicked() {
var $contact_title = $("#contact_title");
var $contact_summary = $("#bbcode");
alert($contact_title.val()); // with the val
alert($contact_summary.val()); // with the val
$.post('jquery_send_admin.php', { title: $contact_title.val(), content: $contact_summary.val() }, function (data) { alert("Message was sent") }, 'html');
}
Instead of this posted by #Darin
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
use this
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert(data);
});
That will show the result of the echo statements in the alert box which could possibly help you debug the issue.
Oh my. jQuery bugs, PHP debugging bugs. I'll probably get down-rates for this answer... but sometimes, it helps to simply read the manuals if you're that lost that people have to help you cross the street: http://api.jquery.com/ & http://php.net/manual/

Categories