post data using ajax and js - javascript

Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}

Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});

Related

Debugger not reaching select statement in jQuery.autocomplete

I have a Dynamic Grid in the ASP.NET page. When I click Add User, it creates an empty record with Textbox controls and when the user types something in the first Textbox - UserName, it should pull the UserNames from the Database and autocomplete should work for that Textbox control.
I have implemented jQuery.autocomplete function as below.
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
success: function (data) {
switch (data) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
var rows = data.split("|");
var jsStr = "var datalist=[";
for (i = 0; i < rows.length - 1; i++) {
var s = rows[i].toString();
s = s.replace("'", "\\'");
s = s.replace('"', "\\'");
var row = s.split("~");
jsStr += "{id:'" + row[0].toString() + "'";
jsStr += ",name:'" + row[1].toString() + "'},";
}
jsStr = jsStr.slice(0, jsStr.length - 1);
jsStr += "];";
eval(jsStr);
if (typeof (datalist) != 'undefined') {
response(jQuery.map(datalist, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
When I try to Debug this autocomplete, the data is coming at the end of response(jQuery.map(datalist, function (items) statement. But the select: option is not firing.
EDIT
The below screenshot shows how the data is formed.
And this is what is present in the Server-Side Users.aspx.vb Page_Load Event
Response.Clear()
Response.Write(GetUserName(Request.QueryString("UserName")))
Response.End()
What could be the problem?
First. In the response, you check the data variable in swith. And you get it as a string.
Second. the best way to work with ajax is JSON.
jQuery.ajax({
url: url,
dataType: 'json'
On successful response:
Make parsing.
json = JSON.parse(data)
And then you already apply your logic, I work with individual object variables.
swith(json.string){ .... }
And it will be easier to fill Textbox controls with the necessary parameters: json.user - the variable will contain an array of data about users.
Update code:
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
dataType: 'json',
/*
* format respone data (string!!!) -> {"result": [{"id": 1,"item": 2},{"id": 1,"item": 2}],"found": "VALUESFOUND"}
*/
success: function (data) {
let json = JSON.parse(data);
switch (json.found) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
response(jQuery.map(json.result, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});

JS insertHtml without focus?

I have some code written in PHP with textarea input field. I also have a JS code that inserts html code into field:
$('form textarea#response').ready(function() {
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0, len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
var test = populateGet();
var ticid;
for(var key in test) {
if(Object.prototype.hasOwnProperty.call(test, key)) {
var val = test[key];
ticid = val;
}
}
$('form select#cannedResp').val('original');
var fObj = $(this).closest('form');
var $url = 'ajax.php/tickets/'+ticid+'/canned-resp/original.json';
$.ajax({
type: "GET",
url: $url,
dataType: 'json',
cache: false,
success: function(canned){
console.log('dupa');
//Canned response.
var box = $('form textarea#response'),
redactor = box.data('redactor');
if(canned.response) {
if (redactor){
redactor.insertHtml(canned.response);
}else{
box.val(box.val() + canned.response);
box.blur();
}
//if (redactor)
//redactor.observeStart();
}
//Canned attachments.
var ca = $('.attachments', fObj);
if(canned.files && ca.length) {
var fdb = ca.find('.dropzone').data('dropbox');
$.each(canned.files,function(i, j) {
fdb.addNode(j);
});
}
document.getElementById('focustest').focus();
}
})
.done(function() { })
.fail(function() { });
});
The problem is that execution of above code (redactor.insertHtml(canned.response);) causes focus on the textarea. The code is executed on page load.
Is there any way I can insert the content into field without causing the focus to placed on this field?
Thank you in advance and best regards
Tom

Undefined ajax response when page load

I have a script, below, and when the page loads I get an error message: Cannot read property 'length' of undefined, so I researched the error and found that the AJAX request wasn't executed. If I execute the same code in the browser console, the script works fine. What's wrong with my code?
<script>
function getCitiesList() {
var country_id = '189';
return $.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
});
}
function getCitiesList2() {
var bla = getCitiesList();
console.log(bla['responseJSON']);
var i = 0;
var data = [];
while (i < bla['responseJSON'].length) {
data[i] = {};
data[i]['id'] = bla['responseJSON'][i]['id'];
data[i]['text'] = bla['responseJSON'][i]['title'];
i++;
}
console.log(data);
}
$('#city').select2({
data: getCitiesList2(),
width: "100%"
});
</script>
Since JavaScript is asynchronous language, it just keeps running and doesn't wait for AJAX to return result.
In your code, the first line of getCitiesList2 function assigns the return value of an AJAX call. The AJAX returns later, and var bla doesn't yet have the response. To solve this, you can pass a callback to your AJAX function getCitiesList and execute it on AJAX success.
function getCitiesList(callback) {
var country_id = '189';
$.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
success: function(result) {
callback(result);
}
});
}
function getCitiesList2() {
getCitiesList(function(result) {
var i = 0;
var data = [];
while (i < result['responseJSON'].length) {
data[i] = {};
data[i]['id'] = result['responseJSON'][i]['id'];
data[i]['text'] = result['responseJSON'][i]['title'];
i++;
}
});
}
The problem is that console.log(bla['responseJSON']); in getCitiesList2 is executed before the ajax response is received. And after var bla = getCitiesList(); assignment, bla basically holds a deferred object. All you need to do is to assign a callback function that is going to be executed once the ajax call returns.
<script>
function getCitiesList() {
var country_id = '189';
return $.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
}).done(function(data){
$('#city').select2({
data: processCitiesResponse(data),
width: "100%"
});
});
}
function processCitiesResponse(data)
{
console.log(data);
var i = 0;
var options = [];
while (i < data.responseJSON.length) {
options[i] = {};
options[i].id = data.responseJSON[i].id;
options[i].text = data.responseJSON[i].title;
i++;
}
console.log(options );
}
</script>
first and second answer doesn't help, the same problem.
This work:
<script>
var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');
function Blabla(){
var country_id = '189';
$.ajax({
type: 'get',
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
success: function(bla){
var i = 0;
var data = [];
while (i < bla.length) {
data[i] = {};
data[i]['id'] = bla[i]['id'];
data[i]['text'] = bla[i]['title'];
i++;
}
$('#city').select2({
data: data,
width: "100%"
});
}
});
}
Blabla();
</script>

how to display json resful data using javascript or jquery

how do i display all content in my data array without repeating my self like i have done below .
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engrid2media.com/nextt/api/epg/schedule/id/",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
}).then(function(data) {
var result = data [0];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
$('.ch-type').append(result.type);
$('.ch-resolution').append(result.resolution);
var result1 = data [1];
console.log(result1);
$('.ch-name1').append(result1.ch_name);
$('.ch-logo1').append(result1.ch_logo);
$('.ch-desc1').append(result1.ch_desc);
$('.ch-genre1').append(result1.ch_genre);
$('.ch-type1').append(result1.type);
$('.ch-resolution1').append(result1.resolution);
var result2 = data [2];
console.log(result2);
$('.ch-name2').append(result2.ch_name);
$('.ch-logo2').append(result2.ch_logo);
$('.ch-desc2').append(result2.ch_desc);
$('.ch-genre2').append(result2.ch_genre);
$('.ch-type2').append(result2.type);
$('.ch-resolution2').append(result2.resolution);
var result3 = data [3];
console.log(result3);
$('.ch-name3').append(result3.ch_name);
$('.ch-logo3').append(result3.ch_logo);
$('.ch-desc3').append(result3.ch_desc);
$('.ch-genre3').append(result3.ch_genre);
$('.ch-type3').append(result3.type);
$('.ch-resolution3').append(result3.resolution);
var result4 = data [4];
console.log(result4);
$('.ch-name4').append(result4.ch_name);
$('.ch-logo4').append(result4.ch_logo);
$('.ch-desc4').append(result4.ch_desc);
$('.ch-genre4').append(result4.ch_genre);
$('.ch-type4').append(result4.type);
$('.ch-resolution4').append(result4.resolution);
var result5 = data [5];
console.log(result5);
$('.ch-name5').append(result5.ch_name);
$('.ch-logo5').append(result5.ch_logo);
$('.ch-desc5').append(result5.ch_desc);
$('.ch-genre5').append(result5.ch_genre);
$('.ch-type5').append(result5.type);
$('.ch-resolution5').append(result5.resolution);
});
});
This works fine , but it will be difficult to display over 20 items from the database with this method since i would have to do it one after the other.
A simple for loop would do it.
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.ch-name' + prefix).append(data[i].ch_name);
$('.ch-logo' + prefix).append(data[i].ch_logo);
$('.ch-desc' + prefix).append(data[i].ch_desc);
$('.ch-genre' + prefix).append(data[i].ch_genre);
$('.ch-type' + prefix).append(data[i].type);
$('.ch-resolution' + prefix).append(data[i].resolution);
}
});
Why not just write helper function?
Something like that.
function(data) {
var result,
suffix = '';
for (var i in data) {
result = data[i];
if (i > 0) {
suffix = i;
}
$('.ch-name' + suffix).append(result.ch_name);
$('.ch-logo' + suffix).append(result.ch_logo);
$('.ch-desc' + suffix).append(result.ch_desc);
$('.ch-genre' + suffix).append(result.ch_genre);
$('.ch-type' + suffix).append(result.type);
$('.ch-resolution' + suffix).append(result.resolution);
}
}
Try utilizing $.each()
$.each(data, function(key, val) {
var idx = key === 0 ? "" : key;
$(".ch-name" + idx).append(val.ch_name);
$(".ch-logo" + idx).append(val.ch_logo);
$(".ch-desc" + idx).append(val.ch_desc);
$(".ch-genre" + idx).append(val.ch_genre);
$(".ch-type"+ idx).append(val.type);
$(".ch-resolution" + idx).append(val.resolution);
});

Send back returned response to ajax call

I have a ajax function in index.php which calls on the page thread.php which returns a JSON response(array). I basically want to parse through that array, display it in a particular html format, take the last value of the last row of that array and send it back in the same ajax call previously mentioned. So that ajax is basically a loop.
function returnValue()
{
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
var dateposted = results[5];
}
}
}
}
});
}
The stored value dateposted needs to be sent as an input when making the ajax call. The default value of dateposted will be 0.
I am not sure if this can be done. I am open to suggestions.
You can make this a lot simpler, you don't need to use the extended GET syntax:
var returnValue = (function() {
var dateposted = 0;
return function() {
$.get("thread.php", { "lastposted": dateposted }, function(result) {
// display your chats
dateposted = result[result.length-1][5];
}, "json");
}
})();
One simple way to your problem is declaring dateposted with a default value outside the function call and use it in the loop to store to store the last value. And have a new Ajax function call. I hope this is want you want.
function returnValue()
{
var dateposted=0;
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
dateposted = results[5];
}
}
}
}
});
}

Categories

Resources