i return from php page an echo for test:
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'https://capelladb.000webhostapp.com/textExample.php',
data: $('#form').serialize(),
success: function (data) {
var compare = data.localeCompare('testest');
console.log(data);
console.log(compare);
}
});
});
});
Just for test, the data returns in the success method is typeof "string" with "testest", but when im comapre to 'testest', is return -1 into "compare" variable. why it happen ?
Console.log photo: http://imgur.com/a/h7wWh
the PHP:
<?php
header("Access-Control-Allow-Origin: *");
$servername = "localhost";
$username = "id1635462_capellam";
$password = "capella2017";
$dbname = "id1635462_capella";
$userInput = $_POST['username'];
$passwordInput = $_POST['password'];
echo $userInput . $passwordInput;
?>
Your data has empty spaces within.
You need to trim it, using .trim().
See the code below:
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'https://capelladb.000webhostapp.com/textExample.php',
data: $('#form').serialize(),
success: function (data) {
var compare = data.trim().localeCompare('testest');
console.log(data);
console.log(compare);
}
});
});
});
Working example:
window.onload = function() {
var data = 'testest ';
var test = data.localeCompare('testest');
console.log('Not trimmed: ' + test);
var test = data.trim().localeCompare('testest');
console.log('Trimmed: ' + test);
};
Related
I didn't understand how to get data from php by ajax.
Here is my javascript code :
$('#value').on('keyup', function(event){
event.preventDefault();
var form_data = $(this).serialize();
var sending = $("#sending").val();
var value = $("#value").val();
var recevied = $("#recevied").val();
$.ajax
({
type: "POST",
//async: true,
dataType : 'json',
url: "{{url('/calculate')}}",
data: {_token:"{{csrf_token()}}", sending:sending,value:value,recevied:recevied}
}).done( function(data){
//swal("Good job!", "Your personal information has been successfully updated!", "success")
$("#mainvalue").val(data)
console.log('Ajax was Successful!')
console.log(data)
}).fail(function(xhr, textStatus, error){
console.log(textStatus)
console.log(error)
});
});
here is my php code :-
public function index(Request $request)
{
$sending = $request->get('sending');
$value = $request->get('value');
$recevied = $request->get('recevied');
$relations = DB::table('tbl_relations')
->where('exid1',$sending)
->where('exid2',$recevied)
->select()
->first();
if ($relations != null) {
$rate = $relations->exrate2;
$mainvalue = $sending * $rate;
return $rate;
}else{
return $request->all();
}
}
How to restore $rate value into #mainvalue ?
well i guess you can try the following inside the php code :
$post = file_get_contents('php://input');
I'm trying to get result and alert it if the solicitude was successful or not on the PHP file, it worked (because changed the results) but the AJAX didn't show alerts (No error and no "true")
js:
function addentrys() {
var nwentry = {};
el = document.getElementById('addname').value;
eldmn = document.getElementById('adddomain').value;
nwentry.name = el;
nwentry.domain = eldmn;
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: nwentry
}).done(function(data) {
alert(data);
});
}
php:
$app->post('/domain', function () {
$jsonContents = file_get_contents('data/data.json');
$name = $_POST['name'];
$domain = $_POST['domain'];
$data = json_decode($jsonContents, true);
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'name' => $name,
'domain' => $domain,
'id' => $last_item_id+1
);
$json = json_encode($data);
file_put_contents('data/data.json', $json);
return true;
});
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.
Im trying to pass data from using Ajax and PHP on server side. the php file is not catching the data sent through Ajax.
the code gets the values with jquery and make a long string called data
the jquery code looks like this:
var data = 'ppemail=' + $('#email').val()
+ '&monto_enviar=' + montoEnviarDisp
+ '&monto_pub=' + montoPubDisp
+ '&tasa=' + tasaDisp
+ '&monto_recibir=' + monto_recibirDisp
+ '&banco=' + $('#banco').val()
+ '&receptor=' + $('#receptor').val()
+ '&cuenta=' + $('#cuenta').val()
+ '&cedula=' + $('#cedula').val();
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: ({data}),
success: function (response) {
alert(response);
}
});
the php file is this:
<?php
session_start();
require_once 'dbconfig3.php';
var_dump($_POST);
try {
$userID = $_SESSION['userSession'];
$ppemail = $_POST['ppemail'];
$monto_e = $_POST['monto_enviar'];
$monto_p = $_POST['monto_pub'];
$tasa = $_POST['tasa'];
$monto_rec = $_POST['monto_recibir'];
$banco = ($_POST['banco']);
$receptor = ($_POST['receptor']);
$cuenta = ($_POST['cuenta']);
$cedula = ($_POST['cedula']);
/// luego de confirmar hacer el try e insertar
//if(isset($_POST['btnferta'])){
//$password = md5($upass);
$bid_date = date('Y-m-d H:i:s');
$stmt = $db_con->prepare("INSERT INTO ofertas(uid,email_pp,nombre_receptor,banco_receptor,cuenta_receptor,cedula_receptor,monto_enviar,monto_publicar,tasa,monto_recibir,fecha)
VALUES(:userid, :emailpp, :nombre, :banco, :cuenta, :cedula, :monto_e, :monto_p, :tasa, :monto_r, :fecha)");
$stmt->bindParam(":userid", $userID);
$stmt->bindParam(":emailpp", $ppemail);
$stmt->bindParam(":nombre", $receptor);
$stmt->bindParam(":banco", $banco);
$stmt->bindParam(":cuenta", $cuenta);
$stmt->bindParam(":cedula", $cedula);
$stmt->bindParam(":monto_e", $monto_e);
$stmt->bindParam(":monto_p", $monto_p);
$stmt->bindParam(":tasa", $tasa);
$stmt->bindParam(":monto_r", $monto_rec);
$stmt->bindParam(":fecha", $bid_date);
$stmt->execute();
echo 'ok';
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
why the $_POST is not getting any data? Thanks for the help!
You should set data to an object. This ensures that the URL parameters will be properly encoded; otherwise, you need to call encodeURIComponent on any parameter that could contain special characters.
var data = {
'ppemail': $('#email').val(),
'monto_enviar': montoEnviarDisp,
'monto_pub': montoPubDisp,
'tasa': tasaDisp,
'monto_recibir': monto_recibirDisp,
'banco': $('#banco').val(),
'receptor': $('#receptor').val(),
'cuenta': $('#cuenta').val(),
'cedula': $('#cedula').val()
};
Then you shouldn't wrap it in another object when calling $.ajax:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
It looks like you're trying to pass a string as an object property. Change your $.ajax options:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}
I am storing my checkbox selections in an array then splitting each array and posting them using AJAX so my PHP function can use the posted id/ids to query my MySQL database.
First part of my JavaScript
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
alert(tbl);
This first part works as intended, where every time I click a checkbox the value is alerted.
AJAX post
$.ajax({
type: "POST",
url: "index.php",
data: "tbl=" + tbl
});
});
Finally my PHP
function describeTables() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}}
I don't get any vlaues of tbl even if I choose just one option. Why is this????
EDIT
My Checkbox
function showTables() {
if (isset ( $_GET ['db'] )) {
$db = $_GET ['db'];
$link = mysqli_connect ( 'localhost', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
echo '<ul>';
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
echo '<input type="checkbox" name="tbl[]" class="tbl_list" value="' . $row [0] . '" class="tablebox" />';
echo $row [0];
echo '<br>';
}
}
}
showTables ();
SECOND EDIT
After suggestions I have amended my code but now have a new problem where the page doesn't load #dbdisplay Below is my full JS code
if (!location.search.match(/db=[^&#]+/i)) {
$("#dbdisplay").show();
} else {
$("#qryDisplay").show();
}
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
window.sessionStorage.setItem("db", db);
window.location.assign("index.php?db=" + db);
$("#dbdisplay").hide();
});
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
//alert(tbl);
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl': tbl }
});
});
The old function
/*
$(document).on("change", ".tablebox", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var yourDB = window.sessionStorage.getItem("db");
window.location.assign("index.php?db=" + yourDB + '&tbl=' + tbl);
});
*/
How do I fix this??
In ajax call, data has to be object data: {'tbl': tbl}
This should to the job
$.ajax({
type: "POST",
url: "someurl",
data: {"tbl=" + tbl}
});
http://api.jquery.com/jquery.getjson/
See here for documentation
First thing in your ajax call, data has to be object
data: {'tbl': tbl}
Secondly Ajax can't call php function directly
so your index.php file should be something like this without function
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}
You should use "{ }" with data
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl' : tbl}
});
or
$.ajax({
type: "POST",
url: "index.php&tbl="+tbl
});