Ajax Request Return HTML Page - ajax

I am trying to send data from an Input to the controller of my application in Laravel, where I supply the category ID and it returns a jSON with the related id's.
I have a input to get data
<label for="categoryMae">Nome da Categoria Mãe</label>
<input class="form-control" id="getCategoryMae" name="getCategoryMae" />
A script to pass to my controller
<script>
$("#getCategoryMae").blur(function(){
var cat_id = $(this).val();
console.log(cat_id);
$.ajax({
type: 'GET',
url: '{{route('getCategoryName')}}',
data: 'cat_id',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log(data.cat_id);
}
});
});
</script>
and I trying to get this values in my Controller (Route::get('/categories/getCategoryName', 'CategoriesController#getCategoryName')->name('getCategoryName');)
public function getCategoryName(Request $request)
{
$data = $request->all();
dd($data);
}
But the code returns the HTML structure and not the the value
How return only the value and not all that structure and why that happened? Thanks in advance!

I don't think you're sending any data to your controller. Try this, check the data property of the AJAX call.
<script>
$("#getCategoryMae").blur(function(){
var cat_id = $(this).val();
console.log(cat_id);
var dataObject = {cat_id: cat_id};
$.ajax({
type: 'GET',
url: '{{route('getCategoryName')}}',
data: dataObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log(data.cat_id);
}
});
});
</script>
Also, I can tell you use Google Chrome, you can make sure you send something to the server, you can click on the Headers, go to the bottom to the Query String Prameters to see the parameters you're sending.
Here's a good resource: Chrome Dev Tools

Related

Ajax link does not send POST request

I have the following ajax link:
#Html.AjaxActionLink(item.Name, "https://test.testspace.space/storage/Data/stream?tokenValue=e58367c8-ec11-4c19-995a-f37ad236e0d2&fileId=2693&position=0", new AjaxOptions { HttpMethod = "POST" })
However, although it is set to POST, it seems that it still sends GET request.
UPDATE:
As suggested below, I also tried with js functuion like this:
function DownloadAsset() {
alert("downloading");
$.ajax({
type: "POST",
url: 'https://test.testspace.space/storage/Data/stream?tokenValue=add899c5-7851-4416-9b06-4587528a72db&fileId=2693&position=0',
success: function () {
}
});
}
However, it still seems to be GET request. Parameters must be passed as query and not in the body of the request because they are expected like that by the target action. I don't know why (it would be more natural to have GET request) but back-end developer designed it like this due to some security reason.
If I use razor form like this, then it works:
<html>
<form action="https://test.testspace.space/storage/Data/stream?tokenValue=2ec3d6d8-bb77-4c16-bb81-eab324e0d29a&fileId=2693&position=0" method="POST">
<div>
<button>Send my greetings</button>
</div>
</form>
</html>
However, I can not use this because I already have bigger outer form on the page and I'll end up with nested forms which is not allowed by razor/asp.
The only way is to use javascript but for some reason it does not make POST request.
#Html.AjaxActionLink will generate to <a> tag,and tag will only have HttpGet request method.If you want to send HttpPost with <a> tag,you can use it call a function with ajax,here is a demo:
link
<script>
function myFunction() {
$.ajax({
type: "POST",
url: "https://test.testspace.space/storage/Data/stream",
data: { tokenValue: "e58367c8-ec11-4c19-995a-f37ad236e0d2", fileId: "2693", position:0 },
success: function (data) {
}
});
</script>
Since you want to make a POST request, but the values need to be as query string params in the URL, you need to use jquery.Param.
see https://api.jquery.com/jquery.param/.
You should set the params, like below :
$.ajax({
url: 'your url',
type: 'POST',
data: jQuery.param({ tokenValue: "your token", fileId : "2693", position: 0}) ,
...
Try this instead,
First remove the action url from the from
Second put the result in the success function to return response
and for parameters, I always use FormData() interface to post with Ajax
And last don't forget to include dataType, contentType, processData to not get an unexpected behavior
your code will look like this
var form_data = new FormData();
form_data.append('tokenValue' ,'add899c5-7851-4416-9b06-4587528a72db&fileId=2693');
form_data.append('position' ,'position');
$.ajax({
type: "POST",
dataType: 'json',
contentType:false,
processData:false,
data: form_data,
url: 'https://test.testspace.space/storage/Data/stream',
success: function (result) {
}
});

Ajax Post not sending data Correctly

VB.net, MVC4, asp.net views.
I would like to know why I cannot send or what I am doing wrong sending a parameter(int), parameter(model).
data:
var ID = '<%: Model.ID%>';
var data = $('#dlg').find('form').serialize();
Ajax Post:
$.ajax({
url: '<%: Url.Action("EST", "Now")%>',
type: 'POST',
data: { id: ID, model: data },
success: function (rData) {
$('#divE').html(rData);
}
});
Now - Controller:
<HttpPost> _
Function EST(id As Integer, model As EViewModel) As ActionResult
So I'm passing a modelID and the forms data, sending them separately( with modifications ) both work, but sending them together it seems to null the 2nd parameter. Found by debugging the action.
try use JSON.stringify.
Include contentType: "application/json; charset=utf-8", when you omit the contentType value default is 'application/x-www-form-urlencoded; charset=UTF-8' this could become a trouble when you will post data
$.ajax({
url: '<%: Url.Action("EST", "Now")%>',
type: 'POST',
data: JSON.stringify({ id: ID, model: data }) ,
contentType: "application/json; charset=utf-8",
success: function (rData) {
$('#divE').html(rData);
}
});

Linking AJAX with PHP code. Do i need to write it again?

I have a real problem. I have a php code and a form where when the form is submitted a POST request is sent and the page reloads again and ofcourse the post is viwed in the page.But i want to work with AJAX in order page not to be refreshed.I know the basics of AJAX but i don't want to build all the project from the beggining.Is there a way in success function of AJAX to link to my php code??
$.ajax({
type: "POST",
url: "index.php",
datatype: "html",
data: dataString,
success: function(data) {
//How can i link here to start running my php code which is located in the same page.
}
});
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
// try this
console.log(data);
// see what 'data' actually is
}
});
then check in the browser by hitting F12 to look at the console.
also are you sure you want datatype of html ? you probably want a data type of json or XML , what is the server returning to you after the ajax post?
You have to cancel the form's submission so that the ajax request will take place, otherwise it is canceled. Also use .serialize to get a name-value pair string of the form data to use in the ajax call.
Html
<form id="MyForm">
<button id="MyButtonId">Submit</button>
</form>
JS
$("#MyForm").submit(function(e){
//Prevents the form from being submitted
e.preventDefault();
$.ajax({
type: "POST",
data: $("#MyForm").serialize(),
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
});

Send FormData and String Data Together Through JQuery AJAX

I have the below that uploads an image using JQuery's AJAX function
var id = <?php echo $id; ?>;
var img_data = new FormData($("form")[0]);
$.ajax({
url: 'add.php',
data: img_data,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
I'd like to include a string with the FormData sent. I tried the following, but no luck
data: img_data {id: id},
What's the correct syntax here?
Use append
var img_data = new FormData($("form")[0]);
img_data.append('id', id);
You could create a JSON data object and pass that as application/json and process the data within add.php:
var data = {
id : <?php echo !empty($id) ? $id : "''",
img_data : new FormData($("form")[0])
};
$.ajax({
url: 'add.php',
data: data,
contentType: "application/json",
type: 'POST',
success: function(data){
alert(data);
}
});
Although unconventional, you could also append the data as a query string to the URL with the POST. You'd also need to edit add.php to get this parameter.
$.ajax({
url: 'add.php?id=' + id,
data: img_data,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});

Ajax Success Function not working

I am using Ajax to add contents on my database. And here's the code:
function addToFavorites(){
var recipe_id = $("#recipe_id").val();
var url = connect_url+'addFavorite.php?user_id='+user_id+'&recipe_id='+recipe_id;
$.ajax({
type: 'POST',
data: [{
user_id: user_id,
recipe_id: recipe_id
}],
url: url,
async: true,
jsonpCallback: 'userCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
alert("HELLO!!!");
},
error: function (e) {
alert("ERROR!");
}
});
}
The Ajax call was successful and I was able to add records on the database but I'm just wondering why is it not displaying the alert message if the calling was successful? Is there something wrong with my code? Or is there something wrong with my understanding? Thanks!
you must give a response with some info to the ajax or it won't know the response succeeded

Resources