submit form to check something with ajax and jquery - javascript

I am making a form to check a security code. In fact, I am new to ajax and jquery, so I tried what I can, but my code doesn't work. Can anybody help me?
php file :
<?php
include('/includes/db-connect.php');
if( isset($_POST["seccode"]) ){
$result=mysqli_query($con,"SELECT * FROM `certificate_acheived_tbl` WHERE `cert_check_code` = ".$seccode.")";
if( mysql_num_rows($result) == 1) {
echo "<script>alert('s')";
}
}
?>
js file:
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: 'certcode='+ ID,
success: function() {
$('#someHiddenDiv').show();
console.log();
}
});
});
});

your code is bad... (sometimes mine too)
One first mistake : data: 'certcode='+ ID, in jQuery
and isset($_POST["seccode"]) in PHP 'certcode' != 'seccode'
so a better code.. ?
jQuery (I allways use JSON, it's more easy)
$(function () {
$(".btn btn-success").click(function() {
var
Call_Args = {
certcode: $(this).attr('id')
};
$.ajax({
url: 'cert-check-ajax.php',
type: 'POST',
data: Call_Args,
cache: false,
dataType: 'json',
success: function (data) {
console.log( data.acceptCod ); // or data['acceptCod'] if you want
$('#someHiddenDiv').show();
// ...
}
}); //$.ajax
}); // btn btn-success").click
});
PHP (with utf8 insurance, and good header / JSON encode response )
<?php
mb_internal_encoding("UTF-8");
include('/includes/db-connect.php');
$T_Repons['acceptCod'] = "bad";
if (isSet($_POST['certcode'])) {
$sql = "SELECT * FROM `certificate_acheived_tbl` ";
$sql .= "WHERE `cert_check_code` = ".$_POST['certcode'].")";
$result = mysqli_query($con, $sql);
$T_Repons['acceptCod'] = (mysql_num_rows($result) == 1) ? "ok" : "bad";
}
header('Content-type: application/json');
echo json_encode($T_Repons);
exit(0);
?>

you can use it
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: {'seccode': ID}
}).done(function(data) {
$('#someHiddenDiv').show();
console.log(data);
});
});
});

Related

my ajax post method works but i can not catch the value by php

post method , it can post value, my success alert is working but i can not echo in my php. i tried to send to same page and another page. Both they haven't work. Here is my ajax code :
<script>$( "#il" ).change(function() {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: { aa1 : 'mynameis'},
success: function () {
alert($("#il").val());
},
});
});
</script>
and here is my php code to catch :
<?php
$aa = $_POST['aa1'];
if($aa != ""){
echo $aa;
} else { echo "puuf";}
?>
In order to catch the data returned from the PHP echo you need to add a parameter to the success method for javascript to place the value in for you to then make use of
<script>
$( "#il" ).change(function() {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: { aa1 : 'mynameis'},
success: function (data) {
// - - - - - - - - ^^^^
alert($("#il").val(data));
// - - - - - - - - - ^^^^
}
});
});
</script>
You'll have to define a data parameter on the success callback, because the echoed data have to be passed as argument to it. So,
The client script:
<script type="text/javascript">
$("#il").change(function () {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: {
aa1: 'mynameis'
},
success: function (data) {
alert(data);
},
});
});
</script>
And the PHP:
<?php
$aa = $_POST['aa1'];
if (isset($aa) && !empty($aa)) {
echo $aa;
} else {
echo "puuf";
}
?>

Post to php file, and retrieve data with javascript

So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});

Pass values from JQUERY to PHP then output to INPUT in FORM

i need to get a value from the a form then send it to php using jquery then output the result a dropdown select menu
get the value of using jquery
<input id="search" name="search" type="text">
send it to php and perform a query
<select id="farmertype" name="farmertype" >
<option value="" > - PLEASE SELECT FARM -</option>
//// output here as options
</select>
my php file farm.php
<?php
include_once("../init.php");
$q = ($_POST["search"]);
$db->query("SELECT * FROM farmers ");
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
echo "<option value='$idno'>$idno</option>";
}
}
?>
the jquery part is so messy this is where i really need help
$("#search").click(function() {
search = $(this).attr('#search');
$.ajax({
type: 'GET',
url: 'farm.php',
data: "#search=" + search,
});
});
try this, it will help you.
JQuery:
$("#search").click(function() {
search = $(this).val();
$.ajax({
type: 'POST',
url: 'farm.php',
data: {searchValue:search},
success:function(result) {
console.log(result);
}
});
});
PHP:
<?php
include_once("../init.php");
$q = ($_POST["searchValue"]);
$db->query("SELECT * FROM farmers");
$result = [];
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
$result = "<option value='$idno'>$idno</option>";
}
print_r($result);
?>
what is the purpose of your variable $q?
Your jquery can be like :
$("#search").click(function() {
search = $('#search').val();
$.ajax({
type: 'GET',
url: 'farm.php',
data: {search : search},
success: function(html){
alert(html);
}
});
});
$("#search").click(function() { /* I think you should use keyUp or use click on a button, nobody clicks an input box */
var search = $(this).val();
$.ajax({
method: 'POST', //
url: 'farm.php',
data: {'search' : search},
success: function(data){
alert(data);
}
});
});

PHP/Ajax/jquery/JSON - Take a part from echo text back as a variable after Ajax Post

I'm working on a simple Ajax post method and here is my code:
<script type="text/javascript">
jQuery(document).ready(function($) {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
var nextUrl = "<?PHP echo $nexturl;?>";
$('#Loading').show();
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'html',
data: {
next_url: nextUrl
},
}).done(function ( html ) {
$('#LoadedResults').html( html );
$('#Loading').hide();
});
}
});
});
</script>
This code is sending post data to ajax.php:
<?PHP
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$client_id = "1e0f576fbdb44e299924a93cace24507";
$Next_URL = $_POST["next_url"];
$url = $Next_URL;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
$maxid = $results['pagination']['next_max_id'];
$nexturl = $results['pagination']['next_url'];
//Now parse through the $results array to display your results...
echo json_encode(array(
'next_url_link' => $nexturl
));
The ajax.php is echoing result as:
{"next_url_link":"https:\/\/api.instagram.com\/v1\/tags\/sweden\/media\/recent?count=24&client_id=1e0f576fbdb44e299924a93cace24507&max_tag_id=1427904820688670"}
I was looking here and there and i think there is some method with json with which i can get the result of next_url_link.
So guys, how can i get back the result printed for next_url_link and set is active jQuery/JavaScript variable ?
For example:
var NextUrlLink = data.next_url_link;
Is it possible somehome ?
Should i create two .ajax post methods or how, i have no idea ?
Thanks in advance!
Use the function JSON.parse() for it.
So here is how you will do it :
.done(function ( html ) {
var data = JSON.parse(html);
//now use data.next_url_link
$('#LoadedResults').html(data.next_url_link);
$('#Loading').hide();
});
Maybe you can use the success function to retrieve the data you encoded in your json
var NextUrlLink = []; //declare it as a global variable or somewhere within the same level or scope of where you want to use it so that you can use it
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: {
next_url: nextUrl
},
success:function(data){
NextUrlLink = data.next_url_link;
}
})

Passing array and other data through ajax

This is my javascript function....
But my php controller getting all values but not the array not sure why ? Need help.....
Thanks in advance :)
function submitForm(){
var id = $('#id').val();
var supplier_id = $('#supplier_id').val();
var description = $('#description').val();
var numofpro = $('#numofpro').val();
var product_id = new Array();
for(var i=0;i<numofpro;i++){
product_id[i] = $('#product_id'+(i+1)).val();
}
var payment_mode = $('#payment_mode').val();
//description = description.replace(new RegExp('\r?\n','g'), '<br />');
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase", //The url where the server req would we made.
data: "id="+id+"&supplier_id="+supplier_id+"&description="+description+"&product_id="+product_id+"&payment_mode="+payment_mode,
dataType: "html", //Return data type (what we expect).
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
}
because you pass a string, not an array :) try it:
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase",
type: "POST"
data: {id : id, supplier_id : supplier_id, description : description, product_id : product_id, payment_mode : payment_mode},
dataType: "json",
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
in you php use :
$arr = json_decode($_POST);
//some php code
//some $result;
// if $result arr then
echo json_encode($result);
// else
echo json_encode(array('data' => $result))
hope this helps...
You need to first turn that array into a string in JS. Before sending it, do this:
JSON.stringify(product_id);
Once you receive it in PHP, you need to decode it.
$decoded = json_decode($_POST['product_id'])

Categories

Resources