AJAX code:
var data = $('#myIDform').serializeObject();
$.post(
'my url',
{data: data},
function(response){
response
});
The serializeObject() function: (I took it from a similar post in here)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
I don't have any kind of parsing or stringify method or so, and whenever I add a new entry on my db with special characters (e.g. 'ñ') it shows perfectly in the response, but the database saves this: 'ñ'
I am not sure the problem is in the database, because the same thing without AJAX, works.
EDIT: When I manually refresh the page it shows as the database, since it's where the data is taken
I have been reading over here and JSON.parse and JSON.stringify dosen't seem to work for me, because I get something strange in the database: '{'I guess I am not doing it correctly or something is working not as intended.
In the .php i parsed it as: $result = $obj->insert ( JSON_parse($_POST['data']) );
And in the .js i strigified it as: var data = JSON.stringify($('#myIDform').serializeObject();
How it looks like in the database: http://prntscr.com/99t6po
EDIT: SOLVED. Database and PHP were in different charsets
Related
I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression
I use this serializeObject function for my forms.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};`
I can do this for the ajax call
$('form#changeprofileform').serializeObject();
This works fine for the textfields I have, but when I want to upload a file, the input type="file" is not in the object so I cannot send it to the server to upload.
I searched around on stackoverflow but I can't really find anything that will help.
Does anyone know why this is not working and what I can do about that ?
P.S. I know it is possible to upload files with an iframe, but I want to do it this way
Thanks!
edit
I can ofcourse do it without the serializeObjectfunction and send all the inputs with .val, but that will not work in IE9 :(
I am working on a project that uses a function I called AjaxRequest which handles all AJAX requests I make. I have no problems in making the request however getting the request back is the issue and placing it where I want it on my page is becoming stressful.
HTML BIT
<body onLoad="calling();">
<div id="status">Status: </div>
</body>
JAVASCRIPT BIT
function calling() {
var answer = ajaxRequest("testing", "test.php", "test=test");
document.getElementById("status").innerHTML += answer[1];
document.getElementById("status").innerHTML += " " + answer[3];
}
function ajaxRequest(app, location, credentials) {
var extras = "";
if(credentials === "" || credentials) {
extras = "&" + credentials;
}
var ajax = ajaxObj("POST", location);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var obj = JSON.parse(ajax.responseText);
var arrayObj = [];
for(var i in obj) { arrayObj.push([i, obj[i]]); }
return arrayObj;
}
}
ajax.send("app=" + app + extras);
}
there are two other functions running: ajaxObj and ajaxReturn but I excluded those because they is not the problem. Furthermore, I am trying to make ajaxRequest an efficient function that could be used by more than one application without having to rewrite all the code in more than one location. All error handling acquires before the actual use of ajaxRequest.
PHP BIT
<?php
if($_POST['app'] == "testing") {
$hey = array('success' => 1, 'message' => 'Successful');
echo json_encode($hey);
exit();
}
?>
I'm using calling as a javascript function that does all error handling, this is just basic for the whole of my project however I try to get the JSON from php and convert it to array and the issue is returning the array into calling. I try to display the information on the page yet nothing works.
I am not looking to use any JQuery for my project so I would like to exclude the use of it for this piece of code.
If you want, you could set the header before sending back the json.
header('Content-Type: application/json');
Usually you don't need it, but it will tell your javascript that it's json, and the array will be transform in a javascript object. It work with Jquery, but I assume it'll work without too
I am pretty new to jquery and can't seem to figure this issue out.
I need to figure out how to dynamically set the key:value pairs in this code below from a form that has dynamic values for form inputs. The code works if I add the key:value pairs manually, but I don't always know what the form names are going to be as they are created by the user.
Please see the notes in the middle section of code below. I am trying to use the values from .serialize() to pass as the $_POST value.
Here is the value I currently get from the var formValues:
ID=10&user_login=test9&wplp_referrer_id=&&block_unblock=u
However when I try to pull the values in my function using:
$user_id = $_POST['ID'];
The ID of '10' is not being set in $user_id, indicating that the syntax or method I am using to pass the serialized results is not correct below.
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var formValues = $("#wplp_edit_member").serialize(); //Get all the form input values
alert(formValues); //Check form values retrieved for testing only
var numbers = /^[0-9]+$/;
// Validate fields START
var wplp_referrer_id = $("#wplp_referrer_id").val();
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Post data to ajaxurl
$.post(ajaxurl, {
action: "wplp_edit_member", //Call the PHP function to update/save form values
data: formValues, //Use data to pass form field values as $_POST values to the function above
// No More manual inputs of form fields to be passed
//ID:$("#ID").val(),
//user_login:$("#user_login").val(),
//wplp_referrer_id:$("#wplp_referrer_id").val(),
//block_unblock:$("#block_unblock").val(),
},
// Success
function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
}
);
return false;
});
});
Thanks!
If you want to post data as json, you can use a variation of $.fn.serialize(), Add the jquery extension,
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and use it as,
var data = $('#some-form').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
If posting json is not your requirement $.fn.serializeArray can work.
hope this helps.
What you want is to dynamically add properties to a javascript object. How this can be done is all over the web, but also demonstrated here:
Is it possible to add dynamically named properties to JavaScript object?
so in your case, you would set your object up first before calling .post:
var formData = {};
for (...) {
formData[...] = ...;
}
$.post(ajaxurl, formData, function (data) {
...
});
One way you might accomplish the iteration above is to just collect values from all inputs between your <form> tags:
$('form input').each(function ($input) {
formData[$input.attr('name')] = $input.val();
});
There are lots of ways to skin this cat. Also, jQuery has lots of plugins that might be of help here, although usually YAGNI (You Aren't Going To Need It), so just KISS (Keep It Simple, Stupid).
Here is the solution I was able to get working based on the code provided by #shakib
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var numbers = /^[0-9]+$/;
var wplp_referrer_id = $("#wplp_referrer_id").val();
// Validate fields START
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var data = $('#wplp_edit_member').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
return false;
});
});
This is actually a very simple implementation if you understand Jquery/Javascript! ;o)
Thank you to everyone for your input!
I need to pass an object within the data object but it's not working
I use the following function I found on this very site, very useful, to convert form data to JSON
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and then I need to pass the object as a sub-object, but it's not working. Filters isn't even showing up in the query string parameters in the inspector
var filters = $('.filtersForm').serializeObject();
$.ajax({
type: 'GET',
data: {script:'search',page:page,filters:filters},
success: function(data){
}
});
See how "filters" is missing in the picture
Can someone please explain why I can't pass an object like that?
Try this instead:
$.ajax({
type: 'POST',
data: JSON.stringify({
script: 'search',
page: page,
filters: filters
}),
contentType: 'application/json'
});
Changed type from GET to POST. This will allow you to send a request body.
Stringify your data parameter using the built-in JSON object to stringify your JS object to a JSON-formatted string. (older browsers may not have this built-in object, in that case, add it using json2.js)
Set contentType to application/json. This basically states that the request-body is of this type... which it is because we just stringified it to JSON.
Try to specifiy your filters
For example in try :
jsonfilter = JSON.stringify(filters);
If youre using MVC and ASP.Net you can try
In your HTTPWebMethode which have a jsonResult as Return you can try to specifiy parameters
public JsonResult myPostMethode(string script,object page,List<object> filters){
//make some usefull
var model = script;
return(model,JsonRequestBehavior.AllowGet);
}