Events not triggered when posting json string using jquery [duplicate] - javascript

This question already has answers here:
jQuery posting JSON
(3 answers)
Closed 8 years ago.
I'm totally new to this, so apologies if I'm not explaining this correctly.
I want to post some data in json format to a rest service. I'm trying to get this work with JQuery in a simple .cshtml (razor) page.
My json string looks like this:
{
"ListRequest":{
"Values":[
{
"Name":"SC",
"Value":"PRO001"
},
{
"Name":"PC",
"Value":"Z0R14"
}
]
}
}
I need to pass 2 values from a form into this string and then post it but I'm not sure how do I declare this in javascript and then post it to my $.post function.
My HTML looks like this:
<form action="/" id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
I thought I'd just declare a var:
var jsonText = '{"ListRequest":{ "Values":[' +
'{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
'{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
Is that the correct way to handle this??
Then I've got my 'post' code to test:
var posting = $.post( url, term);
posting.done(function (data) {
var content = $(data).find("#content");
$("#result").empty().append(content);
});
But whenever I call this, it put these 2 values as part of a query string, instead of doing an actual post where this data is not visible in the url.
http://localhost/WebTest/WebDataService.svc/GetList?txtSC=brc001&txtPC=12345
Can someone tell me how to fix this??
Thanks.
UPDATE:
Here is the full code from my test page as it still not working for me. I just noticed that the submit event is not triggered. It seems to be putting the textbox and value automatically because they are part of the form, but my event is definitely not triggered as I've just commented all the code and put a alert('test'); and it didn't show up.
Any ideas?
Thanks.
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
// Attach a submit handler to the form
$("#getListForm").submit(function (event) {
event.preventDefault();
//var jsonText = '{"ListRequest":{ "Values":[' +
// '{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
// '{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonText, url = 'http://localhost/WebTest/DataService.svc';
$.post(url + '/GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
// Send the data using post
//var posting = $.post( url, term);
//posting.done(function (data) {
// var content = $(data).find("#content");
// $("#result").empty().append(content);
//});
});
</script>
#{
ViewBag.Title = "Json Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
<div id="result"></div>
Thanks.
UPDATE:
Latest code where I've updated the term to use the jsonObj and I've put my code in the $(document).ready block as suggested:
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Attach a submit handler to the form
$("#getDocumentListForm").submit(function (event) {
event.preventDefault();
alert('test1');
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PO",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonObj, url = 'http://localhost/WebTest/DataService.svc';
alert(term);
alert(url);
$.post(url + 'GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
//Tried posting using term but no luck. Same problem.
//$.post(url + 'GetList',
//function (data, status) {
// alert("Data: " + data + "\nStatus: " + status);
//});
// Send the data using post
//var posting = $.post(url, term);
//posting.done(function (data) {
// //var content = $(data).find("#content");
// //$("#result").empty().append(content);
// alert(data)
//});
alert('test2');
});
});
</script>
#{
ViewBag.Title = "Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getDocumentListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get Document List">
</form>
<div id="result"></div>
Finale Update on this question
MAKE SURE:
NOT TO USE IE11 WITH JQUERY, WELL AT LEAST JQUERY 2.1.1! DON'T KNOW HOW WELL IT WORKS WITH OTHER VERSIONS OF IE.
ALWAYS TEST WITH OTHER BROWSERS
MAKE SURE TO SET YOUR JQUERY SRC TO THE CORRECT HTTP OR HTTPS DEPENDING ON WHAT YOU USE.
That's it.

I suppose what's going on there is that you are trying to pass an undefined variable named term instead of jsonText, so the javascript code is throwing an uncaught exception and gets ignored, and you get a normal action from your form element.
You should pass the correct data. And also, knowing about JSON.stringify can probably save you a lot of time and headaches ;). You could build your object like so:
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
};
var jsonObj = JSON.stringify(obj);
Another pitfall I can think of in your code, is that you have bound your AJAX to a click event on your submit button, or to an onsubmit event, and you are not preventDefault()ing.
Edit
Given the code you posted, you have a couple of mistakes:
Did you wrap your code into a jQuery(document).ready() block?
You commented out jsonText but still assign it to the variable term, causing an uncaught exception.
Fix these two things and your POST request will be done correctly.
On the other hand, why on Earth are you using jQuery version 1.5?

Related

innerHTML from JSON-file

I just created a Google sheet document and converted it to JSON-file.
Sheet: https://docs.google.com/spreadsheets/d/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/edit#gid=0
JSON: https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json
Now, on the sheet I have text on cells A1 and A2.
I would like to display these lines on HTML-document.
Would somebody know how I can do this?
I think something is wrong at your JSON file, because Line 1 is missing, but based on your json here is how you can access the text:
const jsonResult = {"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended","id":{"$t":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},"updated":{"$t":"2020-01-09T13:49:33.116Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Taulukko1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"https://docs.google.com/spreadsheets/d/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/pubhtml"},{"rel":"http://schemas.google.com/g/2005#feed","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},{"rel":"http://schemas.google.com/g/2005#post","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic"},{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt\u003djson"}],"author":[{"name":{"$t":"contact.tjolanki"},"email":{"$t":"contact.tjolanki#gmail.com"}}],"openSearch$totalResults":{"$t":"1"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic/cokwr"},"updated":{"$t":"2020-01-09T13:49:33.116Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Line2"},"content":{"type":"text","$t":""},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic/cokwr"}]}]}}
const entries = jsonResult.feed.entry;
entries.forEach(function (arrayItem) {
const titleObj = arrayItem.title
const text = titleObj['$t'];
console.log("title object: " + JSON.stringify(titleObj, null, 2))
console.log("Text: " + text)
document.getElementById("result").innerHTML += text;
});
<div id="result"> Text: </div>
You can use json-pretty-print to see the json more clearly.
EDIT
I don't know if the json link is updated real time when you modify the sheet but you can do this:
Make a call to your json link with $.ajax({ type: "GET".. }) in order to retrieve the whole object that I pasted in the previews snippet (Read more about request from here jquery.get )
Make a callback function in order get the content after the request is finished (Read more about callbacks from Callback_function )
Apply the function who print the text
const jsonURL = "https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json"
function printTextFromJson(json) {
const entries = json.feed.entry;
entries.forEach(function(arrayItem) {
const titleObj = arrayItem.title
const text = titleObj['$t'];
console.log("title object: " + JSON.stringify(titleObj, null, 2))
console.log("Text: " + text)
document.getElementById("result").innerHTML += text;
});
}
function getJsonContent(callbackFunction) {
$.ajax({
type: "GET",
url: jsonURL,
success: function(returnValue) {
console.log(returnValue);
callbackFunction(returnValue); // callbackFunction is called when returnValue is ready.
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
},
dataType: "json"
});
}
getJsonContent(function(returnValue) {
printTextFromJson(returnValue)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"> Text: </div>
Sorry if the answer is a bit too complex, but everything has a start. If you have questions feel free to ask! xD
PS: try to change the sheet and run this snippet again, if it's not updating, then the two files are not in sync.
You have to import the .json-file in your js-code as an object. Then you can access to each value like you would with an "normal" object.
object.parameter

How to use for while or something like for while to sending data when trying to post something using jquery

I have some code like this :
<script>
for(i=0;i<=5;i++){name[i]: "name",}
</script>
and i know it's wrong because i want to use it on $.post and i don't know how can i do this
I tried this and this working well but I didn't add for while to this code because I don't know how to do this and i will show you where i want for while :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg",
// for(i=0;i<=5;i++){name[i]: "name",} // it's my custom data and its not working
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
You should create an array of objects and then post that array with all the data to the server.
Something like this:
$(document).ready(function() {
$("button").click(function() {
var data = []; // create an array
//create your loop
for (i = 0; i <= 5; i++) {
var obj = {}; // create an object
obj.name = "Insert name here"; // insert any property you need... you can even fetch the values from a dom object (like an input).
data.push(obj); // add the object to the array;
}
// create your ajax request. Send it as JSON by converting the array (using JSON.stringify) and specifying the content type (json)
$.post("demo_test_post.asp",
JSON.stringify(data),
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}, 'json');
});
});
I found way to do this and it's working:
<script>
var data=[];
for(i=0;i<=5;i++){data.push(i)}
$.post( "test.php", { 'data[]': data } );
</script>
And in test.php i will receive $_POST['data'] as an array than i can do like this :
<?php
for($i=0;$i<=count($_POST['data'])-1;$i++){
print_r($_POST[$i]);
}
?>

Passing JavaScript array from view to Laravel controller

I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.
<script>
var itemCount = 0;
var objs=[];
$(document).ready(function(){
var temp_objs=[];
$( "#add_button" ).click(function() {
var html = "";
var obj = {
"ROW_ID": itemCount,
"STREET_ADDRESS": $("#street_address").val(),
"CITY": $("#city").val(),
"ZIP": $("#zip").val()
}
// add object
objs.push(JSON.stringify(obj));
itemCount++;
// dynamically create rows in the table
html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button' id='" + itemCount + "' value='remove'></td> </tr>";
//add to the table
$("#multiple_table").append(html)
// The remove button click
$("#" + itemCount).click(function () {
var buttonId = $(this).attr("id");
//write the logic for removing from the array
$("#tr" + buttonId).remove();
});
});
$("#submit").click(function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address',
type: 'POST',
dataType:'json',
contentType: 'application/json',
data: objs
});
});
});
</script>
In my controller function is like this
public function search_address(){
$data = json_decode($_POST['data'], true);
print_r($data);
}
I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.
Thank you
Can you change:
$data = json_decode($_POST['data'], true);
to:
$data = json_decode(Input::get('data'));
and make sure you have: use Input; above your class extends Controller
See if that works.
Edit: Also make sure your routes (in the Controllers folder) are correct.
You should console.log() your javascript by placing the following in you ajax post:
error : function(e){
console.log(e);
}
You can then see what errors you are getting in your browsers' developers tools panel.
You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:
$("#submit").on('click', function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
type: 'POST',
data: {'data': objs, '_token' : '<?=csrf_token()?>'},
success : function(data){
// Do what you want with your data on success
},
error : function(e){
console.log(e);
}
});
});
Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:
<input type="hidden" id="_token" value="{{ csrf_token() }}" />
in your HTML, then pull this value from inside your ajax request:
data: {'data': objs, '_token' : $('#_token').val()}
EDIT
I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:
Route::post('/searchAddress', 'YourController#search_address');
Then use:
url: /searchAddress
in your ajax request.

cannot display the data got via ajax call

Just want to display following information which I got from my controller via ajax call:
{"results":{"name":"Bob","city":"Ottawa","reg_date":"12-Feb-2004"}}
Here is my controller:
$data["results"] = $this->my_model->did_get_data($user_id);
echo json_encode($data);
Here is My view:
<div id="display"></div>
Here is my JS file:
$.get('controller/get_data', function (data) {
$( "#display").text(data.results); //???
}, "json");
If you need to display all the attributes inside data then you can do it like this:
$.get('controller/get_data', function (data) {
var name = data.results.name;
var city = data.results.city;
var reg_date = data.results.reg_date;
$("#display").text("name :" + name + ", city:" + city + ", reg date:" + reg_date);
}, "json");
If you want to display those attributes, you need to specify them individually:
var string = "Name: "+data.results.name+", City:"+data.results.city;
$( "#display").text(string);
Or something along those lines.
Your scenario is not well explained. What is the error u get? And have u checked if $("#display") exists?
However there is one thing you could do:
$.get('controller/get_data', function (data) {
$( "#display").text(JSON.stringify(data.results)); //???
}, "json");
The above is if you want to print for checking purpose however if your #display should have only the values of your data i.e. name and such then you need to use the above answer i.e.
var name = data.results.name;
$("#display").html(name);

HTML form with no input selector on code [duplicate]

This question already has answers here:
Creating 'form' in javascript without html form
(4 answers)
Closed 9 years ago.
Is it possible to create an HTML form with no input selectors in page and create these "input" objects via javascript and then submit it? How can I create these "items"?
Or do I have to always create any "item" to submit previously in the HTML code?
So, can I avoid to create annoying hidden inputs in order to send javascript variables? I am not really able to find any tutorial or examples about it...
Thank you very much for your help.
like this, using jquery
$('<form>', {
"id": "getInvoiceImage",
"html": '<input type="text" id="componentInvoicId" name="componentInvoicId" value="' + componentInvoiceId + '" />',
"action": window.siteRoot + 'ComponentInvoice/GetInvoiceImage/'
}).appendTo(document.body).submit();
the MUCH better way:
$.post(url, { value1: "foo", value2: "bar" } );
and if you insist on doing it with a form, here's the generalized function so you can just pass it the json data
var postRequest = function (uri, data) {
data = data || {};
var form = $('<form method="post" class="js:hidden">').attr('action', uri);
$.each(data, function(name, value) {
var input = $('<input type="hidden">')
.attr('name', name)
.attr('value', value);
form.append(input);
});
$('body').append(form);
form.submit();
};
Yes, this can be done, even completely without using a <form>.
Check out jQuery as a starter (http://api.jquery.com). For example, if you want to know the clients device width, you could add this code:
$(document).ready(function() {
$.ajax( {
url: http://yourdomain.com/yourscript.php,
dataType: 'json',
type: 'POST',
data: {
w: $(window).width,
h: $(window).height
}
});
});
This would submit the parameters w and h to your application, containing window width and height. Just as an example.

Categories