AJAX post data from php file - javascript

I have a php file to validate a form with data that need to get sent through ajax.
The data that I receive back from the php file is unchanged, how can I receive the correct data?
main.js
$("#PersonForm").submit(function()
{
var data = $("form").serializeArray();
$.ajax({
type:"post",
url:"main.php",
act: 'validate',
datatype:"json",
data:data,
function(data){
console.log(data);
}});
return false;
});
main.php
else if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("[A-Za-z]{3,20}$/",$_REQUEST['name'])){
$validateData['name'] = 1;
}else{
$validateData['name'] = 0;
}
echo json_encode($validateData);
The data that originally gets sent in the data array is name:Bob
The expected return is 1 or 0 but I recieve name:Bob back.

Ok, the issue is you have to actually pass that in the data. You are doing this:
$.ajax({
type:"post",
url:"main.php",
act: 'validate', // <--- THIS IS WRONG
datatype:"json",
data:data, // <--- IT SHOULD BE IN THIS
function(data){
console.log(data);
}
});
It has to be in your data variable to be passed. You are using it as an option to the jQuery ajax() method, which doesn't work.
var data = $("form").serializeArray();
data.push({name: 'act', value: 'validate'});
// Then make ajax call here
After serializing your form data, you can add that on as an additional value.

Related

How to retrieve the data returned by an AJAX request

I make an AJAX post request to get processed data from DB in form of "array" [value1, value2, value3,...,valueN] to later use it on a chartJS object.
AJAX Request:
$(document).ready($.post('callMeForAJAX.jsp', function(data){
values = data;
console.log(data);
}));
But it doesn't print anything on the console even though I can see the response on the "Network" tab on the Development Tools from Chrome.
How can I retrieve that data (isn't more than a String) to put it on the "data" parameter of the Chart object?
callMeForAJAX.jsp:
<%# page contentType="text/xml;charset=UTF-8"%>
<%
String data = "[";
for(String s : InfoFacade.getData()){
data += s+", ";
}
data += "]";
response.getWriter().write(data);
%>
Edit: If relevant, I was using 1.2.x jQuery lib and now I have upgraded to 2.x without any changes.
Here we go:
$.ajax({
type: "POST",
url: "/yourUrl",
data: data,
dataType: 'html',
success: function (result) {
$("#yourIdContainerToShowResult").html(result);
}
});
Hope it helps;)
Your $(document).ready() block is not correct.
Try this:
$(document).ready(function(){
$.post('callMeForAJAX.jsp', function(data){
values = data;
console.log(data);
})
});
Try This
$(function(){
callMeForAJAX();
});
function callMeForAJAX(){
$.post( "callMeForAJAX.jsp", function(data){
if(data.length > 0)
console.log(data);
else
console.log("DATA NULL");
});
}

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

send multidimensional array to php using ajax as json and receive html text to show in a div

First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});

Send data fetch from array from page to other page by jquery

i have 2 pages, one that send data from form and send data to second page.
the first page is html, and the second is php.
So, my problem is i send data from form to the second page to enter to SQL statement, and i get data from fetch array, how can i send data from second page to first page and put it in div.
my JS that i will send
// This function to search aqar
function search_aqar(){
var city = $('#city').val();
var aqar_type = $('#aqar_type').val();
var adv_type = $('#adv_type').val();
var search_btn = $('#search_btn').val();
var show_type = $('#show_type').val();
if (city!='' && aqar_type !='' && adv_type !=''){
$.ajax({
url: "request.php?do=search_aqar",
type: "POST",
data: {
city : city,
aqar_type : aqar_type,
adv_type : adv_type,
show_type : show_type,
search_btn : search_btn
},
dataType: "json",
success: function(data){
if(data.process == "ok"){
}
else
{
}
}
});
}
else
{
}
}
and i get data to page name request.php and put variable to sql statement, i need send data to first page on div
Just put a div in your html file like this:
<div id="msg"></div>
And change this:
success: function(data){
if(data.process == "ok"){
}
To this:
success: function(data){
$('#msg').html(data);
}
you may need to return the data as an json_encoded array from your php script and then use
success: function(data){
var variable = jQuery.parseJSON(data);
$("#yourdiv").html(variable['your_array_identifier']);
}
if you are not sending back an array and just a single item then you don't need to return an array and just simply use
success: function(data){
$("#yourdiv").html(data);
}

Categories

Resources