HighStocks not updating URL - ajax

I posted this question AJAX URL update as I thought the problem with my code was with AJAX but I think this could be an issue with HighStocks.
I have an external .js file with these functions:
//uses AJAX call to retrieve data and then creates the chart with the data
function createChart(ticker) {
$.ajax({
type: 'post',
url: 'http://...' + ticker + '....com',
success: function (data, status) {
//chart is rendered in here
}
//gets the user inputted ticker symbol from a HTML input box
// and passes to chart function
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
My HTML file just has a simple form with an input box and a button that when clicked calls the getTicker function. For some reason the chart is not being created and the AJAX call doesnt seem to work.
Is this something with HighStocks maybe? Any suggestions would be appreciated.
UPDATE Thank you for the suggestions, I have attempted to use JSONP but the chart still does not load. Can anybody see what I am doing wrong?
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}

Thanks to Jeffrey Blake and Pawel Fus for your suggestions. Using JSONP I was able to get my program functioning correctly :)

Related

Materialize autocomplete : Why AJAX called before entering any character?

I'm using autocomplete with materialize and i'm retrieving the data with ajax call, it works fine but when i want to call ajax only after entering caracters(using onkeyup event), the drop down list will not be showing correctly !!!!
Before i forget please help me to show a "NOT FOUND" in the drop down list if no data founded (because my else condition doesn't work). here is my code and thanks a lot in advance :
$(document).ready(function() {
var contents = $('#autocomplete-input')[0];
contents.onkeyup = function (e) {
$.ajax({
type: 'GET',
url: Routing.generate('crm_search_lead', {"search":
$(this).val()}),
success: function (response) {
var contacts = {};
if (true === response.success) {
var result = response.result;
for (var i = 0; i < result.length; i++) {
var lastName = result[i].lastName ?
result[i].lastName : '';
var firstName = result[i].firstName ?
result[i].firstName : '';
contacts[lastName + " " + firstName] = null;
}
$('input.autocomplete').autocomplete({
data: contacts,
minLength: 2,
});
} else {
$('input.autocomplete').autocomplete({
data: {
"NOT FOUND": null
}
});
}
}
});
}
});
Hi people :) i resolve it by changing onkeyup() with focus() and it's totally logical because with onkeyup() the droplist will appear and disappear very quickly on every key entered.

admin-ajax.php do not recognizes 'action'. $_REQUEST is empty

After two days of fruitless research, I decided to join the community. I hope to get a solution. I develop a plug-in that, among other things, must implement the upload of documents. this should be done using ajax technology. the problem is that the request is approved, but admin_ajax.php reacts like no action was taken. Outside of wp this piece of code works fine, as it was thought out. The problems come with installing this code in wp. Below is my code
PHP. This code in the main class that will call from main modul of plugin
class main{
//other activation methods
private function register_scripts(){
add_action('wp_enqueue_scripts', array($this,'re_add_script'));
}
public function re_add_script() {
wp_enqueue_script('re_upload',plugins_url('re'.'/js/re_upload.js'),array('jquery'));
wp_localize_script('re_upload',"re_ajax",array(
'ajaxurl'=>admin_url("admin-ajax.php")));
add_action( 'wp_ajax_upload', 'processingUpload');
}
}//end of class
//callback function
function processingUpload(){
$clsUpload = new UploadsDocs();
$clsUpload->setRequestedData($_FILES,$_POST['doc_id']);
$clsUpload->checkUploadsFiles();
$clsUpload->outputFilesList();
wp_die();
}
jQuery 're_upload.js'
jQuery(document).ready(function (e) {
jQuery('#bt_upload').on('click', function () {
var toUpload=getFileListToUpload();
var form_data = new FormData();
var ins = input.files.length;
for (var x = 0; x < ins; x++) {
if (isFileToUpload(input.files[x],toUpload)){
form_data.append("files[]", input.files[x]);
}
}
form_data.append("doc_id", jQuery('#doc_id')[0].value);
var data_to_sent={
action: 'upload',
datas: form_data
};
jQuery.ajax({
url: re_ajax.ajaxurl, // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: data_to_sent,
type: 'post',
success: function (response) {
// do something
},
error: function (response) {
// do something
},
xhr: function(){
//upload Progress
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
jQuery('#bt_upload').css("display","none");
jQuery('#progress-wrp').css("display","block");
jQuery('#progress-wrp' +" .progress-bar").css("width", + percent +"%");
(percent<50)? jQuery('#progress-status').addClass('status-less-then-50'): jQuery('.status-less-then-50').removeClass('status-less-then-50').addClass('status-more-then-50');
jQuery('#progress-status').text("Uploading..."+percent +"%");
}, true);
}
return xhr;
},
mimeType:"multipart/form-data"
});
});
});
function getFileListToUpload(){
var list=[];
var elem = document.getElementsByClassName('preview');
var tag_li=elem[0].querySelectorAll('p');
for (var i=0;i<tag_li.length;i++){
list[i]=tag_li[i].textContent.split('(')[0];
}
return list;
}
function isFileToUpload(input_file,files_toUpload){
var res=false;
for(var i=0; i<files_toUpload.length;i++){
if (input_file.name==files_toUpload[i]){
res=true;
break;
}
}
return res;
}
The problem is
add_action( 'wp_ajax_upload', 'processingUpload');
is not called.
The upload is done in two separate invocations of the server. The first invocation displays the upload page to the user. The second invocation processes the AJAX request. Your call to
add_action( 'wp_ajax_upload', 'processingUpload');
is done in the first invocation where it is not needed but not in the second invocation where it is needed.
Please read https://codex.wordpress.org/AJAX_in_Plugins. (Observe carefully how the call to 'add_action( 'wp_ajax_...', ...) is done.) Further, you need to read about nonces.
Try to append action to your ajax url like:
url: re_ajax.ajaxurl?action=upload
and
data: form_data
or pass it to form_data like:
form_data.append('action', 'upload')

Dragula not sending AJAX request

I am using the following code to sort the rows of a table based on Ids. I am using Dragula for drag and drop functionality. The Sorted Ids is presented in the variable sortedIDs. The alert present within if(sortedIDs) is showing an alert, but no request is being sent using AJAX.
var container = document.getElementById('tb');
var rows = container.children;
var nodeListForEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
var sortableTable = dragula([container]);
var pingu='';
sortableTable.on('dragend', function() {
nodeListForEach(rows, function (index, row) {
//alert(row.id);
pingu=pingu+','+row.id;
//alert(pingu);
// row.lastElementChild.textContent = index + 1;
// row.dataset.rowPosition = index + 1;
});
var sortedIDs=pingu;
pingu='';
// alert (sortedIDs);
if (sortedIDs) {
alert(sortedIDs);
$.ajax({
type: 'GET',
url: '<?php echo $site_url . 'index.php/API/p2376ghDSPOLWYBdhBT'?>',
data: 'lmqSPOEhyVt87H6tBYSfdreg=' + sortedIDs + '&hjhqweuty87685gh87GCfsc6HF=' + sbds98JWUDGHKJ98yujg,
success: function (tata) {
alert (tata);
if (tata == '1') {
$("#success").show();
$('#success').delay(2000).fadeOut('slow');
} else {
$("#failure").show();
$('#failure').delay(5000).fadeOut('slow');
}
}
});
} else {
//$('#ms').html('<option value="">Select Q level first</option>');
}
});
And when i am adding
error : function(jqXHR, textStatus, errorThrown){
}
for showing AJAX error, it starts throwing the alert too.
Any sort of help would be deeply appreciated.
Thanks
I solved the problem. I forgot to retrieve the value of an attribute and send it to the API.
var sbds98JWUDGHKJ98yujg = $('#p2JMopns3hfBubNNHJeer').val();

MVC ajax testing form submission

I am trying to submit a form using ajax and want to check to see if the
correct values are sent. How do I do it using the following. Currently, it is sending it to a MVC controller, but I do not want to do that. Is there a way to just sent to the same view page and show all the values???
$(document).ready(function () {
$("#btnSubmit").click(sendValues);
});
function sendValues() {
var a = store.data.items;
var array = new Array();
for (var i = 0; i < store.data.items.length; i++) {
array[i] = store.data.items[i].data;
}
for (var i = 0; i < array.length; i++) {
if (array[i].value == "Using") {
array[i].value = true;
}
else {
array[i].value = false;
}
}
var ClintJSON =
{
"Exempt": Ext.getCmp("mmrComboBox").isIndexSelected(2),
"MM1": Ext.getCmp("mmrComboBox").isIndexSelected(3),
"MM2": Ext.getCmp("mmrComboBox").isIndexSelected(4),
"MM3": Ext.getCmp("mmrComboBox").isIndexSelected(5),
"B1": Ext.getCmp("BComboBox").isIndexSelected(2),
"B2": Ext.getCmp("BComboBox").isIndexSelected(3),
"B3": Ext.getCmp("BComboBox").isIndexSelected(4)
};
$.ajax({
jsonp: null,
jsonpCallback: null,
type: 'POST',
url: '#Url.Content("~/Site/Test")',
data: "{clinsite: " + Ext.util.JSON.encode(ClintJSON) + ", List: " + `
Ext.util.JSON.encode(array) + "}",
dataType: 'json'
, contentType: 'application/json; charset=utf-8'
, success: function (data) {
if (data.success) {
showMessage('Site requirements have been updated successfully');
store.load({ params: { start: 0, limit: 52} });
} else {
showMessage('Site requirements have NOT been updated!!! ');
store.load({ params: { start: 0, limit: 50} });
}
}
});
There is one tool that I cannot recommend enough in this type of scenario, Fiddler2.
You can download it here
It enabled you to examine exactly what is passed to and from the server and you can view the data in various formats i.e. json, web form data or plain old text.
You can also use Composer to simulate http requests, which has its obvious benefits.
As a profession web applications developer, I use this tool all day every day, like I said I can't recommend it enough!!
Cheers
Baz
you can inspect the values in firefox using firebug console or in chrome tools, just press f12 and a window will open infront of your
moreover you can log the ClientJaon to the console liek
console.log(ClintJSON );

Adding a .ajaxForm function to standard .ajax call

So I'm trying to find a method of getting a progress bar working on my .ajax call but not having much luck. I know that the ajaxForm plugin has the following code in it that allows for the uploadProgress option but the way my code works I'm not able to use that plugin. Is there anyway of adding the following code somehow so that it attaches to the standard .ajax call? Long shot I know!
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++)
if (serializedData[i])
formdata.append(serializedData[i][0], serializedData[i][1]);
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}
I do not guarantee on that, but try this:
xhr.upload.onprogress = function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
console.log("Progress: "+percent+"%"); //debug to see if the problem is there
options.uploadProgress(event, position, total, percent);
};
From posted code, I cannot even guess if the problem is in onprogress event handling or that options.uploadProgress, whatever it is.
I posted this as answer only because it wouldn't fit in comment.

Resources