submit form to a php file with angular - php

i would like to submit my form to a php file
var myApp = angular.module('myApp',[]);
myApp.controller('FormController', function($scope, $http) {
$scope.task = {
group: 'fix',
showme: true,
select1: 'basique',
select2: 'micro',
select3: '1',
select4: '1',
select5: 'jour'
};
var server = 'http://localhost/myserver.php?cd=add';
var parameters;
$scope.submit = function(form) {
angular.forEach($scope.task, function(value, key) {
if(value) {
if(key === 'date') {
value = new Date(value).getTime();
}
parameters += '&'+key+'='+value;
}
});
console.log(server+parameters);
//$http.post(server+parameters)
//.success(function(result) {
// console.log("success", result);
//})
//.catch(function(error) {
// console.log("error", error);
//})
}
})
this is the codpen codepen
is this valid?
the result at should be http://localhost/myserver.php?cd=add'name='&'describe='

You are create query string using foreach() and pass with server url but. you are use $http.post(). you have to use $http.get() if you want pass with server url.
Below example with help
$scope.submitForm = function($valid)
{
myobject = {'email' : $scope.user.email, 'pass' : $scope.user.pass};
Object.toparams = function ObjecttoParams(obj)
{
var p =[];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
url: WSURL + '/login',
method: "POST",
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config)
{
}
}).error(function (data, status, headers, config)
{
});
}

Related

how do i send data to php from AngularJS controller?

I'm suffering a lot trying to do this, in words:
Trying to send a token to a myfunction.php so it can do it's job, then make it return 2 variables so I can use em in my Javascript controller (Made with angularJS).
So far i heard I should use $http, but I can't understand how I should do this
create an angularjs service and use it in your controller.
here is the service which can provide Create, read, write and delete functionality:
app.service("MainService", ['$http', function ($http) {
this.getItems = function (url) {
return $http.get(url);
};
this.getItem = function (id, url) {
return $http.get(url + "/" + id)
};
this.post = function (itemToCreate, url) {
var request = $http({
method: "post",
url: url,
data: itemToCreate
});
return request;
};
this.put = function (id, itemToChange, url) {
var request = $http({
method: "put",
url: url + "/" + id,
data: itemToChange
});
return request;
};
this.delete = function (id, url) {
var request = $http({
method: "delete",
url: url + "/" + id
});
return request;
};
}]);
next add this service as a dependency to your controller and use it's methods like this:
app.controller("MyCtrl", ['$scope', '$rootScope', '$timeout', 'MainService', function ($scope, $rootScope, $timeout, MainService) {
//Get All Items::
$scope.GetItems = function () {
var getAllItems = MainService.getItems("YOUR_API_URL_FOR_GET_ITEMS");
getAllItems.then(function (response) {
$scope.items = response.data;//use items with ng-repeat in you html code
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Create New Item::
$scope.Create = function () {
//CREATE an Object and send it via post request. for example:
var category = new CategoryObject($scope.Title, $scope.Description);
var promisePost = MainService.post(category, "YOUR_API_URL_FOR_Post_Item");
promisePost.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Edit an Item::
$scope.Edit = function () {
//CREATE an Object:
var category = new CategoryObject($scope.Title, $scope.Description);
//Then set it's Id
category.Id = $scope.CategoryId;
var promisePut = MainService.put($scope.CategoryId, category, "YOUR_API_URL_FOR_Put_Item");
promisePut.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Delete an Item::
$scope.delete = function (id) {
var promiseDelete = MainService.delete(id, "YOUR_API_URL_FOR_Delete_Item");
promiseDelete.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
}
}]);

Joomla/PHP/Ajax - ajax validate username in registration form

I am trying to do AJAX username verification in joomla registration form in table com_users. I have ajax validate custom fields and this works fine. But when I try anythink (name, username, mail) validate in table com_users, response is NULL (request is ok.)
here is my js with inputmask plugin:
// START #username
var input_username = document.getElementById("jform_username");
var inputParent_username = $(input_username).parent();
$(input_username).inputmask('*{4,40}',{
greedy:false,
placeholder:'_',
allowPlus: false,
allowMinus: false,
definitions: {
'*': {
validator: "[0-9A-Za-z#_-]"
}
},
oncomplete: function () {
$(inputParent_username).addClass("complete").removeClass("incomplete");
$.ajax({
type:"POST",
timeout:3000,
url:"/components/MY_COMPONENT/check_username.php",
dataType:"json",
data: $('#jform_username').serialize(),
beforeSend: function(){
$('#jform_username').siblings(".fa").removeClass("fa-exclamation-circle").addClass("fa-cog fa-spin");
},
success: function(data) {
var obj = JSON.parse(data);
obj=data;
console.log(obj);
if(obj == 0) {
$('#jform_username').siblings("i").removeClass("fa-cog fa-spin fa-check-circle").addClass("fa-times-circle-o");
$('#jform_username').addClass("valid-fail").removeClass("validate").css({"color":"#cf0404"});
$(inputParent_username).addClass("valid-fail").removeClass("validate");
} else if(obj == 1) {
$('#jform_username').siblings("i").removeClass("fa-cog fa-spin fa-times-circle-o").addClass("fa-check-circle");
$('#jform_username').addClass("validate").removeClass("valid-fail").removeAttr("style");
$(inputParent_username).addClass("validate").removeClass("valid-fail");
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
},
onincomplete: function () {
$(inputParent_username).addClass("incomplete");
}
});
// END #username
why is this happening? joomla block requests to com_users or just me totally stupid?

500 (Internal Server Error) in Laravel

Please help. I have this jQuery code
$('.modal-footer').on('click', '.edit', function() {
var serializedData = $(".form-horizontal").serialize();
var criscore = new Array();
$('input[name^=criscore]').each(function(){
criscore.push({score:$(this).val(), criid:$(this).data('criid')});
});
for (var key in criscore) {
var score = criscore[key].score;
var criid = criscore[key].criid;
//console.log(score +" s "+ criid);
$.ajax({
method: 'post',
url: '/judges/candidates/scorecandidates',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'_token': $('input[name=_token]').val(),
'canId': $('input[name=canId]').val(),
'catId': $('input[name=catId]').val(),
'criId': criid,
'score': score,
'judgeId': $('input[name=judgeId]').val()
},
success: function(data) {
console.log(data);
}
});
}
});
and in my controller is
public function scorecandidates(Request $req)
{
$data = new Score();
$data->canId = $req->canId;
$data->catId = $req->catId;
$data->criId = $req->criId;
$data->score = $req->score;
$data->judgeId = $req->judgeId;
$data->save();
return response()->json($data);
}
my problem is that it is still keeps having an 500 (Internal Server Error)
Even though I already put the csrf token is different ways.. Can any body help me?
Thank you

Run two ajax calls at the same time?

If I have one ajax call with a long foreach loop where I update a text file, and at the same time I want to read that file and display changed content from the first call by another second call, how can I achieve that?
When the first runs, the second waits until the first one has finished.
I want to run the first and second at the same time. In the second call, every second I want to check the state inside the file created by the first call - something like a progress bar.
function startTimer(){
timer = window.setInterval(refreshProgress, 1000);
}
function refreshProgress(){
$.ajax({
type: "POST",
url: '/index.php?/system/run_progress_checker',
dataType:"json",
success: function(data)
{
console.log(data);
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
function completed() {
//$("#message").html("Completed");
window.clearInterval(timer);
}
$(".systemform").submit(function(e) { //run system
$.when(startTimer(),run_system()).then(function(){});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function run_system(){
$("#leftcontainer").html("");
$("#leftcontainer").show();
$("#chartContainer").hide();
$(".loading").show();
var sysid = $(".sysid:checked").val();
var oddstype = $(".odds_pref").val();
var bettypeodds = $(".bet_type_odds").val();
var bookie = $(".bookie_pref").val();
if (typeof oddstype === "undefined") {
var oddstype = $(".odds_pref_run").val();
var bettypeodds = $(".bet_type_odds_run").val();
var bookie = $(".bookie_pref_run").val();
}
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,
data: {
system : sysid,
showpublicbet : showpublicbet }, // serializes the form's elements.
dataType:"json",
success: function(data)
{
console.log(data);
$("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
systemradiotocheck();
});
$("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');
$("#resultcontainer").show();
$("#leftcontainer").html(data.historic_table);
$("#rightcontainer").html(data.upcoming_table);
var count = 0;
var arr = [];
$("#rightrows > table > tbody > tr").each(function(){
var row = $(this).data('row');
if(typeof row !== 'undefined'){
var rowarr = JSON.parse(JSON.stringify(row));
arr[count] = rowarr;
$(this).find('td').each(function(){
var cell = $(this).data('cell');
if(typeof cell !== 'undefined'){
var cellarr = JSON.parse(JSON.stringify(cell));
arr[count][6] = cellarr[0];
}
});
count ++;
}
});
if(oddstype == "EU" && bookie == "Bet365"){
$('.bet365').show();
$('.pinnacle').hide();
$('.ukodds').hide();
}
if(oddstype == "EU" && bookie == "Pinnacle"){
$('.pinnacle').show();
$('.bet365').hide();
$('.ukodds').hide();
}
if(oddstype == "UK"){
$('.bet365').hide();
$('.pinnacle').hide();
$('.ukodds').show();
}
if(bookie == "Pinnacle"){
$(".pref-uk").hide();
}
else{
$(".pref-uk").show();
}
$(".loading").hide();
runned = true;
var options = {
animationEnabled: true,
toolTip:{
content: "#{x} {b} {a} {c} {y}"
},
axisX:{
title: "Number of Games"
},
axisY:{
title: "Cumulative Profit"
},
data: [
{
name: [],
type: "splineArea", //change it to line, area, column, pie, etc
color: "rgba(54,158,173,.7)",
dataPoints: []
}
]
};
//console.log(data);
var profitstr = 0;
var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
var counter = 0;
for (var i in parsed)
{
profitstr = profitstr + parsed[i]['Profit'];
//console.log(profitstr);
var profit = parseFloat(profitstr.toString().replace(',','.'));
//console.log(profit);
var event = parsed[i]['Event'].toString();
var hgoals = parsed[i]['Home Goals'].toString();
var agoals = parsed[i]['Away Goals'].toString();
var result = hgoals + ":" + agoals;
var date = parsed[i]['Date'].toString();
var bettype = parsed[i]['Bet Type'];
var beton = parsed[i]['Bet On'];
var handicap = parsed[i]['Handicap'];
//alert(profitstr);
//alert(profit);
//options.data[0].name.push({event});
counter++;
options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
}
$("#chartContainer").show();
$("#chartContainer").CanvasJSChart(options);
$(".hidden_data").val(JSON.stringify(data.export_array));
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Backend part is not so important because it works.
Sounds like a great case for jQuery's $.when $.then. In the first part, the $.when, you'll have the first ajax call, and when that is finished... you can port the data from the first part to the $.then part. For example:
$.when(
//perform first ajax call and pass this data to the 'then'.
$.ajax(
{
type: "POST",
url: "<<insert url>>",
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
).then(function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
$.ajax(
{
type: "POST",
url: "<<insert url>>",
data: params,
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
});
}
});

I want to send data with HTTP request from node js file to PHP file like AJAX but it is not working and i am not getting response from the other side

app.get('/curl', function(request, response) {
var data = querystring.stringify({
name : "bob"
});
var options = {
host: 'localhost',
port: 80,
path: 'http://matricore.com/curl_data/index.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(response) {
console.log('STATUS: ' + response.statusCode);
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write('data\n');
req.write('data\n');
response.send(data);
req.end();
});
I have been trying to post some static data to some url but it's not working, need help.
There is issue with your http request. Host in options should be domain name and path is endpoint's relative path to domain name.
app.get('/curl', function(request, response) {
var data = querystring.stringify({
name : "bob"
});
var options = {
host: 'matricore.com',
port: 80,
path: '/curl_data/index.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(response) {
console.log('STATUS: ' + response.statusCode);
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write('data\n');
req.write('data\n');
response.send(data);
req.end();
});
UPDATE 3
This would work for sure
var request = require('request');
app.get('/curl', function (req, res) {
request({
method: 'POST',
url:'http://matricore.com/curl_data/index.php',
form: {name:'bob'}
},function(err,httpResponse,body){
res.send(body);
});
});

Categories