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 );
Related
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.
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')
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 :)
I have the following situation: I need to make synchronized Ajax requests within a loop and display the returned result after each iteration in a div-element (appended on top with the previous results at the bottom). The response time of each request can be different but the order in which it should be displayed should be the same as issued. Here is an example with 3 requests. Lets say request "A" needs 3 seconds, "B" needs 1 second and "C" needs 5 seconds. The order I want to display the result is A, B, C as the requests were issued but the code I use shows the results in B, A, C.
Here is the code (JQuery Ajax request):
$(document).ready(function(){
var json = document.getElementById("hCategories").value;
var categories = eval( '(' + json + ')' );
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
$("#content").append(data);
}
});
});
I thought it would work with "async:false" but then it waits until every Ajax call is finished and presents the results after the loop. I hope some of you can point out some different solutions, I am pretty much stuck.
Thanks in advance,
Cheers Chris
EDIT: Thanks for all the possible solutions, I will try these now one by one and come back with that one that fits my problem.
I have two solution proposals for this problem:
Populate generated divs
You could generate divs with ids in the loop and populate them when the request finishes:
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
for (curCat in categories) {
(function(curCat) {
var curCatKey = categories[curCat]['grKey'];
$('#content').append('<div id="category-"' + escape(curCat) + '/>');
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val()),
success: function(data) {
$("#category-" + escape(curCat)).html(data);
}
});
})(curCat);
}
});
Or use a deferred
You can store jqXHR objects in an array and use a deferred to call the success functions in order, when all calls have finished.
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
var requests;
for (curCat in categories) {
var curCatKey = categories[curCat]['grKey'];
requests.push($.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val())
}));
}
$.when.apply(requests).done(function() {
for (i in requests) {
requests[i].success(function(data) {
$("#content").append(data);
});
}
});
});
The first method has the advantage that it populates the containers continuously. I have not tested either of these function, but the logic should work the way I described it.
This would do the trick
var results = [];
var idx = 0;
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
(function( i ) {
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
results[i] = data;
if (i == idx - 1) { // last one
for (var j=0; j < results.length; j++) {
$("#content").append(results[j]);
}
}
}
});
})(idx++);
I think something like this is what you're looking for. Might need some tweaking, I'm a little rusty on Deferred. Read up on it though, mighty powerful
deferred = $.Deferred()
for(curCat in categories) {
deferred.pipe(
function(resp){
postData = {} // set up your data...
return $.post("get_results.php", {data: postData, timeout: 8000})
.done(function(content){ $("#content").append(content) })
})
)
}
// Trigger the whole chain of requests
deferred.resolve()
I am working on my first implementation of a jqGrid. I am using the standard add/edit buttons that appear in the navGrid but am having problems identifying how process the server response when I click Submit in the edit/add forms.
.navGrid("#product-codes-footer",{edit:true,add:true,del:false},
{afterShowForm:afterShowEdit}, {afterShowForm:afterShowAdd} );
Is there a standard callback or event parameter I am missing somewhere regarding this? Is there a way to define how saveRow is called or is there a default success/error callback method I can implement?
Any direction would be much appreciated!!!
There appears to be a couple event parameters that I failed to completely read and comprehend...
API --> http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing#editgridrow
using the event parameters for afterSubmit and afterComplete allow me to process the server response and update the form.
--Dan
EDIT
Here is an example of the code used...
.navGrid(
"#product-codes-footer",
{edit:true,add:true,del:false},
{
afterShowForm:afterShowEdit,
afterSubmit:processAddEdit,
beforeSubmit:validateData,
closeAfterAdd: true,
closeAfterEdit: true
},
{
afterShowForm:afterShowAdd,
afterSubmit:processAddEdit,
beforeSubmit:validateData,
closeAfterAdd: true,
closeAfterEdit: true
}
);
function afterShowEdit(formId) {
//do stuff after the form is rendered
}
function afterShowAdd(formId) {
//do stuff after the form is rendered
}
function processAddEdit(response, postdata) {
var success = true;
var message = ""
var json = eval('(' + response.responseText + ')');
if(json.errors) {
success = false;
for(i=0; i < json.errors.length; i++) {
message += json.errors[i] + '<br/>';
}
}
var new_id = "1";
return [success,message,new_id];
}
There are a few ways I have seen to do this:
jQuery("#search_results").jqGrid({
url: host,
datatype: "xml",
mtype: "GET", // Handy to see the params passed.
height: 200,
width: 500,
...
...
etc
gridComplete: function() {
var ids = jQuery("#search_results").getDataIDs();
if (ids.length Empty Result');
}
else {
$('#jqgrid_error').hide();
}
},
loadError: function(xhr,st,err) {
jQuery("#jqgrid_error").html("Type: "+
st +"; Response: "+ xhr.status + " "+xhr.statusText+'');
}
}).navGrid('#search_results_pager',
{edit:true,add:false,del:false,search:true},
{
afterComplete:processed, // processed is a function you define
closeAfterEdit: true,
reloadAfterSubmit:true
}
);
From the documentation:
afterComplete
This event fires immediately after all actions and events are completed
and the row is inserted or updated in the grid.
afterComplete(serverResponse, postdata, formid) where
response is the data returned from the server (if any)
postdata an array, is the data sent to the server
formid is the id of the form
gridComplete
This fires after all the data is loaded into the grid and all other
processes are complete.
loadError xhr,st,err
A function to be called if the request fails. The function gets passed
three arguments: The XMLHttpRequest object (XHR), a string
describing the type of error (st) that occurred and an optional
exception object (err), if one occurred.
There is a handy/helpful PDF documents (a little dated):
http://www.scribd.com/doc/17094846/jqGrid.
You could try this:
navGrid('#gridpager',{view:true},{},{closeOnEscape:true},{afterSubmit:processAddEdit});
$.jgrid.search={
odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','like','does not contain'],
sopt:['eq','ne','cn','bw','ew']
}