Currently my running program, when I click the submit new phone number button, my ajax shows a response pop up that is empty.
I don't have any running errors so I don't see the issue.
main index.php file:
case 'updatephone' :
include('assets/header.php'); // create top box
include('assets/sidemenu.php'); // create side menu
// use a template to display result
include('views/displayUpdatePhoneForm.php');
include('assets/footer.php'); // create footer
break;
case 'changephone' :
$sql = 'update members set mobilePhone=:mobilePhone where indID=:indID';
$phone = $_POST['mobilePhone'];
$values = array(':indID'=>$_POST['indID'], ':mobilePhone'=>$phone);
$stm = $db->prepare($sql);
$result = $stm->execute($values);
echo $result;
break;
displayUpdatePhoneForm.php
<h4>Changing Mobile Phone</h4>
<p>Enter new number: <input type='tel' id='newPhone' />
<button type='button' class='btn btn-primary' id='updatephone' >Change Phone</button>
</p>
script.js
$(document).ready(function(){
url = '/cs382/cookead06/final/final_app';
if ($('#uid').val() != '-1'){
$('#sign-in' ).hide();
$('#sign-out').show();
}
$('#p2').on('change', function(){
$('#form2').submit();
});
$('#p3').on('change', function(){
$('#form3').submit();
});
$('#p4').on('change', function(){
$('#form4').submit();
});
// validate user
$('#updatephone').on('click', function(){
var f_id = $('#uid').val();
var phone = $('#newPhone').val();
$.ajax({
type : 'post',
url : url + '/index.php?action=changephone',
data : 'indID=' + f_id + '&mobilePhone='+ phone,
success : function(response){
alert(response);
}
});
});
$('#signInBtn').on('click', function(){
var username = $('#username').val();
var password = $('#passwd').val();
var data_items = 'username='+username + '&passwd=' + password;
$.ajax({
type : 'post', // type: get or post
url : url + '/index.php?action=checklogin', // define server-side script
data : data_items, // define data to be sent
success : function(response){
if (response != -1){
// hide login information
$('#username, #passwd').val('');
$('#login-content, #sign-in').hide();
$('#sign-out').show();
// update the value of 'uid'
$('#uid').val(1);
// display user's name
$('#user-info').text(response);
$('#update-link').removeClass('hidelink').addClass('displaylink');
} else
alert("Invalid user");
}
});
});
});
Sorry, read wrongly..
I re-read it and I can see that you are printing $result that is = to $stm->execute($values); that is a sql query, if the query executes successfully, it won't show any message, only if you implemented an echo on the function execute..
Surprisingly, the issue was at line:
$sql = 'update members set mobilePhone=:mobilePhone where indID=:indID';
where members was suppose to cs_members(name of table)
Related
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();
I have a button on my page :
<button class="play"></button>
When I click on it, it launches the video via jQuery
$('.play').on('click',function(){
player.play();
});
But I also want to add PHP code to save the user ID in the database when he clicks on that button.
How can I mix PHP & jQuery? I'm not used to Ajax, is it the solution?
Thanks for your help!
add a function:
function add_to_db(user_id){
$.post('add.php', {userId: user_id}, function(response){
//do something with the response
r = JSON.parse(response);
if (r.status === 'error'){
//handle the error
alert(r.message);
}
});
});
when you play do the following
$('.play').on('click',function(){
player.play();
user_id = //however you chose to set this in the page
add_to_db(user_id);
});
your add.php:
//perform your db update or insert
//if successful:
$response['status'] = 'success';
//else:
$response['status'] = 'error';
$response['message'] = 'update was not successful';
//look into try/catch blocks for more detailed error messaging.
//then send the response back
echo json_encode($response);
Try using ajax
$('.play').on('click',function(){
player.play();
$.ajax({
type: "POST",
url: "some.php", // your php file name
data:{id :"id"}, //pass your user id
success:function(data)
{
if(data==true)
alert("success");
else
alert("error");
}
});
}
some.php
<?php
$success=false; //Declare and initialize a variable
// do your code to update your database
//and check if the database is updated , if so set $success=true
echo $success;
?>
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.
Below I have an jquery with ajax code where it will display change the values of course details by inserting the new data from one set of inputs (the set of inputs where the user has made changes) to another set of inputs (the set of inputs where it states the course's current details). Also the course's drop down menu changes to accommodate the new change if it needs to change:
function submitform() {
$.ajax({
type: "POST",
url: "updatecourse.php",
data: $('#updateCourseForm').serialize(),
success: function(html){
$("#targetdiv").html(html);
//Get and store the new course number and name.
var newCourseNo = jQuery("#newCourseNo").val();
var newCourseName = jQuery("#newCourseName").val();
var newDuration = jQuery("#newDuration").val();
//Set your current course number and name to your number and name.
jQuery("#currentCourseNo").val(newCourseNo);
jQuery("#currentCourseName").val(newCourseName);
jQuery("#currentDuration").val(newDuration);
//Find the currently selected course and update it.
var selectedOption = jQuery("#coursesDrop option:selected");
var label = selectedOption.text().split(" - ");
selectedOption.text(newCourseNo + " - " + newCourseName);
$('#targetdiv').show();
}
});
}
Now $("#targetdiv") is the id where it displays the success or error message retrieved from the php page which is accessed through ajax:
updatecourse.php:
...//mysqli code
echo "<span style='color: green'>Course details have been updated:<br/>" . $newcourseno . " - " . $newcoursename . "</span>";
}else{
echo "<span style='color: red'>An error has occured, Course Details have not been updated</span>";
}
But the problem I am having is that if the error message from the php code is retrieved in the jquery, then I don't want the course details to make the edit in jquery to accomodate the current course text inputs to insert the new details. I only want that to happen if the success message appears.
If the error message appears I want no change to happen, the current course details inputs and the new course details input simply remain the same before the submit.
But how can this be achieved?
Get response as JSON (so that you can manipulate the response after you get result...)
try this,
JQUERY
$.ajax({
type: "POST",
url: "updatecourse.php",
data: $('#updateCourseForm').serialize(),
dataType:'json'; //get response as json
success: function(result){
if(result.errorflag){
//do your stuff on getting error message
var newHtml="<span style='color: red'>"+result.msg+"</span>"
$("#targetdiv").html(newHtml); //i am displaying the error msg here
}else{
//you got success message
var newHtml="<span style='color: green'>"+result.msg+"</span>"
$("#targetdiv").html(newHtml);
//Get and store the new course number and name.
var newCourseNo = jQuery("#newCourseNo").val();
var newCourseName = jQuery("#newCourseName").val();
var newDuration = jQuery("#newDuration").val();
//Set your current course number and name to your number and name.
jQuery("#currentCourseNo").val(newCourseNo);
jQuery("#currentCourseName").val(newCourseName);
jQuery("#currentDuration").val(newDuration);
//Find the currently selected course and update it.
var selectedOption = jQuery("#coursesDrop option:selected");
var label = selectedOption.text().split(" - ");
selectedOption.text(newCourseNo + " - " + newCourseName);
$('#targetdiv').show();
}
}
});
PHP
json_encode() to send the reponse as json.... send response as array with the error flag to check if it is a succcess or error and the msg to print...
...//mysqli code
echo json_encode(array('errorflag'=>false,'msg'=>"Course details have been updated:<br/>" . $newcourseno . " - " . $newcoursename));
}else{
echo json_encode(array('errorflag'=>true,'msg'=>"An error has occured, Course Details have not been updated"));
}
User any flag in the JSON response on the basis of that update the DOM
EX:
$.ajax({
type: "POST",
url: "updatecourse.php",
dataType: 'json',
data: $('#updateCourseForm').serialize(),
success: function(json){
$("#targetdiv").html(json.htmlContent);
//Get and store the new course number and name.
if(json.status=="success"){
var newCourseNo = jQuery("#newCourseNo").val();
var newCourseName = jQuery("#newCourseName").val();
var newDuration = jQuery("#newDuration").val();
//Set your current course number and name to your number and name.
jQuery("#currentCourseNo").val(newCourseNo);
jQuery("#currentCourseName").val(newCourseName);
jQuery("#currentDuration").val(newDuration);
//Find the currently selected course and update it.
var selectedOption = jQuery("#coursesDrop option:selected");
var label = selectedOption.text().split(" - ");
selectedOption.text(newCourseNo + " - " + newCourseName);
$('#targetdiv').show();
}else{
//show whatever mesage u want
}
}
});
Do like this in Success Block
success: function(html){
var indexValue = html.indexOf("An error has occured");
if (parseint(indexValue ) < 0 ) {
return false;
}
$("#targetdiv").html(html);
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,