I have a web page which fill's form data based on some json data sent from a web service. Once the form is ready to be submitted a function is called which takes all the form data turns it into a xml-formatted string then parses the xml so it becomes a valid xml object. This is where the problem happens, once this data is turned into an xml I would like to post this data back to the web service so the database can be updated. However using the $.ajax() function to post this data, neither the success nor error function within are ever called. This lead's me to believe the ajax function is never being called or run. Below are the code snippets:
submit button for form:
<input type="submit" name="submitbutton" id="submitbutton" value="Submit" onclick="postData()"/>
postData function:
function postData()
{
//gathering all inputs
var cb = document.getElementById('paymentList');
var selected_cb = cb.options[cb.selectedIndex].text;
var pguid = getParameterByName('guid');
var xmlString = '<string>' +
addField('approver', $('#approver').val()) +
addField('companyName', $('#companyName').val()) +
addField('emailAddress', $('#emailaddress').val()) +
addField('address1', $('#address1').val()) +
addField('address2', $('#address2').val()) +
addField('city', $('#city').val()) +
addField('province', $('#province').val()) +
addField('country', $('#country').val()) +
addField('postalCode', $('#postalcode').val()) +
addField('phoneNumber', $('#phone').val()) +
addField('paymentMethod', selected_cb);
//gathering all table data now
xmlString+='<contractData>';
$('#table tbody tr:has(img[src="images/checkmark.png"])').each(function() {
xmlString += '<contract>' + addField('vendorPart', $('td:eq(1)', this).text()) +
addField('description', $('td:eq(2)', this).text()) +
addField('price', $('td:eq(3)', this).text()) +
addField('quantity', $('td:eq(4) input', this).val()) + '</contract>';
});
xmlString += '</contractData></string>';
//hard coded var for purpose of this example, as web service name will be
var properid = 'somedata';
xmlDoc = $.parseXML( xmlString );
$xml = $( xmlDoc );
//this function I believe is never run as neither alerts below are posted
$.ajax({
type: "POST",
url: "http://www.webservice.com/service.asmx/sendMeMyData",
data: {properdata:properid, xml: $xml},
dataType: "text",
success: function() {
alert("posted");
},
error: function ()
{
alert("error");
}
});
}
addField function (just so you know what it does when it's called in postData()):
function addField(name, value) { // Add a single element and value
value = value.replace(/&/g, '&').replace(/</g,'<').replace(/>/g,'>');
return '<' + name + '>' + value + '</' + name + '>';
}
Related
I have DataTables table with row details which are opening by clicking on row. The row details are displayed in 3 different languages which are selected by checkbox. When the row is clicked, the language is send to details.php script (langy:chLanguage) which returns json values for this selected language.
Initialy the language is set to chDe and everything is working fine until I click on another language. When the language is changed to EN or RU, or even back to DE, the returned json is empty.
index.php :
<h5>Language</h5>
<input type="checkbox" id="chDe" name="languages" checked>DE
<input type="checkbox" id="chEn" name="languages">EN
<input type="checkbox" id="chRu" name="languages">RU
<script>
var chLanguage = "chDe";
$('input[name=languages]').click(function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
chLanguage = [];
$('input[name=languages]:checked').each(function() {
chLanguage.push($(this).attr('id'));
});
if (chLanguage == '') {
chLanguage = 5;
}
$('#example').DataTable().ajax.reload();
});
function format ( rowData, row, $chLanguage ) {
// FOLLOWING CONSOLE.LOG RETURNS THE ACTUALLY SELECTED LANGUAGE CORRECTLY
console.log("chLanguage in format function: " + chLanguage);
var div = $('<div/>')
.addClass( 'loading slider' )
$.ajax( {
url: 'scripts/details.php',
data: {
name: rowData[0],
langy: chLanguage,
},
dataType: 'json',
type: 'post',
success: function ( json ) {
// FOLLOWING CONSOLE.LOG RETURNS [Object object] unless the language is changed, then it returns nothing
console.log("json: " + json);
var childTable = '<div id="rowdetails" class="slidera"><ul class="slider">';
childTable = childTable.concat(
'<div class="row rdstyle">' +
'<table class="detailstable detailserrors">' +
'<tr><td><b>Error class:</b></td><td>' + json[0].ERRTRIEDA + '</td></tr>' +
'<tr><td><b>Error group:</b></td><td>' + json[0].ERRSKUPINA + '</td></tr>' +
'<tr><td><b>Error:</b></td><td>' + json[0].ERRPOPIS + '</td></tr>' +
'</table>' +
'</div>
);
});
}
details.php :
$language = $_POST['langy'];
if ($language == 'chDe' ) {
$setLang = 'DE';
}else if($language == 'chEn') {
$setLang = 'EN';
} else{$setLang = 'RU';}
and $setLang is used in SQL query to filter data by language.
I hope I'm not far away from working solution, because it's working already, just the language switch don't work. Sorry not to attach working sample. I don't know how to implement all these parts including mysql db and several differenct php scripts :(
test.xml
<Bock1>
<No>123</No>
<RoomNo>10</RoomNo>
<UpdateTime>1230</UpdateTime>
</Block1>
run.js
$.ajax({
type: "GET",
url: test.xml,
dataType: "xml",
success: function (xml) {
$(xml).find('Block1').each(function () {
var updateTime = $(this).find("UpdateTime").text();
var no= $(this).find("No").text();
var roomNo = $(this).find("RoomNo").text();
var status = no + '<br/>' + roomNo + '<br/>' + updateTime;
});
}
});
$('<div>')
.attr({
'data-role': 'collapsible', 'data-collapsed': 'false', 'data-mini': 'true'
})
.html('<h4>' + item_name + '</h4><p>' + status + '</p>')
.appendTo(collapsibleset);
}
});
I'm using this to generate collapsibleset with xml data,
but status can't correctly fill into
<p> + status + </p>
status will get correctly inside ajax, but can't get to collapsibleset.
I've tried to use global variable, but get same situation.
How could I fill it in correctly?
I'm new to jquery & javaScript,
Thanks for any answers!!!
jQuery.ajax() is expecting string for the URL value.
Therefore your URL just needs wrapping in quotes.
Then your DOM reference of the
$('< div >')
is wrong.
To reference an element in JQuery, you have several options, but the easiest is to give an element an id and then reference that (think CSS)
$('div') would get all divs
$('div#my_id') would get this particular element:
I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}
I have this simple code as part of a PHP file, the purpose of this code is to execute the job1.js file on the client side (has to be done so), in this file I have a function called job1() that returns 3 variable back. The returned variables must be passed to the Server for further work.
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type = "text/javascript" >
$(document).ready(function() {
// $jobJSPath[0] holds the path to the job1.js file
var scriptPath = "<?php echo $jobJSPath[0]; ?>";
$.getScript(scriptPath, function(data, textStatus, jqxhr) {
// Call the function
job1();
window.alert( data ); // Data, actually it has only the content of the file as a string
window.alert( textStatus ); // Success
window.alert( jqxhr.status ); // 200
});
});
</script>
The function is being executed without any problems, it’s doing some internal string operations (very boring :) ) and returns 3 variables back.
My question is how do I get the 3 return variables from the job1() function with their input back. I searched a lot and even tried
var result = eval('(' + data + ')');
console.log(result);
Because the data variable holds the function as a string but still without any success, this option was suggested on some other page on this site.
EDIT: the data and the job1 have same text:
´function job1() {
var text = "";
var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 1; i <= 500; i++) {
text += vocabulary.charAt(Math.floor(Math.random() * vocabulary.length));
}
var subText1 = text.slice(0, Math.floor(Math.random() * text.length));
var subText2 = text.slice(subText1.length, text.length);
//test for output
alert("This is JavaScript");
var nextJob = "job2, job3";
var prevJob = "null";
return {
text_RT : text,
subText1_RT : subText1,
subText2_RT : subText2
};
}´
java script is for the client side, php is for the server side, just use ajax call and pass the data using post, after job1() is done and you got the returned array, just use an ajax call like this:
var yourdata=job1();
var postdata= [{"1": yourdata[0], "2": yourdata[1], "3": yourdata[2]}];
$.ajax({
type: POST,
data: postdata,
url: "test.php", //stands for the php file you want to send the data to
}).done(function() {
//do something.....
})
on the server side fetch the data using $_POST["1"] for example
Well that what I have until now
<script type = "text/javascript" >
$(document).ready(function() {
// $jobJSPath[0] holds the path to the job1.js file
var scriptPath = "<?php echo $jobJSPath[0]; ?>";
$.getScript(scriptPath, function(data, textStatus, jqxhr) {
// Call the function
var job = job1();
window.alert( data ); // Data, actually it has only the content of the file as a string
console.log(job); // shows all the return parameters from job1();
window.alert( textStatus ); // Success
window.alert( jqxhr.status ); // 200
// push the return parameters into result array
var result = [];
$.each(job, function(index, value) {
//window.alert(index + ": " + value);
result.push(value);
});
// post the results back to the same page
$.ajax({
type: 'POST',
data: {result : result},
url: 'executedJobs.php',
}).done(function(data) {
var redirectUrl = "executedJobs.php";
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="result" value="'+ data +'" />' +
'</form>');
$('body').append(form);
$(form).submit();
});
});
});
</script>
And after that to get the results on the the executedJobs.php page I used
<?php
$myArray = $_REQUEST['result'];
echo "myArray:<br/>";
print_r($myArray);
?>
It works that way, the only thing is I get the word myArray echoed twice every time before the print_r($myArray);.
I am calling an Ajax function from another function and want to get the response and then parse the Json in order to assign it to new divs.
The call is made like this: thedata = GetChequesByBatchID(batchId); and this is the response:
Then, I am trying to loop through the response, but this is where the problem is. I am not sure how to get the response and loop through the thedata. This data should be assigned to the htmlFromJson so it will be inserted as group of divs in the TR. Any ideas?
My function:
<script type="text/javascript">
$(document).ready(function (params) {
var batchId;
var thedata;
var htmlFromJson = "";
$('.showDetails').click(function () {
// Show Details DIV
$(this).closest('tr').find('.details').toggle('fast');
batchId = $(this).data('batchid');
thedata = GetChequesByBatchID(batchId);
var json = jQuery.parseJSON(thedata);
$.each(json, function () {
htmlFromJson = htmlFromJson + ('<div class="ListTaskName">' + this.ChequeID + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAccountNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAmount + '</div>');
});
}).toggle(
function () {
// Trigger text/html to toggle to when hiding.
$(this).html('Hide Details').stop();
$(this).closest("tr").after("<tr class='456456'><td></td><td colspan = '999'>" + '<div class="zzss">' + htmlFromJson + '</div></td></tr>');
},
function () {
// Trigger text/html to toggle to when showing.
$(this).html('Show Details').stop();
//$(this).find('.zoom').remove();
$('tr.456456').remove();
}
);
});
</script>
My Ajax function:
<script type="text/javascript">
function GetChequesByBatchID(BatchID) {
var xss;
var qstring = '?' + jQuery.param({ 'BatchID': BatchID });
return $.ajax({
url: '<%=ResolveUrl("~/DesktopModules/PsaMain/API/ModuleTask/GetChequesByBatchID")%>' + qstring,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
jQuery.parseJSON(result); //the response
},
error: function (response) {
alert("1 " + response.responseText);
},
failure: function (response) {
alert("2 " + response.responseText);
}
});
return xss;
}
</script>
$.ajax is async operation (if you don't include async:false option which is not recommended) so your GetChequesByBatchID function immediately returns either $.ajax object or undefined. Correct usage of $.ajax is to call DOM changing methods from success or error parts of $.ajax.