ajax problem with sencha touch - ajax

I am trying to submit a form using ajax in the sencha touch framework. It's a simple form that asks for a user's name, email address, and a brief message. I then want to post the data to a php script that simply emails the data to me.
The problem I have is when I try to submit the form I get the following error:
"SyntaxError: Unable to parse JSON string"
The code to send the request is as follows:
var userName = name.getValue();
var userEmail = email.getValue();
var userMessage = message.getValue();
Ext.Ajax.request({
url:'path/to/phpfile.php',
jsonData:{"name":userName, "email":userEmail, "message":userMessage},
method:"POST",
success:function(){
alert("Success!");
},
failure:function(){
alert("Error");
}
});
The error occurs in the sencha touch framework on line 14583, which is
Ext.util.JSON = {
encode: function(o){
return JSON.stringify(0);
},
decode: function(s){
return JSON.parse(s); //this is line 14583
}
};
I'm just starting to learn Ext and sencha touch so could someone please point in the right direction here? Any threads/tutorials/examples would be greatly appreciated.
Thanks in advance

Maybe your Server uses Content Negotioation. In this case it respects the Request-Header-Parameter Accept, which is Accept: */* in your case. So the Server sends your Script HTML or XML which can't be read as JSON.
Change your Code to the following:
Ext.Ajax.setDefaultHeaders({
'Accept': 'application/json'
});
Ext.Ajax.request({
url:'path/to/phpfile.php',
params:{"name":userName, "email":userEmail, "message":userMessage},
method:"POST",
success:function(){
alert("Success!");
},
failure:function(){
alert("Error");
}
});
Source: http://www.sencha.com/learn/legacy/Manual:RESTful_Web_Services

What happens if you change the Ajax Request to the following.
Ext.Ajax.request({
url: 'php/file.php',
method: 'post',
params: { id: idvar, data1: Ext.encode(schouw), data2: Ext.encode(opmerkingen) },
success: function(response) {
//Reponse
}
});
In my own application this, direct, encoding of the data to JSON works great.
Are you sure the var's you are sending are filled with data? Within my application I use the below code to substract data from the input values (slightly different);
formID.getValues().inputFieldID

Related

Laravel open url in server side after action

is there any way to open url in "server side".
I'm using https://www.lightsms.com/ as my sms gateway. And to send sms, you need to visit (for example) https://www.lightsms.com/send.php, so i don't want to redirect user to that url. I just want to open it in server background, and close.
after route and before real redirect, example's here:
Route::get('/sms', function() {
//i need to excecute that url here
redirect('success.html');
});
Is there any way to do this?
I think you need to do this asynchronously using xhr or ajax if you use jquery, you basically post the information asynchronously and your server (your php script) just returns a json back, in your success function / promise you can get the data and do something with it if you like, this process does not require any redirect.
This is a simple example which you may need to modify:
function asyncPost(event){
$.ajax({
url: "https://www.lightsms.com/send.php",
data: {
name: "any value or variable,"
id: "any value or variable"
},
datatype: "json",
type: "POST",
success: function(data) {
console.log("success");
// do something with data if you need, data contains the returned data from your php script
},
error: function(data) {
console.log("an error occured");
}
});
}

AJAX JSON with ServiceStack

I have spend over 10 hours trying to figure this out and looking at similar examples from other people but unfortunately I haven't been able to find out what's my problem here.
I have a ServiceStack Webservice setup:
http://example.com/v1/getuser?code=abcd&lastname=doe&format=json
If I run the above via the browser I will get the following:
[{"nameresult":"joe"}]
I am trying to get this via making an ajax call as follow:
var code = $("#code_field").val();
var lastname = $("#lastname_field").val();
$.ajax({
url: "http://example.com/v1/getuser",
type: "POST",
data: JSON.stringify({
code: code,
lastname: lastname,
format: 'json'
}),
contentType: "application/json; charset=utf-8",
success: function (data) {
var returned_data = data;
alert('returned_data=' + returned_data);
},
error: function (xhRequest, ErrorText, thrownError) {
console.log('xhRequest: ' + xhRequest + "\n");
console.log('ErrorText: ' + ErrorText + "\n");
console.log('thrownError: ' + thrownError + "\n");
}
});
When I run the above, I get the following:
returned_data=[object Object]
Does anyone knows how could I get the json result, nameresult=joe? I am assuming that [object Object] contains [{"nameresult":"joe"}] but I am not entirely sure because I cannot see inside the object :(. thanks so much.
LATEST UPDATE - PROBLEM SOLVED!
I figured out the problem I was having. It had to do with ServiceStack and not with the Ajax call. My problems was the following, I hope it helps someone else one day that may face the same issue.
1.- I needed to enable CORS support on ServiceStack in order to allow posting parameters from Ajax:
File: AppHost.cs
//Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders = {
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
{ "Access-Control-Allow-Headers", "Content-Type" },
},
});
Plugins.Add(new CorsFeature());
this.RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpReq.HttpMethod == "OPTIONS")
httpRes.EndServiceStackRequest(); //httpExtensions method
// =>after v.3.9.60, => httpRes.EndRequestWithNoContent();
});
2.- My getuser method was in the GET instead of POST. I moved that to the POST and problem solved.
Moved getuser from here: public object Get(...) into here public object Post(...)
Thanks to all for helping me figure this out.
Use console.log to output returned_data by itself:
console.log(returned_data);
This will display the JSON object:
{"nameresult":"joe"}
Your original alert concatenates the string "returned_data=" with the JSON object, and thus the object is converted to a placeholder string "[object Object]" by the browser.
I often put my label in one log, and the object in another:
console.log('returned_data:');
console.log(returned_data);

DJANGO Jquery/ajax get 'httpresponse' JSON

I have been picking away at this, though thought I would reach out for some advice, if I may, I am fairly new to AJAX.
Right, I am using the django framework, I post the data to the server, which works great, then receive some data back on the callback function, which works, though I want this to be in JSON format so I can populate a table. Currently it either renders in plain text or the browser asks me to download the json data, meaning somethings not quite catching on the $.get part. My code is:
#views.py
if request.POST:
est_show = login_a.test()
return HttpResponse(est_show, content_type='application/json')
<!--JQUERY/AJAX-->
<script type="text/javascript">
$(document).on("submit","#these_choices",function (event) {
var data_form = $('#these_choices').serialize();
if(data_form) {
$.ajax({
type: "POST",
url: "{% url Create_this %}",
data: {'test':'test','csrfmiddlewaretoken': '{{ csrf_token }}'},
cache:false,
success: function(){
jQuery(document).ready(function ($) {
$.get('{% url Create_this %}', function(data) {
alert(data[0]);
});});
},
error: function(){
alert('error !!!!');
}
});}
else {
alert('error elsewhere');
}
event.defaultPrevented(); //not running PreventDefault returns json using defaultPrevented returns json and doesnt render anything when this is blanked out...
return false;
});
</script>
It also seems the alert(data[0]) is being ran before the json data is being received in the browser. Any advice will be appreciated?
Many thanks
Try setting the mimetype in the HttpResponse to application/json. When you don't specify a dataType in the ajax request, JQuery automatically tries to infer it based on the mimetype of the response.
return HttpResponse(est_show, mimetype='application/json')
Alternatively, you can set the dataType to json to tell JQuery to expect json.

Accessing details of ajax response JSON

I have a really stupid beginner jquery question, even if I saw a lot of similar question here:
From PHP with ajax I send this:
public function to_json() {
return json_encode(array( 'test_id' => 'test_value' ));
}
In the jquery file's success part I put:
function(data) {
alert(data);
}
And it shows this in the alert window:
{"test_id":"test_value"}
Which is fine, I guess, but if I change the function to this:
function(data) {
alert(data.test_id);
}
I got:
undefined
What am I missing?
What am I missing?
To set the Content-Type HTTP response header to application/json in your PHP script:
header('Content-Type: application/json');
Or to set the dataType parameter to json on the client:
$.ajax({
url: '/foo.php',
dataType: 'json',
success: function(data) {
alert(data.test_id);
}
});
The first is preferred because this way your server side script properly indicates to the client the content type it is using. And jQuery is intelligent enough to use this reponse header and automatically parse the response from the server before feeding it to the success callback.
You are missing to use the function parseJSON
reference:http://api.jquery.com/jQuery.parseJSON/
That function converts the json string into a javascript object
You need to parse it like this:
function(data) {
var obj = $.parseJSON(data);
alert(obj.test_id);
}
None of the answers posted so far worked for me.
This is what I had to do to get it working:
$.ajax({
url: '/foo.php',
success: function(data) {
var json = data.responseJSON;
alert(json.test_id);
}
});

How to call Twitter v1.1 API in javascript using AJAX

Aim - to get the twitter followers of a particular user using javascript
I have tried the below code as a POC-
$(document).ready(function() {
// Handler for .ready() called.
$.ajax({
url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
type: "GET",
data: { cursor: "-1",
screen_name: "twitterapi" },
cache: false,
dataType: 'json',
success: function(data) { alert('hello!'); console.log(data);},
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
if(xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
//var nonce = freshNonce();
//var timestamp = freshTimestamp();
//var signature = sign(nonce,timestamp);
//alert(signature);
//alert(accessToken+"-"+consumerKey);
//alert(oauth_version+"-"+oauth_signature_method);
xhr.setRequestHeader('Authorization','OAuth');
xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
xhr.setRequestHeader('oauth_timestamp', '1359955650');
xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
xhr.setRequestHeader('oauth_version', '1.0');
}
});
I calculated the signature values from the Twitter OAuth tool ..
This gives me 400 Bad Request error ....
Please let me know what the problem is...
The problem is your request's header, it should be like this:
xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');
Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a
It support both client side and node.js
Cheers
The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request
They should not be presented as separate header fields.

Resources