Treat callback response in $.ajax() as JSON - javascript

I have:
<script>
$('#email').on('blur', function(){
email = $(tihs).val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {
'email': email,
'job': 'check',
},
dataType: "JSON",
success: function (response) {
// the response from PHP is smth like:
// {"status":"failed","reason":"email_not_validated"}
// now I want to:
if(response.status == 'success'){
}else{
}
}
})
});
</script>
This seems to work on every browser except IE, why is that?
Am I doing the right thing? the only thing which I need is to access the returned data like response.status and response.reason .
Thanks for helping

This is a mentioned IE10 bug that can be fixed by adding
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
in the <head>. Note in a <head> there should not be another meta tags with X-UA-Compatible as the previous one will be overridden.

Related

Undefined index Jquery Ajax POST

I have this small but annoying problem. I really not usual with a web thing. I try to request to my php file using ajax jquery. When I want to retrieve the data I send from ajax, it return undefined index. I dunno what's the problem, it make me spend a lot of time to solve it. Thanks
Below is my ajax code
var at=this.name.substring(this.name.length,7);
var value_header = $("#key"+at).val();
var jsObj = { new_value:value_header, id:at, data:'header'};
console.log(JSON.stringify(jsObj));
$.ajax({
type: 'POST',
headers: 'application/urlformencoded',
url: 'admin_crud.php',
data: jsObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log("Sukses");
}
When I call the below code in my php file, the result is 'Undefined index: data'
echo $_POST['data'];
//Edit
So, when I try var_dump($_POST);, the result is array(0) {}. Where is my mistake? I thought I had send the right one
//Edit
As I mention above, I want it to run perfect without error. Thanks
Remove headers, change your datatype to text and catch errors in the ajax call
$.ajax({
type: "POST",
dataType: "text",
data: jsObj,
url: "admin_crud.php",
success: function (result) {
console.log("success", result);
},
error: function (e) {
console.log("Unsuccessful:", e);
}
});
I have another solution beside #Marco Sanchez too, I don't know it always work or not, but in my case, it work :
$.ajax({
type: 'POST',
url: 'admin_crud.php',
headers: "Content-type: application/x-www-form-urlencoded"
data: "new_value="+value_header+"&id="+at+"&data=header",
success: function(data){
console.log("Sukses");
console.log(data);
}
});

Laravel error 405(Method Not Allowed) Ajax Posting

Hello i wnat to send my data with ajax to my controller.
My CODE
AJAX
$.ajax( {
type:'POST',
header:{
'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
},
url:"{{route('race.post')}}",
data:{
_token: "{{ csrf_token() }}",
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
CONTROLLER
public function Points(Request $request){
$test = $request->input('data');
return "$test";
}
ROUTE
Route::post('updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);
And there are the errors what i get.
Console
Network-preview
Network-Response
I just removed the slash at the end of url and it began working...
/managers/games/id/push/ to:
$http({
method: 'POST',
url: "/managers/games/id/push",
add this one in your layout.blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
then use this one in your js code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
i hope this will help!!
First thing is we put two routes in one for displaying view and another for post ajax. So simple add both routes in your route file.
routes/web.php
Route::get('ajaxRequest', 'RacesController#Points');
Route::post('ajaxRequest', 'RacesController#Points');
Include this meta tag inside your view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Include javascript code inside your ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Since you are working in a JavaScript file and not in a Blade file, the route() helper method is not working, and the route 'race.post' isn't parsed to an url.
Try to change the url to this:
url: '/updateC'
When you want to use the route() helper in your JavaScript, you have to add the script to a Blade file, and json_encode the value, you can read more about this in this answer.
I have different way to use it:
AJAX
data = {
selectmanufacturer: selectmanufacturer,
categories: selectCategory,
_token: "{{csrf_token()}}",
productName: productName
};
$.ajax({
url: '{{URL::to('/all-products-data')}}',
type: 'POST',
dataType: 'json',
data: data,
success: function (response) {
},
error: function (response) {
alert(response);
}
});
Controller:
public function Points(Request $request){
$test = $request->all();
return "$test";
}
I hope It will be helpful to you
The URL you’re posting to doesn’t look right in the console output you posted. In your AJAX code, you have this:
url:"{{route('race.post')}}"
But that’s just getting interpreted as is, it’s not getting interpreted as the value of that route in Laravel.
You’ll need to make sure that your JavaScript code is in a Blade template if you want Blade tags parsed.
not type: "POST", method :'POST" try the below code i have modified. ref: Reference Link
HTML code
<button onClick="onBtnClick()" data-url="{{route('race.post')}}"></button>
Updated Code
function onBtnClick(){
var token = $('meta[name="csrf-token"]').attr('content');
var url = $(this).attr("data-url");
$.ajax( {
method:'POST',
header:{
'X-CSRF-TOKEN': token
},
url: url,
data:{
_token: token,
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
}
Check if your laravel route is correctly set for this request.
In my case, I had a $.ajax url: "crop-image-upload" and a Route::post('crop-image-upload ', 'CropImageController#uploadCropImage');
But the request was sent to http://127.0.0.1:8000/news/crop-image-upload
So I had to change my route to Route::post('/news/crop-image-upload ', 'CropImageController#uploadCropImage');
So, in your case, try to add a literal url on ajax like this:
url:"/races/updateC"
and add 'races/' in the route like this:
Route::post('/races/updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);

How to get a URL from a jQuery Ajax

I have this function, and every time I call it, I need the imagesUploadScript variable to be updated with a new URL. I've implemented in the server side a JSON response with the desired URL for each request, but I'm not able to get that JSON value with jQuery.
$(function () {
$('.editor').editorInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: /* The url*/
}
});
});
I have tried this, but doesn't seem to work :S
$.getJSON("/admin/upload_url",function(result){
return JSON.stringify(result)
})
EDIT
I have restructured my code, this way my function accepts a callbacks as #Mohamad suggested and thanks to this question:
function getURL(callback) {
var url;
$.ajax({
type: "GET",
async: false,
url: "/admin/upload_url",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
url = data['url'];
callback(url);
} //success
});
}
But I'm not able to return the url for imagesUploadScript but yes this way
getURL(function(url){
console.log(url);
});
I'm confused, how should I declare this function inside the other one so imagesUploadScript get's a new URL every time is called ?
Thanks in advance for any help ! :D

jquery ajax post not executed

I have a little problem with jQuery ajax.
I want to send a POST to a .php file and afterwards change the current URL. I tried the following code:
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
window.onload = function () {
$.ajax({
type: "POST",
url: "sample.php",
data: {'username': "STRING"},
timeout: 1000,
complete: function(){
window.location.href = 'http://127.0.0.1/sample/another.php';
}
});
}
</script>
So, as I can see in the chrome developer tools Network tab, no POST is executed. Although the URL changed to another.php
Can you tell me what I am doing wrong or how I can solve this issue?
use success instead of complete
$.ajax({
type: "POST",
url: "sample.php",
data: {'username': "STRING"},
timeout: 1000,
success : function(){
window.location.href = 'http://127.0.0.1/sample/another.php';
}
});
You will never see the POST. cause the url changes and remember the another.php hasn't made any AJAX requests! so you'll never find anything there. try changing the JS code in the success method to something like an alert to know if it works! and maybe then you'll find the POST method in the console!
Alternatively, you can use .done() as well. You may also think about scoping this inside a self executing function instead of a window.onload event.
(function($){
// Make an object for your param values.
var ajaxData = {
username: 'STRING',
anotherParam: 'STRING',
andanotherParam: 'STRING',
yetanotherParam: 'STRING'
};
$.ajax({
type: "POST",
url: "sample.php",
data: ajaxData
}).done(function(){
window.location.href = 'http://127.0.0.1/sample/another.php';
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}(jQuery));

PhoneGap AJAX Login

I am trying to build a log in application in PhoneGap. Ive been looking around a lot for similar things and I found them plenty... but I do not understand why this pieces of code does not work. When i press the logIn_btn it shows that It cannot reach the "success" piece of code. Thank you for your help!
$('#logIn_btn').click(function(){
user = $('#username').val();
pass = $('#password').val();
var ev = {'papa':true};
if(user!='' && pass!=''){
alert('trying login');
$.ajax({
url: 'https://localhost/server/IF/mobileApp/login.php',
type: 'post',
datatype: 'json',
data: ev,
success: function(data){
alert('asd');
}
});
console.line('done.')
} else {
alert('Please insert your username and password.');
}
});
Your server should not be https://localhost, it should be the name/ip of the server that you'll be logging into.
For additional information, look at your network tab with Chrome, or install a fail handler
$.ajax({
url: 'https://localhost/server/IF/mobileApp/login.php',
type: 'post',
datatype: 'json',
data: ev,
success: function(data){
alert('asd');
}
}).fail(function(jqXHR, textStatus){
});
console.line?I think it would be console.log. Rather try alerting the message. Also make sure the javascript executes after deviceready. Also localhost in android is a very different thing. Try using the ipadress or domain name to access the server.

Categories

Resources