Why won't my .ajax request work? - php

The code I want to work:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
dataType: "json",
processData: false,
success: function(html) {
$("#srchFrm").append(html);}
});
The code that works:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
success: function(html) {
$("#srchFrm").append(html);}
});
Unfortunately when I send the first one my post data looks like this "Array ()" and when I use the later I get this "Array ( [sndJson] => [\"8\",\"3\",\"6\",\"7\"] )".
I know that there has to be a simple explanation but I haven't been able to figure it out.
Help please!

Try sending your data in a query string...
$.ajax({
type:"POST",
url:"_Source/ajap/ajap.nlSrch.php?json="+jsonData,
dataType:"json",
success: function(data) {
$("#srchFrm").append(data);}
error: function(xhr, ajaxOptions, thrownError)
{alert("Error!");}
});

You can use shorthand $.post instead of using low level ajax class --- because you don't need to advanced handling. So, this one will be great enough.
$(document.ready(function(){
$("#submit_button").click(function(){
$.post('php_script.php', {
// here's what you want to send
// important -- double quotes, 'cause It's evals as valid JSON
"var1" : "val1"
"var2" : "val2"
}, function (respond){
try {
var respond = JSON.parse(respond);
} catch(e){
//error - respond wasn't JSON
}
});
});
});
PHP code:
<?php
/**
* Here you can handle variable or array you got from JavaScript
* and send back if need.
*/
print_r($_POST); // var1 = val1, var2 = val2
?>
Back to your question,
Why my .ajax request doesn't work?
This is because JavaScript throws fatal error and stops further code execution.
You can catch and determine the error occasion, simply by adding
try {} catch(){} block to the statement you think may occur any error

When you specify dataType: json, jQuery will automatically evaluate the response and return a Javascript object, in this case an array. You're taking the result and adding it as html to #srchForm, so it does not make sense to convert it to a javascript object. Use dataType: html, or none at all.
http://api.jquery.com/jQuery.ajax/

The following examples above are not reusable. I am a huge fan of reuseable code. here is my solution.
Software design 101:
DRY Don't repeat your self. You should wrap your code into an object. This way you can call it from anywhere.
var Request = {
version: 1.0, //not needed but i like versioning things
xproxy: function(type, url, data, callback, timeout, headers, contentType)
{
if (!timeout || timeout <= 0) { timeout = 15000; }
$.ajax(
{
url: url,
type: type,
data: data,
timeout: timeout,
contentType: contentType,
success:function(data)
{
if (callback != undefined) { callback(data); }
},
error:function(data)
{
if (callback != undefined) { callback(data); }
},
beforeSend: function(xhr)
{
//headers is a list with two items
if(headers)
{
xhr.setRequestHeader('secret-key', headers[0]);
xhr.setRequestHeader('api-key', headers[1]);
}
}
});
}
};
Usage:
<script type="text/javascript">
var contentType = "applicaiton/json";
var url = "http://api.lastfm.com/get/data/";
var timeout = 1000*5; //five seconds
var requestType = "POST"; //GET, POST, DELETE, PUT
var header = [];
header.push("unique-guid");
header.push("23903820983");
var data = "{\"username\":\"james\"}"; //you should really deserialize this w/ a function
function callback(data)
{
//do logic here
}
Request.xproxy(requestType, url, data, callback, timeout, header, contentType);
</script>

Related

Pass Boolean Values from Ajax to PHP

I've read a tonne of questions on the subject but none of them seam to solve my particular issue – I guess there's something wrong with the way I've formatted my array of objects in JS. Here's my Ajax function:
var marketing_prefs = [];
$('#save-marketing-prefs input').each(function() {
var tmp_array = {};
tmp_array['marketing_permission_id'] = $(this).val();
if ($(this).prop('checked')) {
tmp_array['enabled'] = 1;
} else {
tmp_array['enabled'] = 0;
}
marketing_prefs.push(tmp_array);
})
console.log(marketing_prefs);
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: marketing_prefs
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
What I'm doing is looping through a simple form with three checkboxes and creating an array of objects which will then go off to Mailchimp. My data arrives intact but the problem is that my boolean values come over to PHP as strings. I've switched from using true and false which was coming over as "true" and "false", to using 1 an 0 but those come over as strings too.
I suppose I could loop through the data and build a new array in PHP but the data is so close to being correct when it arrives that it seems like it must be unnecessary.
How can I get my data over as non-strings?
POST data is sent as simple name=value pairs, there's no syntax to specify datatypes, and everything is parsed as strings.
You can call intval($_POST['marketing_prefs'][$i]['enabled']) to convert it to an integer.
Another option is to convert the marketing_prefs array to JSON.
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: JSON.stringify(marketing_prefs)
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
Then in the PHP you can do:
$marketing_prefs = json_decode($_POST['marketing_prefs'], true);
Since, as Barmar stated, GET/POST can't specify data types (that's a rant in and of itself), one way would t be to cast it.
Very rough example:
var_dump((bool) <variable>);
The issue is if it's anything but 'true', 'empty' or I believe 0 it will return true. I'm in a hurry else I'd flush it out for you better.

AJAX call is not working as expected

I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

Workaround possible for cURL and Javascript?

Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>

JQuery AJAX - Not sending with data?

I'm building a chatroom that sends messages via AJAX. Whenever I hit enter, with the data: parameter, it returns an error, but if I remove data:, it doesn't do anything. This is very puzzling, and I'm wondering what I'm doing wrong. Here is what I have:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: "message="+$("#message").val()+"&user="+$("#user").val()+"&room="+$("#room").val(),
success: $("#message").val(""),
error: $("#message").val("FAIL"),
});
return false;
}
});
I use PHP in my AJAX call, so I don't know if that is causing the problem?
Try this:
...
$.ajax({
type: 'POST',
url: "send-message.php",
data: {message: $("#message").val(), user: $("#user").val(), room: $("#room").val()},
success: function() { $("#message").val(""); },
error: function() { $("#message").val("FAIL"); }
});
...
In the above code:
a) data sent as JSON - this will make sure that any url encoding and escaping will be correctly performed by jQuery as needed
b) success and error options must be callback functions
I would do this just to check if it grabs all the data correct:
var data = {
message: $('#message').val(),
user: $('#user').val
};
console.log(data);
You need to change these lines:
success: $("#message").val(""),
error: $("#message").val("FAIL"),
to
success: function () { $("#message").val("") },
error: function () { $("#message").val("FAIL") // removed trailing comma
I wrapped your handlers in a function and removed the trailing comma.
You can pass an object into data, and jQuery takes care of transforming it into the correct form for the type of request you issue, in this case a POST:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: {
message: $("#message").val(),
user: $("#user").val(),
room: $("#room").val()
},
success: function () {
$("#message").val("");
},
error: function () {
$("#message").val("FAIL");
},
});
return false;
}
});
Also, error and success are callbacks, so you need to provide a function, not a string if you want it called. Fixed it for you.
If you want to pass your data in POST you should use the javascript key:value format (or JSON format).
Input the following in
data: {"message": $("#message").val(),"var2":variable}
and a hint
...
data: $("#form").serialize();
...

Categories