i am a noob to jquery and i want to know how to make use of if else for the following:
on the server side there is a if for number of rows is equal to 0 and else some JSON part.
$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
if ($age_num_rows==0)
{
echo "true";
}
else
{
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$abc_output = array('title' => $row['title'],'age' => $row['age']);
}
echo json_encode($abc_output);
}
Now coming to Jquery part :
If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.
$(document).ready(function(){
$("#button1").click(function(){
$.getJSON('script_1.php',function(data){
if (data=='true') {
alert ('hello')
}
else {
$.post('script_1.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
},
"json");
}
});
});
Edited:
$(document).ready(function(){
$("#button1").click(function(){
$.post(
'script.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
var data = JSON.parse(json);
if (data.length === 0){
alert('no data');
}
else{
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
}},
"json"
);
});
});
PHP side
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row= array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}
You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.
For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
echo json_encode($row);
} else {
echo json_encode(array());
}
Back in the JavaScript, you could then do something like this:
var data = JSON.parse(json);
if (data.length === 0) {
alert('no data');
} else {
$("input[name='title']").val(data.title);
$("input[name='age']").val(data.age);
}
jeroen is right though, you only need to use one AJAX call.
There seem to be a few problems:
You are treating the data returned from getJSON as if it is plain
text
The php that you are calling from javascript does not always
return json
You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition
By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.
Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:
$.getJSON('script_1.php',function(data){
to something like:
$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {
and in your php you need to use something like:
$name = mysql_real_escape_string($_GET['id']);
Related
I'm working on a php project and the search function from the database is not returning any results or any error. Below is the code for the search function:
function searchweb() {
console.log("click");
//e.preventDefault();
searchWebsite = $("#searchWebsite").val();
if (searchWebsite == "")
$("#searchWebsite").focus();
else {
console.log("else");
$("#search").html("Searching..");
$("#search").attr("disabled", true);
var excat = "like";
if ($('input[type=checkbox]').prop('checked'))
excat = "match";
$.post("userinput.php", {
searchWebsite: $("#searchWebsite").val(),
excat: excat
}, function (data) {
console.log("hey"+data);
populateSearch(data);
});
function populateSearch(data){
data = JSON.parse(data);
$('#result').empty();
$.each(data, function (key, value) {
//console.log(data);
$('#result').append("<tr>\
<td><a href='"+value.website_name+"' target='_blank'><i class='glyphicon glyphicon-search'></i></a></td>\
<td>"+value.website_name+"</td>\
<td>"+value.avg_score+"</td>\
<td><img class = 'imgs img-responsive center' src='../img/"+value.remark+".png' alt ='"+value.remark+"' />\
</td></tr>");
});
}
// console.log(searchWebsite);
$("#search").html("Search Website");
$("#search").attr("disabled", false);
}
}
The 'searchweb' function calls the post method to search in the mysql database. I'm using phpmyadmin for this project. The code for post function in userinput file:
if(isset($_POST['searchWebsite'])){
$searchWebsite = $_POST['searchWebsite'];
$type = $_POST['excat'];
$sql = "SELECT * from websites WHERE ";
//for excact match
if($type=="match")
$sql.= "MATCH(tags) Against('$searchWebsite') ORDER BY avg_score DESC";
//for tags contaionun gthose words
else
$sql.= "tags LIKE '%$searchWebsite%' ORDER BY avg_score DESC";
$result = mysqli_query($db, $sql);
if($result){
$rr = array();
$i=1;
while($row = mysqli_fetch_assoc($result))
{ $rr[] = $row;
$i=$i+1;}
echo json_encode($rr);
}
else
{
echo "<script type='text/javascript'>alert('Error: '".mysqli_error($db).");</script>";
}
}
No error will be spit back as this is a .post in javascript call / AJAX request. AJAX will not dynamically parse the javascript error code you're trying to trap within the AJAX request.
It's better to do something like this:
PHP side:
Replace:
echo "alert('Error: '".mysqli_error($db).");";
With:
echo json_encode( [ 'error' => mysqli_error($db) ] );
Javascript Side:
// Note you shouldn't have to parse JSON since on the PHP side the error array has been encoded as json
if( ! $.isEmptyObject(data.error) ) {
alert( data.error );
}
i am trying to get the data which is in array, from an SQL query to the ajax success data. Here is the code i tried,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
now in the php method which is requested from the above ajax call, i have to get the data return by this function which is returning an array
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
here $row is returning an array as data to the ajax function, where i need to get all the items seperately. Some one help me out to get the values into the ajax call. Thanks in advance..
In your PHP file, you can return your array as a json object in the following way (notice how the PHP file echos the result to pass it back to javascript)
...
$json = json_encode($row);
echo $json
Now add the following to your javascrip ajax
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
You can handle the java script variable 'data' as an associative array like it was in PHP
also, look how you populate the php variable $row and adjust the following way:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
in javascript you can access your rows the following way in teh data variable:
var value = data[0]['field_name'];
in the above statement, 0 will correspond to the value of $cnt (i.e. mysql returned row number)
return $row;
replace like this
echo json_encode($row);
and add dataType='json' in ajax like this
dataType: 'json',
If you want get the value in ajax call i think it shoul be :
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;
I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )
I've read multiple similar posts on this, and my code seems to match the suggestions, but still no data returned.
Here's my JS:
$.post('php/get_last_word.php', { user_id : userID },
function( data ) {
currentLanguage = data.language_id;
currentWord = data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
},'json');
And the relevant php:
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$encoded = json_encode($row);
echo $encoded;
}
And the resulting log:
Connected successfully{"language_id":"1","word_id":"1"}
So the json array is being echoed, but it's not ending up in data, because currentLanguage and currentWord are not being populated. Is this a problem with asynchronicity? Or something else?
Make sure you have a valid json coming back to your variable from your PHP script
IF your json object is like this,
{"language_id":"1","word_id":"1"}
You can access the values like this
currentLanguage = data.language_id;
currentWord = data.word_id;
Example JsFiddle http://jsfiddle.net/NuS7Z/8/
You can use http://jsonlint.com/ to verify your jSon is in correct form or not.
Specifying json as the data type value in your post request will make sure the reponse is coming back as json format to the success callback.
$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
currentLanguage = data.language_id;
currentWord = data.word_id;
});
You can also use getJson to simply get json data. getJson is a shorthand of ajax Call with datatype as json
http://api.jquery.com/jQuery.getJSON/
Try changing your JS to:
$.getJSON('php/get_last_word.php', { user_id : userID },
function( response ) {
if (response.success) {
currentLanguage = response.data.language_id;
currentWord = response.data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
} else {
alert('Fail');
}
});
and your PHP to:
<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$success = true;
$data = $row;
}
// I generally format my JSON output array like so:
// Response
header('Content-Type: application/json');
echo json_encode(array(
'success' => $success,
'data' => $data
));
?>
That way its more organized and don't forget to set the content type.
Hope that helps.
below is my $.ajax call to php
$(document).ready(function() {
$('ul.sub_menu a').click(function(e) {
e.preventDefault();
var txt = $(this).attr('href');
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#container').fadeOut('8000', function (){
$('#container').html(data);
$('#container').fadeIn('8000');
});
}
});
});
});
my php code
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
echo $row['img'];
}
}
I m getting this output
images/man/caps/army-black.pngimages/man/caps/army-brown.pngimages/man/caps/army-grey.pngimages/man/caps/army-lthr.pngimages
these are basically image paths now how to loop over them in jquery and fit each image in image tag
any code will be useful
Plz Note I DONT NEED JSON
regards sajid
JSON is probably your best bet here. In PHP do something like this:
$ret = array();
while( $row = mysql_fetch_assoc( $result ) )
{
$ret[] = $row['img'];
}
echo json_encode( $ret );
This will output something like the following
["image1","image2","image3"]
jQuery has a function which can convert this information into a javascript array. So put this code in your success callback.
var result = jQuery.parseJSON( data );
alert( result[1] );
EDIT: A method which does not use JSON
In PHP place each image url on a separate line
echo $row['img'], "\n";
Then in javascript, split the response by the new line character
var result = data.split( "\n" );
simply change your php code:
`if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
echo ""<img src='".$row['img']."' /><br />";
} }