I'm working with Instagram's api, and I must validate a profile before form is submitted:
<button type="button" id="clickMe">Run It!</button>
<div id="data">
</div>
<script type="text/javascript">
$('#clickMe').click(function() {
$.ajax({
method: 'get',
url: 'php-script.php',
data: {
'username': '217380759',
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
</script>
php-script.php:
$access_token = "...";
$username = "...";
$url = 'https://api.instagram.com/v1/users/' . $username . '?access_token=' . $access_token;
$api_response = file_get_contents($url);
$record = json_decode($api_response);
$code = $record->meta->code;
if($code == 200) {
//user is valid, continue to next page
} else {
echo "invalid";
}
Any suggestions on verifying Instagram user, allowing user to continue without hitting submit again?
Just try this code :
success: function(data) {
if(data != 'invalid') {
location.href = "YOUR NEXT PAGE URL";
}
}
Related
I am trying to check if value exist in database in my CodeIgniter website using AJAAX. I have written the following code:
<input id="username" name="pincode" type="text" class="form-control" placeholder="Enter Pincode">
<input id="prodid" name="prodid" value="<?php echo $prodid;?>" type="hidden">
<button type="button" onclick="check_if_exists();" class="btn btn-primary">Check</button>
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {
username: username,
prodid: prodid
},
success: function(response) {
if (response == true) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
function filename_exists()
{
$username = $this->input->post('pincode');
$prodid = $this->input->post('prodid');
$exists = $this->product->filename_exists($prodid);
if ($exists) {
return true;
} else {
return false;
}
}
function filename_exists($prodid)
{
$this->db->select('*');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
I am only getting the message that the value doesn't exist even if the value is there in database.
You are using AJAX not the form submission method, so in back-end post() method won't work
To transfer a value from server in php, one method is echo, but return is wrong here.
Please rewrite your code like this
View
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
var transfer = [username,prodid];
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {result: JSON.stringify(transfer)},
success: function(response) {
if (response) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
Controller
function filename_exists()
{
$post = json_decode($_POST['result']);
$username = $post[0];
$prodid = $post[1];
$exists = $this->product->filename_exists($prodid);
echo $exists;
}
Modal
function filename_exists($prodid)
{
$this->db->select('id');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
if($query->num_rows()) return true;
}
enter code here
How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});
I have a problem after pressing the like button with javascript. It pops the empty alert window.
<script type='text/javascript'>
function like(btn) {
var username = '<?php echo $username ?>';
var dataString = 'username=' + username;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
ajaxjs.php file:
include ('./include/connect.php');
$username = $_POST['username'];
if ($username == "") {
echo "You are not logged in";
} else {
mysql_query("INSERT INTO likes VALUES('','$username')");
}
I want it to pop the window only when if ($username == "") { echo "You are not logged in";
But not if the ajaxjs.php ends up running the query. How do I keep it for echo, but prevent it for mysql_query("INSERT INTO likes VALUES('','$username')");?
You need to check html result in your javascript-code using if statement.
function like(btn) {
var username = '<?php echo $username ?>';
var dataString = 'username=' + username;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(html) {
if(html.length > 0) {
alert(html);
}
}
});
}
Instead of
alert(html);
Use
html.length && alert(html);
I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});
When submitting my form I need to check in the database whether chassis and pin exists. If it exists i need to display a pop up message through Ajax. This is my code. But i am not getting any pop up message if the data has been inserted or if there is any error.Can you guys help me figure out where I am going wrong? Thanks in advance for your help.
AJAX CODE :
<script type="text/javascript">
$(document).ready(function () {
$("#user_submit_form").submit(function () {
var user_data = $("#user_submit_form").serialize();
if ($('#chassis').val() == '') {
alert('Please enter chassis');
} else if ($('#pin').val() == '') {
alert('Please enter pin');
} else
{
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function (user_data) {
if (user_data == "Data inserted") {
alert("Data inserted");
} else {
alert("fail!");
}
}
}); // End ajax method
}
});
});
</script>
PHP CODE:
<?php
session_start();
$hostname = '*****';
$database = '****';
$username = '****';
$password = '*****';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT chassis,pin FROM checking_chassis WHERE chassis="'.$chassis.'" && pin="'.$pin.'" ');
if(mysql_num_rows($sql) == 1)
{
echo "Data inserted";
}
else
{
echo "Error";
}
?>
first do this after submitting and check
$("#user_submit_form").submit(function(e){
e.preventDefault();
});
and when alerting return false;
OR
pass data like this
$data = array(
'status' => 1,
'message' => 'Data inserted'
);
echo json_encode($data);
and in success function use
var json = $.parseJSON(user_data);
alert(json.message);
I am trying this now but I don't think that the value is getting returned. It is just printing the content of the else statement
<script type="text/javascript">
$(document).ready(function (){
$("#user_submit_form").submit(function(){
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
var pincode = new Array();
pincode = $('#pincode').val().split("");
if($('#chassis').val() =='')
{
alert('Please enter chassis');
}
else if($('#pin').val() =='')
{
alert('Please enter pin');
}
else
{
$.post("validate_user.php",{"chassis":$('#chassis').val(),"pin":$('#pin').val(),"title":$('#title').val(),"fname":$('#fname').val(),"lname":$('#lname').val(),"email":$('#email').val(),"mobile":$('#mobile').val(),"dob":$('#dob').val(),"anniversary":$('#anniversary').val(),"company":$('#company').val(),"designation":$('#designation').val(),"home_business":$('#style').val(),"add1":$('#add1').val(),"add2":$('#add2').val(),"city":$('#city').val(),"state":$('#state').val(),"pincode":$('#pincode').val()},function(data) {
if(data == true)
{
alert("Error");
}
else
{
alert("Success");
}
});
}
});
});
</script>