What I am trying to do is retrieve JSON data from an online web service that searches and finds a certain string in a MySQL database and display it using Javascript on an HTML page.
What I am struggling with is actually displaying the resulting data.
The relevant areas of my HTML page looks like this:
<form onSubmit="results()">
<fieldset>
<label for="area">First digits of postal code:</label>
<input name="area" type="text" maxlength="4" placeholder="AB12" required />
<input type="submit" value="Search" name="search" />
</fieldset>
</form>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="cordova-2.3.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
function results(){
$.ajax({
url: 'http://www.foobar.com/cp/index.php?area=AB12',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<h1>'+item.location+'</h1>'
+ '<p>'+item.id+'</br>';
output.append(place);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
};
</script>
<div id="place">
<h3>Places near your location</h3>
</div>
The page for the GET data is http://www.foobar.com/cp/index.php with the search variable 'area'. Test sample is ?area=AB12.
It seems that this service is not correctly wrapping the JSON object in parentheses so it doesn't work as JSONP.
See: http://www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST
It returns:
TEST[{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]
while it should return:
TEST([{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]);
You won't be able to use it because it is not valid JSONP.
UPDATE:
Answering more info from the comment - if you control the server-side script then try changing:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . json_encode($records);
to:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
and see if that works.
UPDATE 2:
Answering another comment. Do you actually initialize the output variable? For example with something like this at the beginning:
var output = $('#place').append('<div/>');
Do you actually call your results function? It must be called with:
results();
or registered somewhere as an event handler, using the jQuery way:
$('form').submit(results);
but then add:
return false;
to the end of the results function to prevent the page from being reloaded.
See this demo: http://jsbin.com/uziyek/1/edit - it seems to work.
Another problem:
There seems to be another problem with your code, that the area=AB12 parameter is hardcoded into your URL. What you should do instead is get the value from the form and send that.
You implemented JSONP incorrectly. You need to generate a function call, i.e. the response should be foo(<json here>); not foo<json here>.
It is trivial to fix:
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
Another problem is that you are not preventing the form submission, i.e. when you submit the form, the page refreshes. You have to prevent that. Better bind the event handler with jQuery and don't use inline event handlers:
<form id="myForm">
and
$(function() {
$('#myForm').submit(function(event) {
event.preventDefault(); // <-- prevent form submission
// Ajax call here
});
});
DEMO
Related
I have a data which i use PHP to access them. So i created a simple button, when i click on it, my programm needs to create a table with the data. Below you can see the jQuery Code to read the data, and also create a table. But the problem is, i can not access the each element in the DATA.
I want to make clear because of that i also add the code, which i make the selection in data. Its called "household.php"
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.6.2.js"
integrity="sha256-pkn2CUZmheSeyssYw3vMp1+xyub4m+e+QK4sQskvuo4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<script>
function suchen() {
jQuery(document).ready(function($) {
$.ajax({
type: "get",
url: "household.php",
dataType: "json",
success: function(response) {
var data = JSON.parse(response)
var html_table = "";
data.forEach(function(item) {
var row = $("<tr>");
row.append($("<td>").text(item.contact_id_a));
row.append($("<td>").text(item.contact_id_b));
// add more cells for additional columns
html_table += row[0].outerHTML;
});
$("#tabelle").html(html_table);
}
});
});
}
</script>
</head>
<body>
<form id="form" onsubmit="suchen()" method="get">
<label>Enter your age: </label>
<br />
<input type="number" name="min" min="0">
<br />
<input type="number" name="max" min="0">
<br />
<input type="submit">
</form>
<div id="tabelle"></div>
</body>
</html>
Here's the code for household.php file. It works without problem. But i can not connect between my main php file.
<?php
require_once '/var/www/html/wordpress/wp-content/plugins/civicrm/civicrm/civicrm.config.php';
require_once 'CRM/Core/Config.php';
$config = CRM_Core_Config::singleton();
$relationships = \Civi\Api4\Relationship::get()
->addSelect('contact_id_a', 'contact_id_b', 'contact_id_a.display_name', 'contact_id_b.household_name', 'relationship_type_id')
->addClause('OR', ['relationship_type_id', '=', 7], ['relationship_type_id', '=', 8])
->setLimit(25)
->execute();
foreach ($relationships as $relationship) {
// do something
}
var_dump(json_encode($relationships));
?>
i can not access the data with php file. I also can not connect my main php file, with searching php.
I think you already used echo json_encode($relationships) in household.php file. You don't need the parse the response (you used ) because you already write dataType to json. it would automatically be converted. Hope this answer to help you. According to jQuery Manual, "any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected". So you can use dataType: 'json' only, if you're sure, that server will return poperly formatted JSON. If it only returns "a string, that looks like JSON", you should use dataType: "text json" to force jQuery conversion.
[NOTE] If above answer doesn't help you, I suggest that you use this function for parsing response. var data = jQuery.parseJSON(response); or var data = $.parseJSON(response)
I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article
bit of a selfish question but I am really strugerling with ajax in general so I need some help. So basically Im trying to update and sql database using an 'onblur' function. heres my code:
code on index.php
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
and code on saveStatus.php
<?
require 'core.php';
require 'connect.php';
$status = $_POST['feed_id'];
$idPerson = $_SESSION['user_id'];
$query = "UPDATE person SET status = '".mysql_real_escape_string($status)."'
WHERE idPerson = '$idPerson'";
$query_run = mysql_query($query);
?>
at the moment the sql database does not update when i click of the input box. Any help would be great!!
Answer:
You have to devide scripts and html output
You forget );.You have to close $.ajax block.
You miss } closing function saveStatus().
Code:
<script>
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}); // <-- Also, you forget `);` here
} // <-- Also, you foget closing `}` here
</script>
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
Not error, but advice:
Also, note this: you used jQuery ajax function, so use jQuery in other cases too (you used pure JavaScript instead).
You getting value this way:
var status = document.getElementById("statusForm").value;
Use jQuery syntax instead:
var status = $("#statusForm").val();
Additional info
As, #Utkanos noticed in comments to this answer:
...all of which would be obvious if you look in the error console.
You have to use some debug tool, like FireBug or DevTools (Chrome, also in Chrome you can use CTRL+SHIFT+J). Not have to. You MUST do it.
I have thoroughly researched this topic, but cannot seem to find an answer due to the fragmented nature of the discussions and the very different use cases everyone seems to have.
I am using JQuery mobile to send data to a PHP login/registration script via $.ajax() call. It appears that the data I am trying to send never makes it to the server to be evaluated, and I am at a loss as to why.
I am trying to send the data from this form:
<div data-role="content">
<form id="reg_form" data-ajax="false">
<div data-role="fieldcontain">
<label for="reg_email">Email:</label>
<input type="email" name="reg_email" id="reg_email" value="" />
<label for="reg_pass">Password:</label>
<input type="password" name="reg_pass" id="reg_pass" value="" />
<label for="reg_pass_conf">Password:</label>
<input type="password" name="reg_pass_conf" id="reg_pass_conf" value="" />
<h4 id="reg_notification"><?php echo 'Notifications will appear here...'; ?></h4>
<button data-theme="b" id="reg_submit" type="button">Register!</button>
</div>
</form>
</div>
Which is triggered by this javascript:
$(document).on('pageshow', '#reg_page', function() {
$("#reg_notification").text("page loaded");
$(document).on('click', '#reg_submit', function(){
$("#reg_notification").text("button clicked");
var formDataReg = $("#reg_form").serialize();
$.ajax({
type: "POST", // Method of sending data to server
url: "php_scripts/reg_handle.php", // php script being sent to
cache: false, // requested pages won't be cached by server
data: formDataReg, // data to be sent to server
dataType: "json", // data type to be received back from server
success: onRegSuccess, // function to call on success
error: onError // function to call on error
});
return false;
});
});
function onRegSuccess(data, status)
{
alert(data);
$("#reg_notification").text(data.email + ' ' + data.pass + ' ' + data.pass_conf);
}
Which is sent to this php script:
<?php
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
?>
However, as stated earlier, the if/else block detects that $_POST['formDataReg'] is not even set. When I try to use it to assign values to variables, it obviously has no data to assign and I get null values.
I used alert to verify that indeed formDataReg did hold the proper form values before being passed to the server in the ajax call. It somehow gets lost in the ajax call, or I am not accessing it correctly.
If someone can point me in the right direction, I would very much appreciate it.
By this:
var formDataReg = $("#reg_form").serialize();
You serialized your form into the form. Now in formDataReg has such contents:
reg_email=xxx#gmail.com®_pass=yyy®_pass_conf=yyy
You have to parse this query in your php file:
$email = $_POST['reg_email'];
$pass = $_POST['reg_pass'];
$pass_conf = $_POST['reg_pass_conf'];
But you tried to work with $_POST['formDataReg'] which wasn't sent. So it is wrong. Yes, you had variable formDataReg in your JS, but it means nothing. You had sent serialized string (query) with your ajax-request and have to handle it.
So this code:
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
wouldn't work because you hadn't sent formDataReg and there are no value with this key in $_POST array.
This:
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
should work properly.
Let me know is something is unclear.
I was trying to create a autocomplete box that gets stock symbols and names from finance.yahoo.com according to the user query typed in typeahead text box.
I created a quote_form.php page in which there is a text box on which i applied jquery keyup function to get the characters when typed by the user and then based on that characters i made a get request inside my typeahead function on my php page called symbols.php which inturn calls this link below:
http://d.yimg.com/aq/autoc?query=$search®ion=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks
In the above link $search contains the characters received by get request and then in response i received JSON data with some junk i cleared the junk and then made it a legitimate JSON data and from that JSON data i created a string that looks like javascript array with the field i needed from the JSON. So, when my quote_form.php receives that data it does not shows it in typeahead. I surely receive data as i have seen in chrome's inspect element's Network tab. The code for both the pages is as below, i have created a seperate html header so i will not include the same as it is not necessary:
I have included the necessary javaScript files and CSS files:
jquery version used: 1.8.2
Bootstrap version used: v2.2.1
quote_form.php
<script type ="text/javascript">
$(document).ready(function () {
var key;
$("input[name='symbol']").keyup(function() {
console.log("Key pressed");
window.key = $(this).val();
});
$("input[name='symbol']").typeahead({
source: function(query, process) {
return $.get('symbols.php', {s: window.key}, function(data) {
console.log(data);
return process(data);
});
}
});
});
</script>
<form action="quote.php" method="post">
<fieldset>
<div class="control-group">
<input id = "sy" autofocus autocomplete ="off" name="symbol" placeholder="Symbol" type="text"/>
</div>
<div class="control-group">
<button type="submit" class="btn">Get Quote</button>
</div>
</fieldset>
</form>
symbols.php
<?php
$search = $_GET['s'];
$url = "http://d.yimg.com/aq/autoc?query=$search®ion=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks";
$raw_data = #file_get_contents($url);
$json = substr($raw_data, strpos($raw_data,'Result"') - 1);
$json = rtrim($json, '})');
$json = "{" . $json . "}";
$result = json_decode($json, true);
$jsarr = "[";
foreach($result as $symbols)
{
foreach($symbols as $symbol)
{
$jsarr .= "'".$symbol['name'] . " " . $symbol['symbol'] . "', ";
}
}
$jsarr .= "]";
echo $jsarr;
?>
I also tried the above code without converting to JavaScript array i.e i also tried with JSON only but that didn't work either. Seen many examples on internet also but still i am missing something don't know what. If any body can figure out what i am doing wrong that would be a great relief for me.
Thanks in advance.
The Yahoo API is actually returning a JSONP callback, you can avoid the parsing by making a jsonp request directly from jquery, you just need to build the YAHOO object that's specified in the callback:
var $typeaheadInput = $("input[name='symbol']");
$typeaheadInput.typeahead({
source: function (query, process) {
return $.ajax({
url: 'http://d.yimg.com/aq/autoc?query=' + query + '®ion=US&lang=en-US',
dataType: 'jsonp',
jsonpCallback: 'YAHOO.util.ScriptNodeDataSource.callbacks'
});
}
});
//Build YAHOO object with callback function
YAHOO = {
util: {
ScriptNodeDataSource: {
callbacks: function (data) {
var sourceArray = $.map(data.ResultSet.Result, function (elem) {
return elem.name + ' - ' + elem.symbol;
});
$typeaheadInput.data('typeahead').process(sourceArray);
}
}
}
};
Here's a working fiddle
Note: I removed the autofocus attribute from the input because it was causing issues with the typeahead dropdown