AngularJS insert page refresh - php

I wish to add a record in MySQL database through AngularJS and PHP. the record is added successfully but the AngularJS effect is not seen. that is the page is not automatically refreshed. below is the code was given:
controller:
$scope.add = function() {
var elem = angular.element($element);
var dt = $(elem).serialize();
//alert($element);
console.log($(elem).serialize());
$http({
method: 'POST',
url: 'php/add.php',
data: dt,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status) {
$scope.status = status;
$scope.data = data;
console.log(data);
data.push(this);
$scope.products = data; // Show result from server in our <pre></pre> element
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
index.html
<li ng-repeat="product in products" ng-model = 'products'>
{{product.description}}|{{product.name}} | edit | delete
<input type="hidden" name="hdnid" ng-model="hdn" value="{{product.product_id}}"/>
</li>
add.php
<?php
include 'connect.php';
mysql_select_db($database,$con);
$nm = $_POST['keywords'];
$desc = $_POST['desc'];
$query = "INSERT INTO `product`(`name`,`description`) VALUES ('$nm', '$desc')";
$result = mysql_query($query) OR die(mysql_error());
?>
What should I do to automatically refresh the page
?

When you assign new array or modify existing to $scope.products, it will automatically list each product in the new/modified list in the html. You don't have to reload the page.
In your case the response data for the post should be json array and if it is not, it wont work.
Something like mysql_query($query).toJSON should work.
If you want refresh the page ( for some non -angular reasons), you should explicitly do it in the success of the http call. Remember the GET/POST calls made using the $http wrapper are ajax calls.
example: http://jsfiddle.net/Y3b3H/12/

Related

how to get response of clicked captcha as a variable

I want to include google recaptcha in my login page.
Normally, I collect variables from various inputs and sent them using ajax to prologin.php for proccessing.
But don't know how to get response of clicked captcha, what kind of responses are possible (true, false, or... what ?), to proccess them also.
login.php
<script src='https://www.google.com/recaptcha/api.js'></script>
<input type='text'...>
<input type='checkbox'...>
<div class="g-recaptcha" data-sitekey="6Ld..."></div>
<div id='btnlogin'>LOGIN</div>
login.js
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = ...; // what ?
$.ajax({
url: 'prologin.php',
...
});
Any help?
You have to use grecaptcha.getResponse() to get the user's response. And as a sidenote, use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'prologin.php',
...
});
...
});
Here's the reference: https://developers.google.com/recaptcha/docs/verify
Update(1): Yes, you have to send user's response to backend PHP page prologin.php and get it verified there. So roughly, your AJAX and backend PHP code would be like this:
AJAX:
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = grecaptcha.getResponse();
$.ajax({
type: 'POST',
url: 'prologin.php',
data: {a: a, b: b, captchaResponse: captchaResponse};
success: function(data) {
// reset the reCaptcha
grecaptcha.reset();
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
...
});
prologin.php
<?php
//your site secret key
$secret = 'YOUR_SECRET_KEY';
if(isset($_POST['captchaResponse']) && !empty($_POST['captchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['captchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
}else{
// failure
}
}
?>
Google recaptcha's response is sent with name g-recaptcha-response. This is also class name and ID for an input (textarea). So you can try any of these:
$('#g-recaptcha-response').val();
$('form .g-recaptcha-response').val();
$('form [name="g-recaptcha-response"]').val();

Ajax update table with php content

How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.

How to update values in my DB with values from <select> tags - (Not $_POST)

I want to take values from <select> or <input> tags but using function onclick button, not using $_POST. I did a try but I have stack on syntax. In case of $_POST goes like this:
The button in to my form:
<input class="" name="submit" type="submit" value="UPDATE" />
My update query:
if (isset($_POST['submit']) or isset($_GET['submit'])){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = '".$_POST["name"]."',
lastname = '".$_POST["lastname"]."',
rank = '".$_POST["rank"]."'
WHERE id=1";
$db->setQuery($query);
$db->query();}
Now I am trying to do something like this:
The button in to my form:
<input class="" name="submit" type="submit" value="UPDATE" onclick="update()" />
My update query:
function update(){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = ???,
lastname = ???,
rank = ???
WHERE id=1";
$db->setQuery($query);
$db->query();}
But what is the syntax to call <select> and <input> tags names? Or their values in other words.
You're confusing the code that runs on the client-side (JS) with the code that runs on the server-side (PHP). JS runs after the PHP finished - so you can't "call" from JS to functions in PHP unless you submit a form (POST/GET) or use AJAX.
TYou must use $.ajax if you want to do this just by clicking a button and not refreshing or redirecting your browser
1) Read about http://api.jquery.com/jQuery.ajax/
2) add an eventhandler on your button onclick="update();"
3) create an ajax thingy like:
function request(variable1,variable2,variable3){
var request = $.ajax({
url: "/server.php", // The address of you php script that will handle the request
type: "POST", // Method type GET / POST in this case POST (Similar to form submission methods....)
data: { // What you send to the server 'VariableName' : VariableValue, in this case you assign the varaiables that were passed to the request function.
'var1': variable1,
'var2' : variable2,
'var3': variable3
},
dataType: "json" // The response type you expect from the server
})
request.done(function(msg) // Function being called when everything is ok and server sends back data
{
console.log(msg) // handle the reply / data
})
request.fail(function(jqXHR, textStatus) // Something went wrong...
{
console.log(textStatus); // See the error report
console.log(jqXHR);
})
request.complete(function(){
console.log("Ajax request complete!"); // This will always be executed when a request has completed even if it failed. (Executes after .done and .fail)
})
}
So you cound do this inside your update function that is being called whenever you click the button:
function update()
{
var val1 = $.('#selectbox').val();
var val2 = $.('#inputbox').val();
var val3 = $.('#textarea').val();
new request(val1,val2,val3);
}
The request / variables will be sent using the POST method so in you php script
you may process them as you would do with a form
if(isset($_POST['var1']) && isset($_POST['var2']) && isset($_POST['var3']))
{
$serverReply = doThings($_POST['var1'],$_POST['var2'],$_POST['var3']);
//and this is how you reply to your client/browser in json format
echo json_encode($serverReply);
}
Make sure to Check more in Depth tutorials regarding ajax comunication.
There are plenty around on the net.
onclick called function javascript
function javascript implements with ajax
example:
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

edit in angularjs using php

i wish to fetch the values to be edited, in the textbox, i.e. 1st the textboxes will be empty, then when user clicks on the edit link the values should be filled in the textbox. User can change the values, click on save button and the new values will be updated. following is the code:
html code:
Save
controller:
$scope.fetch = function(id) {
var elem = angular.element($element);
var dt = $(elem).serialize();
dt = dt+"&id="+id;
dt = dt+"&action=fetch";
alert(dt);
console.log($(elem).serialize());
$http({
method: 'POST',
url: 'php/products.php',
data: dt,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status) {
//~ $scope.status = status;
//~ $scope.data = data;
$scope.rs = data;
console.log($scope.rs); // Show result from server in our <pre></pre> element
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
products.php:
if($action == 'fetch') {
$query = '
SELECT
*
FROM
product
WHERE
`product_id` ="' . $_POST['id'] . '"
';
$result = mysql_query($query) OR die(mysql_error());
$data = array();
$row = mysql_fetch_assoc($result);
echo json_encode($row);
//print_r($row);
}
this code is not working- when user clicks on edit link of any user, the textboxes get filled with the value- Object object. If ti print the value then it gets printed but when i try to assign it to the textbox, it gets filled with Object object.
where am i getting wrong? how do i solve this?
Don't use jQuery to get/set fields anymore if you're using Angular.
<input type="text" ng-model="field1">
Controller:
//set
$scope.field1 = obj.field1;
//get
var f1 = $scope.field1;
You forgot to use the angular.fromJson function when receiving the response
.success(function(json, status) {
data=angular.fromJson(json);
//~ $scope.status = status;
//~ $scope.data = data;
$scope.rs = data;
console.log($scope.rs); // Show result from server in our <pre></pre> element
})
You might want to take a look into AngularPHP and save some time,

jQuery ajax call won't update mysql after pressing back button

I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!

Categories