AJAX on IE doesnt give result onchange (ONLY IE) - javascript

my code is working on other browser yet on IE they doesnt give any result once i select my drop down button.but it change and it just give empty result.
this is my ajax
$("#book").change(function(){
var DOMBULK = $("#book").val();
$.ajax({
cache: false,
type: 'GET',
url: "store/book.php?cc="+DOMBULK,
data:{get_option:DOMBULK},
success: function(result){
$("#tybook").html(result);
}});
});
book.php
<?
$dtacc = $_GET['cc'];
$tybook= mysql_query("SELECT * FROM store WHERE status = 1 AND parentid ='$dtacc'");
while($rowtybook = mysql_fetch_assoc($tybook) or die (mysql_error()))
{ ?>
<option value='<?=$rowtybook['value']?>'><? =$rowtybook['name']?></option>
<? } ?>
and html
<select id='book' name='book'>
<? $result = mysql_query("SELECT * FROM store WHERE status = 1");
while($row = mysql_fetch_assoc($result)){
?>
<option value='<?=$row['value']?>'><?=$row['name']?></option>
<?
}
?>
thanks in advance.

You have not printed any thing in book.php that is why it's give you the blank response
$dtacc = $_GET['cc'];
$tybook = "SELECT * FROM store
WHERE status = '1'
AND parentid ='".$dtacc."' ";
$pretybook = mysql_query($tybook) or die(mysql_error());
$infor = null;
while($rowtybook = mysql_fetch_array($pretybook)){
$infor['name'] = $rowtybook['name'];
$infor['value'] = $rowtybook['value'];
$data[] = $infor;
}
die(json_encode($data));

Related

Ajax request shows status of 200 in console but executing the error function

In my index.php file I have the following script that sends an ajax request:
$('#select-name').on('change', function () {
var selectedName = $(this).find('option:selected').val();
$.ajax({
type: "POST",
url: "assets/php/selectCar.php",
data: {
selectedName: JSON.stringify(selectedName)
},
dataType: "json",
contentType: "application/json",
success: function (data) {
$.each(data, function (i, value) {
$('.car-model').append('<option value = "'+value+'">'+value+'</option>');
});
},
error: function () {
alert("error");
}
});
});
The element with id select-name in the index.php file looks like:
<select name="car-name" id="select-name" class="form-control">
<option value="select_make">Choose make</option>
<?php
$stmt = "SELECT DISTINCT name FROM car_name";
if ($result = mysqli_query($conn, $stmt)) {
while($row = mysqli_fetch_array($result)){
echo '<option value = "'.$row['name'].'">'.$row['name'].'</option>';
}
}
?>
</select>
And the php statement in the above code works fine and renders the elements. The selectCar.php in which the request is sent to looks like:
<?php
require 'db.php';
$selectedName = $_POST['selectedName'];
$stmt = "SELECT DISTINCT model FROM model WHERE id IN ( SELECT model_id FROM cars WHERE name_id IN ( SELECT id FROM car_name WHERE name = '".$selectedName."'))";
$models = array();
$result = mysqli_query($conn, $stmt);
while($row = mysqli_fetch_array($result)){
$models[] = $row['model'];
}
echo json_encode($models) ;
?>
I have tested the sql statement substituting the value of $selectedName with the value I get when I alert selectedName in the script.
I have no idea why this isn't working. Any help would be appreciated. Thank you in advance.
Edit:- I have logged the error in the console and I see :
responseText: "<br />\n<b>Notice</b>: Undefined index: selectedName in <b>/opt/lampp/htdocs/wabi-cars/assets/php/selectCar.php</b> on line <b>3</b><br />\n[]"
and line 3 of selectCar.php is $selectedName = $_POST['selectedName'];

Ajax Success Returning Commented Html Tag

I am trying to set up a select box that would show up the cities depending on the prior selection of the state.
Basically, I am using ajax to run my php.file to populate my <option>. In the php file I successfully passed the pre-selected state to query the database. However, now, to populate the <option> I am using ajax success to call the php file, however, whenever I try to pass the variable containing the php code it shows up commented with !-- and --.
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
I expect to populate my select options by looping through the table city in the php file. The tag <?php include_once 'fillcity.php' ?> was used to populate the state select. Probably, there may be a more direct way to populate accordingly, but as I am new to programming, I am trying to figure things out on my own. But please, feel free to recommend other methods as I am not sure if what I am planning to do will gonna work. Thanks!
You can try this one. You can modify it later for improvement.
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetState"){
//SAMPLE QUERY
$sql = "SELECT StateID,StateName from State";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetCity"){
$StateID= $_POST["StateID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT CityID,CityName from City where StateID = '".$StateID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="state"></select>
<select id="city"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadState();
function LoadState(){
$.ajax({
url:"read.php?type=GetState",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
State</option>";
for(var i in data){
options += "<option value='"+data[i].StateID+"'>" + data[i].StateName+ "</option>";
}
$("#state").html(options);
}
});
}
function LoadCity(StateID){
$.ajax({
url:"read.php?type=GetCity",
type:"POST",
data:{
StateID: StateID
},
success:function(data){
var options = "<option selected disabled value="">Select City</option>";
for(var i in data){
options += "<option value='"+data[i].CityID+"'>" + data[i].CityName+ "</option>";
}
$("#city").html(options);
}
});
}
$("#city").change(function(){
LoadCity(this.value);
});
You don't need to include 'fillcity.php. The AJAX call runs that script, and the response is the output. It will be in the parameter of the success function.
function fillSelectCity () {
var getState = $("#selectState").val();
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (tag){
$('#select-city').html(tag);
}
});
}

Requesting data from php through ajax

Trying to request the posts made by users and loading more posts on user's request.
Getting Unexpected end of JSON input error while making ajax request in console.
Javascript
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
url: "action.php?action=morePosts",
success: function(response){
var result = $.parseJSON(response);
console.log(result);
}
});
});
Making request to following code.
$_SESSION['posts']) stores the number of posts to be loaded in the session.
if($_GET['action']=="morePosts"){
if(isset($_SESSION['posts'])){
$_SESSION['posts'] = $_SESSION['posts'] + 4;
echo fetchAllPosts($_SESSION['posts']);
} else if(isset($_SESSION['posts'])&& $_SESSION['posts']>4){
$_SESSION['posts'] = 4;
}
}
Function for requesting all posts
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
for($i=0; $i<$array_length; $i++){
if(!empty($row[$i])){
for($j=0;$j<count($row);$j++){
$post['id']=$row[$i][0];
$post['user_id']=$row[$i][1];
$post['title']=substr($row[$i][2], 0 ,75);
$post['text']=strip_tags(mb_substr($row[$i][3],0,50));
$post['image']=$row[$i][4];
$post['date']=$row[$i][5];
}
return json_encode($post);
}
elseif(empty($row[count($row)])){
return json_encode(array());
}
}
}
Please suggest better ways of achieving this functionality,
Try to use echo instead of return and change ajax like also you din not echo the code inside elseif part:
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
dataType: "json",
url: "action.php?action=morePosts",
success: function(response){
console.log(response);
}
});
});
try this :
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
if($result && mysqli_num_rows($result) > 0) {
foreach($row as $key=>$value){
$post[$key]['id']=$value['id'];
$post[$key]['user_id']=$value['user_id'];
$post[$key]['title']=substr($value['title'], 0 ,75);
$post[$key]['text']=strip_tags(mb_substr($value['text'],0,50));
$post[$key]['image']=$value['image'];
$post[$key]['date']=$value['date'];
}
return json_encode($post);
}
return json_encode(['error'=>"no post found"]);
}

how to retrieve echo data from php to jquery 1 by 1

I have a JQuery on click that sends a php query to MySql and then I want to send the data back 1 by 1 on JQuery.
But I only know how to send back results from php to JQuery as a whole.
my current JQuery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
alert(data);
}
});
});
});
my current php:
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['UserID'];;
echo $row['EmailAddr'];
}
?>
the outputs are both UserID and EmailAddr, I don't know how to just display either the UserID or EmailAddr out only
I tried alert(data[0]), but it only displayed one letter of the result.. Any ideas on how to do this?
UPDATE: After sean's help i have the current updated code
Jquery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
PHP
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
In your php, save the results to an array -
<?php
include 'dbAuthen.php';
$array = array(); // create a blank array
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// add each result to the array
$array[] = array('UserID'=> $row['UserID'], 'EmailAddr'=> $row['EmailAddr']);
}
echo json_encode($array); // json_encode() the array
?>
Then in your js/ajax you can loop through each value
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
// loop through each returned value
$.each(data, function(){
//alert each result, this is just an example as alert() for each result is not a great idea
alert("UserID:"+ this.UserID + " EmailAddr:" + this.EmailAddr);
});
}
});
});
});
jquery
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
php
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>

Array of drop down list in html

How to change the value of dropdown dinamically.
here the case:
for example i have an array of dropdown and has 2 names on it, like name1 and name2,
the name 1 has grade and also the name2.
what i want to do is change the first dropdown which has the value of name and
i want the second dropdown change automatically according to his grade.
Like:
John -> 90
Paul -> 80
please help me to find the index of array and the selected value of dropdown using javascript. thanks in advance.
<script>
function Change2(a){
var options1= document.getElementById('stuname[]').options;
var options2= document.getElementById('stugrade[]').options;
for(i = 0; options1.length;i++){
if(options1[i].selected == true){
options2[i].selected = true;
}
}
} // what I want is, if I change the first dropdown in row 1, the 2nd dropdown should change too, and same in row 2.
</script>
<?php
$getlist= mysql_query("SELECT * FROM STUDENTS");
while($row = mysql_fetch_assoc($getlist)){
print "<select id = 'stuname[]' name = 'stuname[]' class = 'text4' onchange = 'Change2(this.value);'>";
$getname = mysql_query("SELECT * FROM NAME");
while($row = mysql_fetch_assoc($getname)){
$name = $row['name'];
print "<option value = '$name'>$name</option>";
}
print "</select>";
print"<select id = 'stugrade[]' name = 'stugrade[]' onchange = 'Change2(this.value);'>";?>
<?php
$getgrade = mysql_query("SELECT * FROM GRADE");
while($row = mysql_fetch_assoc($getgrade)){
$grade = $row['grade'];
print "<option value = '$grade'>$grade</option>";
}
print "</select><br>";
}
?> // heres my code.. edited
This is a common approach to solve this kind of issues, differently you need change querys and names accordingly
JS file
$(document).ready(function(){
getfirstSelect();
})
function getSecondSelect() {
var firstDropDownSelectedID = $('#firstSelect option:selected').val();
$.ajax({
type: "POST",
url: "getSecondDropDownOptions.php",
data: "firstDropDownSelectedID="+firstDropDownSelectedID
}).done(function (result) {
//alert(result)
$("#secondSeect").html(result);
});
}
function getfirstSelect() {
$.ajax({
type: "POST",
url: "getFirstDropDownOptions.php",
data: {}
}).done(function (result) {
//alert(result)
$("#secondSeect").html(result);
});
}
getSecondDropDownOptions.php
<?
$firstDropDownSelectedID = isset($_POST['firstDropDownSelectedID']) ? (int)$_POST['firstDropDownSelectedID'] : 0;
$list2 = mysql_query("SELECT * FROM LIST2 WHERE relatedid=".$firstDropDownSelectedID);
$returnString = "";
while($row = mysql_fetch_assoc($list2)){
$returnString.= "<option value = '".$row['grade']."' >".$row['grade']."</option>";
}
print $returnString;
?>
getFirstDropDownOptions.php
<?
$list1 = mysql_query("SELECT * FROM LIST1 ");
$returnString = "";
while($row = mysql_fetch_assoc($list1)){
$returnString.= "<option value = '".$row['grade']."' >".$row['grade']."</option>";
}
print $returnString;
?>
HTML
<form name="formName">
<select name="firstSelect" id="firstSelect" onchange="updateSecondSelect()"></select>
<select name="secondSeect id="secondSeect" ></select>
</form>

Categories