Why i can not get value from input using javascript? - javascript

When i press on click here It's wil be alert blank and blank value.
I want to know why not alert 400 and 400
test1.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="first_image_data_url_fid" style="display: block;">
<input type="text" name="first_image_data_url" id="first_image_data_url"/>
<input type="text" name="first_image_data_dimension_width" id="first_image_data_dimension_width"/>
<input type="text" name="first_image_data_dimension_height" id="first_image_data_dimension_height"/>
</form>
<span id="mySpan_check_image_data_width_height"></span>
<div onclick="test_fn()">click here</div>
<script language="JavaScript" type="text/javascript">
function test_fn()
{
var first_image_data_url = "https://pbs.twimg.com/profile_images/839721704163155970/LI_TRk1z_400x400.jpg";
document.getElementById("first_image_data_url").value = first_image_data_url;
document.getElementById("first_image_data_dimension_width").value = "";
document.getElementById("first_image_data_dimension_height").value = "";
$.ajax
(
{
url: 'test2.php',
type: 'POST',
data: $('#first_image_data_url_fid').serialize(),
cache: false,
success: function (data) {
$('#mySpan_check_image_data_width_height').html(data);
//get_first_image_data_width_height();
}
}
)
var item = get_first_image_data_width_height();
}
</script>
<script>
function get_first_image_data_width_height(){
var item;
var first_image_data_dimension_width_val = document.getElementById("first_image_data_dimension_width").value;
alert(first_image_data_dimension_width_val);
var first_image_data_dimension_height_val = document.getElementById("first_image_data_dimension_height").value;
alert(first_image_data_dimension_height_val);
var item = "0";
return item;
}
</script>
test2.php
<?PHP
session_start();
include("connect.php");
$first_image_data_url = mysqli_real_escape_string($db_mysqli,$_POST['first_image_data_url']);
$first_image_data_dimension = getimagesize($first_image_data_url);
$first_image_data_dimension_width = $first_image_data_dimension[0];
$first_image_data_dimension_height = $first_image_data_dimension[1];
?>
<script>
document.getElementById("first_image_data_dimension_width").value = "<?PHP echo $first_image_data_dimension_width; ?>";
document.getElementById("first_image_data_dimension_height").value = "<?PHP echo $first_image_data_dimension_height; ?>";
</script>

If I understood your question correctly, you want to know why alerts gives you an empty string even if you see 400 and 400 in your inputs. It is because JS is asynchronous language and your timeline looks like this:
function test_fn()
{
var first_image_data_url = "...";
// (1) setting an empty values
document.getElementById("first_image_data_url").value = first_image_data_url;
document.getElementById("first_image_data_dimension_width").value = "";
document.getElementById("first_image_data_dimension_height").value = "";
// (2) starting AJAX call
$.ajax
(
{
url: 'test2.php',
type: 'POST',
data: $('#first_image_data_url_fid').serialize(),
cache: false,
success: function (data) {
// (4) END of AJAX call
$('#mySpan_check_image_data_width_height').html(data);
//get_first_image_data_width_height();
// you should get your 400 and 400 here
//var item = get_first_image_data_width_height();
}
}
)
// (3) showing the result
var item = get_first_image_data_width_height();
}
If you look carefully, you will see that you try to alert values before they come.
BTW, you don't need to do mysqli_real_escape_string before get_image_size.
If you don't do any calculations on the image nor downloading it, you can obtain it dimensions by pure JS. See this answer

Related

how to get the value from php with AJAX

I would like to get the 2 values separately in order to fill automatically the input in the first file from the PHP via AJAX, but when i console.log(data) I get all the data and I want to retrieve it separately in order to put it in different tags
<input id="regist" type="text" name="regist" onblur="passdata();">
<input id="atyp" type="text" name="atyp" >
<input id="mtow" type="text" name="mtow" >
<script>
$(document).ready(function(){})
function passdata() {
var regist = $('#regist').val();
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
success: function(data){
var atyp = $('#myvalue1').val();
var mtow = $('#myvalue1').val();
$('#atyp').text(atyp);
$('#mtow').text(mtow);
alert (aty+mtow);
console.log(data);
}
})
}
</script>
and PHP file.... of course with db connection
$regist = $_POST['regist'];
$conn = mysqli_connect($host,$user,$pwd,$db);
$sql= ("SELECT * FROM aircrafts where regist='$regist'");
$datas = mysqli_query($conn,$sql);
foreach ($datas as $row) {};
if(mysqli_num_rows($datas) == 0) {
echo 'non ce niente';
} else { ?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
?>
Change your Ajax request to:
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
dataType: 'json', // NEW LINE
success: function(data) {
//var atyp = $('#myvalue1').val();
//var mtow = $('#myvalue1').val();
//$('#atyp').text(atyp);
//$('#mtow').text(mtow);
var atyp = data.atyp;
var mtow = data.mtow;
alert ('aty: ' + aty , 'mtow: ' + mtow);
console.log(data);
}
})
and in your PHP: change these lines
else{?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
to this exactly lines
else {
echo json_encode( $row );
}
EDIT
Regarding your "DOM-event"-handling ("document onready" and "input#regist onblur") I recommend to do it like this.
HTML:
<!-- <input id="regist" type="text" name="regist" onblur="passdata();"> -->
<input id="regist" type="text" name="regist">
<input id="atyp" type="text" name="atyp">
<input id="mtow" type="text" name="mtow">
JavaScript:
function passdata(event) {
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist=' + $(event.target).val(),
dataType: 'json',
success: function(data){
console.log(data);
}
})
}
$(document).ready(function(){
// on blur event
$('#regist').on('blur', passdata)
// on input event | maybe this would be also an interesting option as it fires immidiately on input
// $('#regist').on('input', passdata)
})
This bootstrap seperates the logic from the markup which is a good practice in general.

jQuery Ajax GET request not working correctly

I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});

Difficulties using AJAX to pass input value to controller

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";
}

PHP function is not echoing anything in Zend Framework

I'm working on a website where clicking on a button will cause a variable to be initialized containing the contents of the associated text field.
However, I've noticed that none of my echo commands are executed and none of the related JS-alerts are showing up either. I have already checked the debugger and know that the action requests are being validated. It's just that nothing is showing up.
My controller:
public function validateuser2Action() {
echo 'asdasdfasdf';
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if (Zend_Auth::getInstance()->hasIdentity()) {
$model = new Application_Model_User();
$emailAddress = $this->getRequest()->getPost("emailAddress");
echo 'he';
} else{
echo 'whatever';
}
}
My PHTML-file:
<script>
$(document).ready(function() {
$(".btn-test").click(function() {
var form_data = document.getElementById("textbox").value
var form_url = "/workspace/validateuser2";
var form_method = "POST";
alert("cool");
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
success: function(data){
alert(data);
},
error: function(){
alert("tpai");
}
});
})
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

How to insert into mysql table using ajax?

I want to insert data into table using ajax so data will insert without reload of page.
This code insert data into table very well but code also reload the page.
But I want insert without reloading of page.
How can i do this ?
<?php
include('connection.php');
if(isset($_POST['cmt'])){
$comment = addslashes($_POST['cmt']);
$alertid = $_POST['alert_id'];
mysql_query("INSERT INTO `comments` (`id`, `alert_id`, `comment`, `username`) VALUES (NULL, '".$alertid."', '".$comment."', 'tomas')");
}
?>
<script>
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
$.ajax({
type: "POST",
//url: "ana.php",
data:{cmt:comment,alert_id:alertid}
}).done(function( result ) {
$("#msg").html( result );
});
}
</script>
<form method = "POST" onsubmit = "submitform()">
<textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" style="margin: 0px 0px 8.99305534362793px; width: 570px; height: 50px;" rows = "6" cols = "40" id = "comment"></textarea><br />
<input type = "text" placeholder="Enter Maximium 100 Words" id = "alertid" value = "10">
<input type = "submit" name = "submit" value = "Comment">
</form>
try this add this to form onsubmit = "return submitform();"
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
$.ajax({
type: "POST",
//url: "ana.php",
data:{cmt:comment,alert_id:alertid}
}).done(function( result ) {
$("#msg").html( result );
});
return false;
}
return false from your event handler function.
onsubmit="submitform(); return false;">
Consider moving to modern methods of event binding.
You have to create a php file that insert into your table the posted data and call it with ajax like that :
$.ajax({
url: "/file.php",
type: "POST",
cache: false,
dataType: "json",
data: postValue,
success: function(results) {
bootbox.alert(results.message, function() {
bootbox.setIcons(null);
window.location.reload();
});
},
error: function(results) {
bootbox.alert(results.message, function() {
bootbox.setIcons(null);
});
}
});

Categories