Angularjs ensuring the json posted data has been transmitted - javascript

I am trying to send data from a Angularjs app to php in order to insert it into mysql db .
I have the index.html that contains the script,getUser_api.php page and insert.php page
I hav not error in console but I failed insert into mysql db.
So Is there any way to ensure if json data has been transmitted or nor
var app = angular.module("app",['ui.router']);
app.controller("insertCtrl", function($scope,$rootScope, $http) {
$scope.insert = function() {
$http.post(
"getUser_api.php", {
'Customer_Name': $scope.Customer_Name,
'Cust_mail': $scope.Cust_mail,
'Cust_Address': $scope.Cust_Address
}) ;
}
});
My insert.php page
<div class="well col-xs-8 col-xs-offset-2" style="margin-top: 10%" ng-controller="insertCtrl">
<form>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" ng-model="Customer_Name">
</div>
<div class="form-group">
<label> mail</label>
<input type="text" class="form-control" ng-model="Cust_mail">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" ng-model="Cust_Address">
</div>
</form>
<button class="btn-block btn-info" ng-click="insert()">Insert</button>
</div>
getUser_api
<?php
include('config.php');
$result=mysql_query('select * from customers');
$data['results']=array();
while($row=mysql_fetch_assoc($result)){
array_push($data['results'],$row);
}
if(count($data['results'])>0)
$data['status']='OK';
else
$data['status']='Z-Result';
echo json_encode($data);
?>

If you want to check manually, you can check it in the browser - developer tools in XHR tab.
In case if you want to catch error in the js end you can do:
var dataToSend = {
'Customer_Name': $scope.Customer_Name,
'Cust_mail': $scope.Cust_mail,
'Cust_Address': $scope.Cust_Address
};
var req = {
method: 'POST',
url: 'getUser_api.php',
data: JSON.parse(JSON.stringify(dataToSend))
};
$http(req).then(function (response) {
//handle success
}, function (error) {
//handle error
});
How to check manually in browser:
Open Chrome and press F12 for developer options
Click on Network
Click on XHR
Now in your html page click on the button which will call your inser method.
Your request will be displayed like following
Click on the request sent
Click headers
You will be able to see your Json in Request payload

Related

Insert data from multiple text boxes into sql via ajax

Not sure of the best way do this.
On my page I have the following (which pulls a list of custom questions from my database set by a user)
PHP PAGE THAT SHOWS THE QUESTIONS / COVER LETTER TEXT AREA
$questions = $this->db->get_where("applicationquestions",
["opportunity_id" => $contact->id]);
$questionsfound = $questions->num_rows();
$questions = $questions->result();
<? foreach ($question as $q):?>
<div class="form-group">
<label for="<?echo $q->id;?>" class="control-label"><? echo $q->label;?
>:</label>
<input type="text" class="form-control" id="<?echo $q->id;?>" name="<?echo $q->id;?>">
</div>
<?endforeach;?>
and using ajax / javascript i am passing information via POST
** THE JS **
$("#apply").click(function(e) {
e.preventDefault();
var oppid = "<?echo $opportunity->id;?>";
$.ajax({
url:
"https://MYSITEHERE/submitapplication",
method: "POST",
data: {oppid:oppid}}); });
What i am wondering is the best way to get then insert the questions id and the users answer into my database through this method.
** Submit Application File / Function **
public function submitapplication() {
$insert['opportunity_id']= $this->input->post('oppid');
$insert['user_id']= is_user_logged_in();
$insert['time']= time();
$insert['coverletter']= $this->input->post('coverletter');
$this->db->insert("applications", $insert);
// here i would need it to submit the answers from the question textboxes into the table applicationanswers along with the question id
}
HTML THAT IS DISPLAYED AFTER PHP HAS LISTED QUESTION FIELDS
<form id="applyform" class="">
<div class="row">
<div class="col-md-6 col-xs-12">
<label>Cover Letter</label>
<textarea class="form-control" id="coverletter" name="coverletter" rows="7" placeholder="Start typing a cover letter"></textarea>
<div class="form-group">
<label for="1" class="control-label">Have you sold web design before?:
</label>
<input type="text" class="form-control" id="1">
</div>
<div class="form-group">
<label for="2" class="control-label">Do you like monkeys?:</label>
<input type="text" class="form-control" id="2">
</div>
</div> </div>
</form>
If you are using more than one item in your form, I would suggest using
var data = $('form').serialize();
This will pass all of the form values to your php script and then you can use php to insert them.
$("#apply").click(function(e) {
e.preventDefault();
var oppid = "<?echo $opportunity->id;?>";
var data = $('form').serialize();
$.ajax({
url:
"https://MYSITEHERE/submitapplication",
method: "POST",
data: {formdata:data}}); });
You would then just parse the data in your php

Mithril ajax sending empty inputs

I'm trying to send a POST request through ajax and Mithril.js using CodeIgniter. But for some reason the input always is empty. I have tried with a regular ajax post request and that works fine, but Mithril doesn't.
m.request({
method: "POST",
url: "http://localhost/index.php/login",
data: {
username: $("#login-username").val(),
password: $("#login-password").val()
}
})
.then(function(result) {
console.log(result)
})
And the php
public function login()
{
$username = $this->input->post('username');
die($username);
}
It always prints "null" in console. Any ideas?
UPDATE:
<form class="uk-form-stacked uk-margin-remove" id="login-form" method="post" action="index.php/login">
<fieldset class="uk-fieldset">
<div class="uk-margin">
<div class="uk-inline uk-width-1-1">
<span class="uk-form-icon" uk-icon="icon: user"></span>
<input class="uk-input" id="login-username" name="username" type="text" placeholder="Username">
</div>
</div>
<div class="uk-margin">
<div class="uk-inline uk-width-1-1">
<span class="uk-form-icon" uk-icon="icon: lock"></span>
<input class="uk-input" id="login-password" name="password" type="password" placeholder="Password">
</div>
</div>
<div class="uk-margin" style="margin-top:10px">
<label ><input class="uk-checkbox" type="checkbox"> Remember me</label>
</div>
<input type="submit" class="uk-button uk-button-primary uk-width-1-1" value="Login">
</fieldset>
</form>
Routes:
$route['login']['post'] = 'Users/login';
That code will send a JSON body to the server, not a form submission. I'm guessing your PHP code expects the data to be formatted like a <form> would send it, so for that you'd want to use a FormData instance.
var data = new FormData();
data.append("username", document.querySelector("#username").value);
data.append("password", document.querySelector("#password").value);
m.request({
method: "POST",
url: "https://httpbin.org/post",
data: data
})
.then(function(result) {
console.log(result)
})
I also set up a JsBin where you can see this working & poke at it.
https://jsbin.com/gififo/2/
try print the data to be able to see it i the console .
public function login()
{
$username = $this->input->post('username');
echo $username;
}
I don't know if you have define a route (in app/config/route.php) but, actually you are pointing to the default controller.
If you are trying to send your request to, for exemple, the login method of the users controller, your request path should be http://localhost/index.php/users/login
I also recommand you to use the base_url function instead of a simple string, which is far more easier when you deploy your app on the real server.
So, I propose to change this line
url: "http://localhost/index.php/users/login",
By
url: <?= json_encode(base_url("/users/login")) ?>,
For this function work, you should have load the URI helper, in your controller __construct or directly in your current method :
$this->load->helper('URI');

$http not working in Angularjs 1.x

I am stuck with angular's all type of $http requests I am trying to hit the rest API with $http but my code ran through it and do not show any call in chrome network tab. I am using python simplehttpserver for my project execution.
Below is the code of the service I am trying to hit
HTML CODE
<form class="form-horizontal" method="post" ng-submit="loginModel.login()">
<div class="form-group">
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Username" ng-model="loginModel.username"/>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="password" class="form-control" placeholder="Password" ng-model="loginModel.password"/>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
Forgot your password?
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-info btn-block">Log In</button>
</div>
</div>
</form>
Controller Code
module.exports = function ($scope,$rootScope,$state,crudFactory,$http,$resource) {
var vm = this;
vm.login = login;
function login() {
var userDetail = {
username:vm.username,
password:vm.password
};
$http({
method: 'POST',
url:'http:example.com',
data:userDetail,
}).then(function (response) {
console.log(response)
}, function (response) {
});
}
I have inject $http in my controller and have also tried to hit the API with $resource but nothing is happening when i hit the service on click event.
I have tried this with core javascript and it works fine but why its not working $http or $resouce
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.example.com/", false);
xhr.send();
console.log(xhr.status);
Please help me on this
Thanks
It looks like your URL is not formatted correctly, and you aren't doing anything in the event of an error.
$http({
method: 'POST',
url:'http://example.com',
data:userDetail,
}).then(function (response) {
console.log(response)
}, function (response) {
console.log('error response', response);
});
This will at least show something in the console if there is an error.
If the url change still isn't working, check your browser developer console's network tab to see if the request is being made and if so, if it is timing out (stuck in pending state)

why is this not printing to console

Hello I have a form with some data what I want is when I click a button a jQuery function executes and print all that data in the console so here is my form code:
<form>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="fecha">Fecha:</label>
<input type="text" name="fecha" id="fecha" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="total">Total:</label>
<input type="number" min="0" name="total" id="total" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="abono">Abono:</label>
<input type="number" min="0" name="abono" id="abono" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="resta">Restante:</label>
<input type="text" name="resta" id="resta" class="form-control" readonly>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-5">
<button type="submit" value="actualizar" class="btn btn-info" id="actualizar">Actualizar Datos
<span class="glyphicon glyphicon-refresh"></span>
</button>
</div>
</div>
</form>
and this is my script include
<script src="js/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="js/actualizar_orden.js"></script>
this is actualizar_orden.js file:
//Al clickear boton actualizar ordenes
$('#actualizar').click(function(){
var orden = parseInt($('#norden').val());
var id_tecnico = parseInt($('#id_tec').val());
var memoria = $('#memoria').val();
var chip = $('#chip').val();
var tapa = $('#tapa').val();
var falla = $('#falla').val();
var observacion = $('#observacion').val();
var estado = $('#estado').val();
var fecha = $('#fecha').val();
var total = parseInt($('#total').val());
var abono = parseInt($('#abono').val());
var ajaxUrl = 'actualizar_ordenes.php';
data = { 'norden': orden, 'id_tec': id_tecnico, 'memoria': memoria, 'chip': chip, 'tapa': tapa,
'falla': falla, 'observacion': observacion, 'estado': estado, 'fecha': fecha,
'total': total, 'abono': abono };
console.log(data);
/*$.post(ajaxUrl, data, function(response){
if(response.empty)
alert("Datos no actualizados");
else{
alert("Datos Actualizados.");
location.reload();
}
}) */
});
I just want to log that data into console to check if I'm getting it right.. but instead of log that to console my page is refreshing automatically so I can't see the output in the console... I've tried with both mozilla and chrome but still nothing
I see You want to submit form using jquery, without refreshing screen.
simply do following in Your js file:
$(function() {
$('form.ajax').submit(function(e) { // catch submit event on form with ajax class
e.preventDefault(); // prevent form act as default (stop default form sending)
var $form = $(this); // caching form object to variable
var data = $form.serializeArray(); // getting all inputs from current form and serializing to variable
var url = $form.attr('action'); // reading forms action attribute
console.log('DATA:', data);
$.post(url, data, function(response) { // posting form data to url (action)
console.log('RESPONSE:', response);
if(response.empty) {
alert("Datos no actualizados");
return;
}
alert("Datos Actualizados.");
$form.find('input, select').val(''); // resets form inputs
});
});
});
and change Your form tag to be like this:
<form class="ajax" action="actualizar_ordenes.php" method="post">
this example shows You that:
1) You can catch all form submits that has ajax class defined
2) no need to set exact url in js code (before it was hardcoded ajaxUrl variable). now it gets form action url from form attributes.
3) it does ajax post and if success, so You can redefine some wise behavior to make really flexible solution, and forget about writing custom code for each form submitting
isn't it flexible? (:
Everyform need some default action to do on submitting. When it's not set it reloads the page by default. So to prevent the refreshing, you should add some empty action to your <form> tag, like this:
<form action="javascript:void(0);">

AJAX Request when submitting form

I added to my form a special id which I would like to track. If this id is available in the form, an AJAX request should be initialised.
Form
{!! Form::open(['data-remote', 'action' => 'IncidentsController#store', 'id'=>'incidentEntryForm']) !!}
<div class="form-group">
{!! Form::label('city', 'Name:') !!}
{!! Form::text('city', null, ['class' => 'form-control']) !!}
</div>
(...)
Therefore I wrote this helper script:
Helper Script
(function() {
console.log("Helper OK");
var submitAjaxRequest = function(e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function() {
console.log("Submit OK");
$.publish('form.submitted', form);
}
})
e.preventDefault();
};
// forms marked with the "data-remote" attribute will submit, via AJAX.
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
The $.publish is a short script for PubSub Functionality I included as well.
PubSub
(function($) {
console.log('PubSub OK');
var o = $({});
$.subscribe = function() {
o.on.apply(o, arguments);
};
$.unsubscribe = function() {
o.off.apply(o, arguments);
};
$.publish = function() {
o.trigger.apply(o, arguments);
};
}(jQuery));
But when I press the submit button, the last line of the helper script does not seem to react. The function submitAjaxRequest is never called.
The script is included in my head section. For checking if this is loaded, I included the console.log at the beginning. I see the output. So it is running I think. But it does not react to the submit press in the form.
Update 1
When I try calling submitAjaxRequest() I get the error: Uncaught TypeError: Cannot read property 'preventDefault' of undefined
Update 2
The Form Code that is generated is this:
<form method="POST" action="http://dev.server.com/incidents" accept-charset="UTF-8" data-remote="data-remote" id="incidentEntryForm"><input name="_token" type="hidden" value="<TOKEN>">
<div class="form-group">
<label for="city">Notrufort:</label>
<input class="form-control" name="city" type="text" id="city">
</div>
<!-- Latitude Form Input -->
<div class="form-group">
<label for="street">Straße:</label>
<input class="form-control" name="street" type="text" id="street">
</div>
<!-- Notruftyp Form Input -->
<div class="form-group">
<label for="type">Notruftyp:</label>
<select class="form-control" id="type" name="type"><option value="1">CPR</option></select>
</div>
<!-- Notruf erfassen Form Input -->
<div class="form-group">
<input class="btn btn-primary form-control" type="submit" value="Notruf erfassen">
</div>
</form>
Update 3
I inserted a console.log at the beginning of the closure:
var submitAjaxRequest = function(e) {
console.log("submitAjaxRequest OK");(...)
And the function is being called. The console prints the message. So I think something is wrong with the event.
Update 4
So I tried to use the pubSub System to listen to this event. Therefore I
function reverseGeoCode() {
$.subscribe('form.submitted', function() {
console.log("OK");
})
}
But there is no reaction when I hit the submit button in the console. I used this function in a different script somewhere else on the page. Shouldn't it still react to the publish?

Categories