jQuery to read json data - javascript

I am trying to get jquery to read json data but getting undefined.
$.post( wce_data.url, { userid : userId, token : accessToken }, 'json')
.done(function( data ) {
console.log("data.status: " + data.status);
if (data.status === "success") {
alert("Coupon added");
} else {
alert("failed");
}
})
.fail(function() {
alert("The requested action failed. Please contact the site administrator!");
});
data.status: returns 'undefined'
data: returns {"status":"success"}

Try error checking like this:
.done(function() {
alert( "Coupon added" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );

Oh I see. I got it. It was the PHP Output Header that was needed.
I added:
header("Content-type: application/json");
To the PHP for jQuery.
Hope this helped someone new to json like me.

Related

Trying to automate scanning for flash embed links on other domains

I tried this code to pull website but when I test it, the alert box doesn't run.
<script type="text/javascript" >
$(document).ready(function(){
$.get( "https://crossorigin.me/https://google.com", function( data ) {
alert( "Data Loaded: " + data );
});
});
</script>
Taken from the documentation, try implementing the .fail method to see what went wrong.
var jqxhr = $.get( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
Also the author of crossorigin.com warns that
PLEASE DO NOT USE THE PROXY ON A PRODUCTION SITE.
I cannot guarantee the stability of the service, and you will probably experience service interruptions.

getJSON - working on response and displaying error message

I have a JSOn method as below:
$("#pwdOverride").change(function(){
alert("Inside onchange");
var pwdOverride = $("#pwdOverride").val();
alert("value of pwdOverride... "+pwdOverride);
$.getJSON(
'${pageContext.request.contextPath}/transaction/authenticationChk.do',
{paramFilter:'PROFILE',pwdOverride:pwdOverride},
function(data){
alert(JSON.stringify(data)); -> return would be "pwd" or "aPwd" or "err"
}
)
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
});
JSOn response would be a String either "pwd" or "aPwd" else "err".
Based on the result I would want to display an inline error message similar to the validaiton rules.
like
messages: {
pwdOverride :"Incorrect pwd.",
cpwdOverride: "Incorrect sec pwd."
}
Is it possible? if so how do i achieve?

Javascript : invalid character error

In my .cshtml page I have JavaScript function it is working fine but showing error like Invalid Character. Here is my code snap :
Please help me. Not getting where is the error.
Please use like this:
.
Please click here for details documentation on Jquery.com
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});

Wordpress update_user_meta onclick with Ajax

I'm attempting to update_user_meta via Ajax call in Wordpress.
I keep getting a 'success!' console log, but no data is returned and the user meta field is not being updated.
general.js on a button click:
var newViewPreference = jQuery(this).attr('id');
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: {
'action':'update_view_pref',
'viewPref' : newViewPreference
},
success:function(data) {
console.log(data);
console.log("success!");
},
error: function(errorThrown){
console.log(errorThrown);
console.log("fail");
}
});
functions.php
add_action( 'wp_ajax_update_view_pref', 'update_view_pref');
function update_view_pref() {
if(empty($_POST) || !isset($_POST)) {
ajaxStatus('error', 'Nothing to update.');
} else {
try {
$user = wp_get_current_user();
$viewPref = $_POST['viewPref'];
if ($viewPref == 'toggle-grid') {
update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'grid' );
} elseif ($viewPref == 'toggle-list') {
update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'list' );
}
die();
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}
Anyone able to pinpoint where I'm going wrong? Thanks.
Changing $_POST to $_REQUEST worked.
Can anyone explain why $_POST didn't work but $_REQUEST did?
I was submitting the data to the ajax request via a button click (not a form).

ajax catch correct error code

i have this little code to post to my server
$.ajax({
type: 'POST',
url: 'post.php',
data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: '' },
success: function(data){
alert (data)
}
});
Wondering how i can "catch" the different errors for ajax request:
for eg, post.php return 'token error' when invalid token has been posted, or 'invalid title' for missing title.
Thanks in advance
If the server sends something else than 200 status code you could use the error handler:
$.ajax({
type: 'POST',
url: 'post.php',
data: {
token: '123456',
title: 'some title',
url: 'http://somedomain.com',
data: ''
},
success: function(data){
alert(data);
},
error: function() {
alert('some error occurred');
}
});
If your server performs some validation on the request arguments maybe it could return a JSON object containing the error information (and set the proper Content-Type: application/json):
{ error: 'some error message' }
In this case you could handle this in the success callback:
success: function(data) {
if (data.error != null && data.error != '') {
// TODO: the server returned an error message
alert(data.error);
} else {
// TODO: handle the success case as normally
}
}
// build the initial response object with no error specified
$response = array(
'error' => null
);
// the data checks went fine, process as normal
if (data is ok) {
$response['some_object'] = value;
// something is bad with the token
} else if (bad token) {
$response['error'] = 'token error';
// something is bad with the title
} else if (bad title) {
$response['error'] = 'bad title';
// some other error occured
} else {
$response['error'] = 'unspecified error';
}
// output, specifying that it's JSON data being returned
header('Content-Type: application/json');
echo json_encode($response);
and....
// $.ajax({ ...
success: function(data){
if (!data.error){
alert('OK!');
}else{
alert('Error: '+data.error);
}
}
// });
Something like that perhaps? (Unless you're talking legitimate AJAX errors, in which case supply the error: function(x,t,e){} ajax option or use .ajaxError)
What I like to do is set the dataType for the $.ajax() to 'json' and then in the PHP page you can just echo a json_encode()ed associative array. This will let you reference the values via your function parameter data (i.e. data.success, data.message). Let me know if you need some examples.
You probably want to set the 'error' handler function, which would treat the error you received.
Take a look at http://api.jquery.com/jQuery.ajax/ in the error setting.

Categories

Resources