I have a PHP script that loads XML content dynamically:
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($nice)
->show(array('name','Price'))
->query();
echo $result
This will work fine when it is loaded. But I am trying to use an ajax/jquery script to send the value $nice to the PHP script; and to ultimately send the result back from the dynamically created XML file. I've been trying to figure this out for hours
Here is the ajax Script
function sendValues() {
$("$nice")
$.ajax({
url: "/myphp.php",
data: {str}
cache: false
});
}
Has anybody done something similar to this concept?
Why not pass it as a GET param like so...
jQuery
function sendValues(something) {
$.ajax({
url: "/myphp.php?nice=" + something,
cache: false,
dataType: 'xml',
success: function(xml) {
// Work with the XML
}
});
}
PHP
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($_GET['nice'])
->show(array('name','Price'))
->query();
// You said it is XML?
header('Content-Type: text/xml');
echo $result;
Related
I have a problem with the communication between AJAX and PHP. I've already tried all these pieces of code from related questions and answers but nothing worked. This code should recieve a JSON string from a PHP file on the same server and display the values in the HTML area.
$(document).ready(function(){
setInterval(ajaxcall, 1000);
});
function ajaxcall(){
var data = $('#signup_form').serialize();
$.ajax({
type: "GET",
url: "test.php",
data: data,
dataType: 'json',
success: function (data) {
window.console.log("Success");
document.getElementById("count").innerHTML = $('#time').html(data.time);
},error: function alert(){"error";}
});}
When I execute the script in my browser (with debug mode) then nothing happens. I assume this implies a problem with the 'success' method.
Here is a part of my PHP code (for testing):
for($i = 0; $i < 50; $i++){
sleep(1);
return_json($argv[1]);
}
//return all values for html/javascript
function return_json($a){
$json = array('time' => $a);
echo json_encode($json);
}
I hope some of you can help me :)
Is the function ajaxcall() really being called? Try to add a console.log call at its begining, eg
function ajaxcall(){
var data = $('#signup_form').serialize();
console.log(' form data = %o', data)
//...
There is another possible issue the function error: function alert(){"error";} does nothing visible. If your server script is returning an error you will see nothing in this case.
Change it to something like
error: function(){ alert("error"); }
You should add the content type to your response header:
//this line
header('Content-type: application/json');
for($i = 0; $i < 50; $i++){
sleep(1);
return_json($argv[1]);
}
//return all values for html/javascript
function return_json($a){
$json = array('time' => $a);
echo json_encode($json);
}
Further reading and a more detailed explanation here: jQuery $.ajax request of dataType json will not retrieve data from PHP script
I am currently migrating an already built web application to MVC, and I'm figuring out that I'm too newbie to do some kind of changes. There are some ajax calls that are freaking me out. I'll try to be as clear as possible, but due to my inexperience I'm not sure if I won't let some important information by the way.
The point is in the old application, things go this way:
In the php code:
if ($action_user == 'show_alerts') {
$list = array();
$query = "SELECT alert_type FROM alert_contact WHERE NOT
deleted AND user_email=" . typeFormat($email);
$result = mysqli_query($db, $query) or die('Error in query "'.$query . '": ' . mysqli_error($db));
while ($db_field = mysqli_fetch_assoc($result)) {
$list[] = $db_field['alert_type'];
}
echo json_encode($list);
In the jquery code:
$.ajax({
type: 'POST',
url: 'userpost.php',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Here comes my problem, and since I don't have an userpost.php file anymore, I have to send it to the index.php and call my users component by a get petition, which I don't like, but I coudn't find another way to do it. And, what is even worse, I don't know at all how ajax is getting the variables that it needs. It must be a pretty basic mistake, but I recognize my skills at this point are't so good. That's what I'm doing in my version:
In the php code:
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
In the jquery code:
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json',
success: function(data) {
alert ('gotcha');
$.each(alertsarray, function(index, value) {
if ($.inArray(value, data) === -1) {
$("#sub" + value).prop("checked", false);
$('#alert' + value).removeClass("list_alert_sub");
}
else {
$("#sub" + value).prop("checked", true);
$('#alert' + value).addClass("list_alert_sub");
}
});
},
error: function(data) {
alert("¡Error (ajax)!");
}
});
Any help would be appreciated, and if there's some more information I've missed, please let me know. Thanks in advance.
UPDATE:
I've been making some progress but don't seem to find a real solution. Now I know that the url has to be the controller, so I'm using 'components/userpost/controller.php' as it, and it reaches the ajax call, cause the success alert is showing up. The problem is the MVC way, because I send ajax to the controller, but since I don't have a reload in the page, all the includes are failing so they are obviously not being loaded, and I'm getting errors like this:
PHP Warning: include(components/userpost/model.php): failed to open
stream: No such file or directory in
/var/www/html/viewer_mvc/components/userpost/controller.php on line 3,
referer: http://localhost/viewer_mvc/index.php
Really hope you guys can show me where am I failing, and if there's a special way to do these thing in MVC.
For the JQuery call it makes a POST request to index.php?option=users with JSON data. The form with the ID userForm is serialized using the Jquery serialize method.
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Now for your PHP sample
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
This code will be looking for variables that probably don't exist anymore if it is a different file i.e. is there an $action_user variable?
To start reimplementing it you will need to add the logic so that it checks the POST variable if your not using the framework code. So if you have a form element with the name 'name' then that will be available in your PHP script POST variable
$_POST['name']
[How to call a PHP function in MVC using AJAX]
$.ajax({
type: 'POST',
url: 'save-user.php',
data: { fname: "manish", email: "manishkp#com", role:"admin"},
success: function(data) {
console.log(data);
if(data == 'error')
{
$('#Register_error').text('Must Be filled...');
$('#Register_error').show();
}
else {
$('#Register_error').hide();
$('#Register_success').text('Successfully submit');
$('#Register_success').show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$fname = $_POST['fname'];
$email = $_POST['email'];
$role = $_POST['role'];
if(!empty($fname) && !empty($email) && !empty($role))
{
#MYSQL CONNECTION QUERY #
echo"success";
}
else{
echo "error";
}
?>
I'm attempting to access data cross domain (testing locally) but the data keeps failing to load.
$.ajax({
type: 'POST',
url: 'http://localhost/php/ajax/json.php',
dataType: 'jsonp',
data: {action: 'get_json'},
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error loading data");
}
});
The PHP is as follows (function is called through a switch statement earlier in the file).
function get_json() {
$mysqli = db_connect();
$sql = "SELECT * FROM json_test";
$result = $mysqli->query($sql);
$rows = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($rows, $row);
}
}
echo $_GET['callback']."(".json_encode($rows).");";
}
Headers are set at the start of the PHP document.
header('Content-Type: application/json');
The error I am receiving (if I run the PHP file by itself) is Undefined index: callback. The json string echoes fine as text after this error. (I have tried echo $_POST[...] as well).
How can I get this callback to work or how do I define it properly? Any help is appreciated.
add this parameter:
&jsoncallback=?
I was able to fix the error in the PHP file by changing the callback to the following:
$callback = "";
if (array_key_exists('callback', $_GET) == TRUE) {
$callback = $_GET['callback'];
}
echo $callback."('".json_encode($rows)."');";
The AJAX query now also retrieves the JSON data successfully.
Okay, I asked a question earlier but I've run into a whole new problem. I have a PHP array in a PHP script server side. I am trying to write a Client side Ajax script to repoll the PHP script for new data and update the statistics displayed on the page.
Heres the Ajax that im sure im not doing right:
setInterval(function(getLatestInfo)
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'id=data',
dataType: 'json',
cache: false,
success: function(getLatestInfo){
$.getJSON(script.php, function(getLatestInfo){
var result_array = JSON.parse(result);
});
$('#bit_rate').html(result_array[4]);
$('#listeners').html(result_array[5]);
$('#current_song').html(result_array[9]);
});
});
}, 10000);//time in milliseconds
And here is the PHP:
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '00000000000000000';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output = curl_exec($ch);
curl_close($ch);
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
In short, I need this ajax script to update and pull the PHP variable $dp, which is an array, parse it out, and create HTML usable string variables. And repeat the process every 10 seconds.
Don't use setInterval in this instance. In the success callback call the original function again. Also you are calling getJSON in the success callback of the ajax call - this is duplicating calls.
For example
function getlatest()
{
$.ajax({
//rest of ajax param
success : function(results){
var resultarray = $.parseJSON(results);
$('#bit_rate').html(result_array[4]);
$('#listeners').html(result_array[5]);
$('#current_song').html(result_array[9]);
getlatest();
}
});
}
i have a javascript code that requests a php page to provide it with list of names that are currently online and update a Table, but i have a problem sending it back in form of an array, someone told me that this is usually done using XML, but i dont know how to start.
javascript Post method:-
$.post( "updateTable.php", POSTdata,
function( data ) {
$("#mytable").last().append('<tr><td>'+data+'</td></tr>');
}
);
the php file:-
include("connect.php");
$query1 = "SELECT * FROM formtable";
$result_id = mysql_query($query1, $global_dbh)
or die ("display_db_query:" . mysql_error());
while ($table_array = mysql_fetch_object ($result_id))
{
$rows[] = $table_array;
}
foreach ($rows as $temp ) {
if ($temp->isOnline==1)
$newRow[] = $temp->name;
}
echo "$newRow";
mysql_close($global_dbh);
Please excuse any syntax or semantics in my code, i am a beginner.
How can i populate my table using ajax callback function, and in what form the data will arrive there, and how can i use xml to help me.
Many thanks in advance.
A quick example of json:
var table = $("#mytable").last();
$.ajax({
type: 'post',
url: "updateTable.php",
dataType: 'json',
data: POSTdata,
success: function(data){
jQuery.each(data, function(i, row){
//console.log(row);
table.append('<tr><td>'+row.name+'</td></tr>');
});
}
});
and in php file, instead of :
echo "$newRow";
replace with:
echo json_encode($newRow);
That's it!