Jquery ajax call not working with relative and absolute urls - ajax

This is the code, I don't get any alerts whether, error or success. That ajax call returns a json map, and that map is populated in the select options dynamically.
<body>
<script>
$(document).ready(function() {
var selectValues;
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/",
data: APP_002,
async: false,
success: function(data) {
selectValues = data;
alert("Details saved successfully!!!");
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
});
</script>
<div>
<select class="mobile-vendor">
<option value="motorola">Motorola</option>
<option value="nokia">Nokia</option>
<option value="android">Android</option>
</select>
</div>
<div>
<select class="model"></select>
<a id="download-link"> Download </a>
</div>
</body>
Why it can't it send the request to the server, I'm using logs in the server side. No request there.
The page url : http://59.163.254.24:4287/wap/download/
Ajex request Url : http://59.163.254.24:4287/wap/retrieve/hanset/data/
I used both /wap/retrieve/hanset/data/ and http://myhost.com/wap/retrieve/hanset/data/ as the parameter for url in the ajax method, both are not working.

Code on your server (link you provided) is not the same as the one you have posted in your question. Code there has error: SCRIPT1009: Expected '}' meaning that you are missing } from your javascript.
Line:
// bonus: how to access the download link
comments out the rest of javascript as you have not switched it to a new row. This commented js includes some code and closing braces. You should add newline after this comment.
This is why you have javascript error and your browser never calls server.
And your parameter should be 'APP_002', not just APP_002
When you fix this, you will probably be able to make request, but if not, we can check for any other errors when you do this.

I think the problem is you're passing APP_002 using the data parameter, which is equivalent in this case to the querystring. Looking your comments on the OP, you need to actually pass it in directly in the URL so that the request is routed correctly on the server, like this:
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002",
async: false,
// rest of your code...
});
Example:
http://59.163.254.24:4287/wap/retrieve/hanset/data/?APP_002 -> page not found
http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002 -> JSON response

Actually, there is not a problem with the code you provided.
Here is jsfiddle:
http://jsfiddle.net/fHtcc/1/
However, there must be an issue with APP_002 (if it is not something defined) or Jquery is not included to page.

Related

How to make a ajax request using post method

I made an ajax request using post method in django..its wokring perfectly..the problem is its calling the complete html page rahter than a div..i want to call only a div..i tried but unable to find the exact solution..
<script>
$(document).ready(function(){
$('#Category').change(function(event){
event.preventDefault();
var e = document.getElementById("Category");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "/charts/",
type: "post",
dataType: "html",
data: value,
success: function(data) {
$('#div1').html(data);
}});
return false;
});
});
</script>
I want only div content with id #div1..i already tried find and replace method
What is the nature of the event ? Is it a button ? an Input ?
If it is an input as <input type="submit">, the default action is to reload the page like a form.
Did you check if your div id is really div1?
$("#div1").append("your html code"+data+" your html code")

MVC Core : Upload file through Ajax request and return JSON object without redirect

I have a requirement where I want to upload an excel file to the controller, read the file, process its data and send it back to the same view as the JSON object.
I want to achieve this using AJAX call as I want to capture its success callback and manipulate DOM as per received response. I have tried a few things but I am not able to hit the controller. Any help on this is appreciated.
Below shown is my JS, HTML and C# code :
function SubmitInfo() {
var formData = new FormData();
formData.append('file', $('#fileInput')[0].files[0]); // myFile is the input type="file" control
var _url = '#Url.Action("Upload", "CrossValidation")';
$.ajax({
url: _url,
type: 'POST',
data: formData,
processData: true, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (result) {
//manipulate DOM and bind response with Kendo grid
alert("result");
},
error: function (jqXHR) {
},
complete: function (jqXHR, status) {
}
});
}
<div class="col-md-4">
<input id="fileInput" type="file">
</div>
<div class="col-md-4">
<input type="submit" value="Upload file" onclick="SubmitInfo()"/>
</div>
public JsonResult Upload(IFormFile formData)
{
//Do something here....
return Json("");
}
There are two obvious problems in the code you've posted:
processData: true. By setting this to true (the default), you're asking jQuery to attempt to turn the data you're providing into a query string, which is not what you want. Instead, you want to set this to false, which will ask jQuery to leave the data alone and pass it on to the underlying XMLHttpRequest as is, where the data will be formatted correctly as multipart/form-data.
The name argument passed to formData.append must match the name of your IFormFile parameter in the ASP.NET Core MVC Controller. You're using file in the the former and formData in the latter, so you'll need to change one of them so that they're the same.

Django template not re-rendering on successful AJAX get request

I have written a very simple ajax code which makes a get request, and it expects django template values as response. So when I try to execute this ajax code, in chrome under network, I can see that the get request was successful and in the preview section under network, I can see the template values that I had expected but the webpage remains same, doesn't get rendered again.
My view:
def test(request,id=1):
return render(request,'test.html',{'num':id,'next':9})
My template and ajax code:
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<p>{{num}}</p>
<button onclick='test({{next}})'>Test</button>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(){
console.log('done');
}
});
}
</script>
Please check this sample image of my problem when I started on '/test/66' , made a click on the button, got the required response, still no change.
You're mixing server side rendering (DTL) and client side (javascript). Once django as rendered the template, you're javascript has no access to server side variable as {{ text }}.
You will have to do :
Template before SSR
<div id="content">
<p>{{num}}</p>
<button onclick='test({{next}})'>Test</button>
</div>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(data){
document.querySelector('#content p').innerHTML(data);
}
});
}
</script>
Template after SSR (something like this, you get the point)
<div id="content">
<p>66</p>
<button onclick='test(66)'>Test</button>
</div>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(data){
document.querySelector('#content p').innerHTML(data)
}
});
}
</script>

Passing value using Ajax to my PHP

My ajax code didn't work, i am trying to pass the colorit value from my script to my controller(php), but the ajax didnt work. the alert box with out put 'success!' didn't pop out and also the alert(colorit). but if i comment the ajax code, the alert(colorit) pops. is there any wrong in my ajax code? please help. tnx. sorry im new to this.
script
$( ".colorselector_1" ).change(function() {
var colorit = document.getElementById("colorselector_1").value;
alert(colorit);
$.ajax({
url: '/addItemColor',
type: 'GET',
data: {'colorit':colorit},
success:function(data){
alert('success!');
}
});
});
html
<select id="colorselector_1" class="colorselector_1">
<option value="#A0522D" data-color="#A0522D">sienna</option>
<option value="#CD5C5C" data-color="#CD5C5C" selected="selected">indianred</option>
</select>
route
Route::get('addItemColor','CakeController#addItemColor');
controller
public function addItemColor(){
.......}
May I just suggest something?
First of all, this is why you have vars like "error" in place. So the first thing you should do is change your code accordingly:
$( ".colorselector_1" ).change(function() {
var colorit = document.getElementById("colorselector_1").value;
alert(colorit);
$.ajax({
url: '/addItemColor',
type: 'GET',
data: 'colorit':colorit,
success:function(data){
alert('success!')},
error:function(data){
console.log(data);
alert('error');
}
});
});
Another thing to remember is that you have the Network panel in developer tools where you can see all of the calls that were made and whether they had successful responses or not, such as in Chrome when you go to More tools -> Developer tools. These two will help you find the answer of "whether there is something" for yourself, like if there's a wrong URL or something.
Make sure you point to the right url in your $.ajax function.

how do basic jquery ajax in typo3 flow?

I am trying to do some very basic ajax. I just want an onchange event on a select that will call an ajax function that will get the options for another select and fill it in. However I am not sure how to do this in a simple way in Typo3 Flow. My php code for the action just looks like this:
public function getProductsByCategoryAction( $category='' ) {
$postArguments = $this->request->getArguments();
echo __LINE__;
TYPO3\Flow\var_dump($postArguments); die;
}
and my ajax call looks like this:
jQuery('#get_category').change(function(event) {
event.preventDefault();
alert('get products');
var category = jQuery('#get_category').val();
alert(category);
jQuery.ajax({
url: "/admin/orders/getproductsbycategory.html",
data: {
'category': category
},
async: true,
dataType: 'html',
success: function(data) {
alert('hi mom');
...
}
});
});
when I try this url in the browser mysite-dot-com/admin/orders/getproductsbycategory.html?category=17ca6f3e-a9af-da7d-75cd-20f8d6a05ed0
on the page the var_dump just gives me array(empty). Why doesn't the request->getArguments() call work and give the category argument?
The getproductsbycategory.html is created in Neos and has the right plugin for the action call. So I know the right action gets run but it does not get any args. At this point the argument is just a string and not an _identity even though I should eventually do it that way, I'm trying to keep things simple for now for the sake of expediency.
Thanks
Update: as a temp workaround shameless hack I just did this to get the variable:
$categoryID = $_GET['category'];
which works but I'd like to know the proper way especially if it does not involve writing my own view helpers.
First define variable in your html file
<script>
var ajaxUrl = '<f:uri.action action="actionName" controller="(controllername)Ajax"/>';
</script>
Your Ajax code will look like :->
$.ajax({
data: '&lookup='+{somevalue},
type: 'POST',
url: ajaxUrl,
success: function(data) {
$('.lookup-id').append(data);
},
});
Your conroller action will look like :->
public function getLookupIdAction(){
// Get company detail for set logo of company
$companyDetail = $this->getUserCompany();
// Template Name
$templateName = 'GetLookupID.html';
$viewVariables = $this->lookupIdentifierRepository->findByCompany($companyDetail);
$templatepath = 'resource://WIND.Alertregistration/Private/Templates/LookupIdentifier/' . $templateName;
$this->standaloneView->setLayoutRootPath('resource://WIND.Alertregistration/Private/Layouts');
$this->standaloneView->setPartialRootPath('resource://WIND.Alertregistration/Private/Partials');
$this->standaloneView->setFormat('html');
$this->standaloneView->setTemplatePathAndFilename($templatepath);
$this->standaloneView->assignMultiple(array("lookUpValue" => $viewVariables));
$this->standaloneView->setControllerContext($this->getControllerContext());
return $this->standaloneView->render();
}
Your view file look like :->
<f:layout name="Lookup" />
<f:section name="Content">
<label for="lookupId" style="box-sizing: border-box;">Identifier</label>
<div class="select-box" style="box-sizing: border-box;">
// Your Code
</div>
</f:section>

Resources