Using the JQuery .Ajax() method? - php

I am creating a site where the user fills out a form, has that data sent to a php script and display result in a div and have been struggling to complete it for a while now. Below is the code i have created:
the button activates this function:
function callFunc()
{
var testVar = "Example 01";
$.ajax(
{
url: "public/includes/userCreate.php",
type: "POST",
data: testVar,
success: function(html)
{
$('#web_Content').html(html);
}
});
};
The PHP file is this:
<?php
$test = $_POST['testVar'];
echo $test;
?>
For some reason though i doesnt work. I mean it doesnt inject the value of the echo command into the div, If however i take out the variable data from the PHP and just have it echo a simple element, it does work and injects the echo value into the div, Below is the code that will run:
<?php
$test = $_POST['testVar'];
echo "<h3>User ???? Created.</h3>";
?>
I think it is because i am not sending data correctly, Could anyone tell me the correct way to send the data to the PHP script and also, how to send more than one variable?

you need data: { testVar: "Example 01"} it is a key value pair. This will generate a query string parameter like testVar=Example%2001

The correct way to send data via the AJAX function is with either an object or string. Examples:
var pData = "testVar=Example.";
$.ajax({
/* Other ajax params */
data: pData,
/* Other ajax params */
});
or
var pData = { testVar: "Example." };
$.ajax({
/* Other ajax params */
data: pData,
/* Other ajax params */
});

Related

How to return values from a function and send to AJAX using jquery?

When i click the button,am calling a function it will return some values.I need to get those values and send through AJAX using Jquery.
Give below the click button function.Inside this function am calling another function(here returning values i need to pass through ajax)
The problem is i cant able to send those values inside ajax.
Can anyone plz help me to do this?I dont know where am doing mistakes.
Here is the function am calling inside button click
in this eaxample i have send with the ajax request the name of the function that i want to use
let fd = new FormData();
fd.append('function_name', 'activity_submitted');
$.ajax({
url: "activity_submitted.php",
type: "POST",
data: fd,
complete: function (results) {
try {
var str = JSON.parse(results.responseText);
}
catch (e) {
}});
in the PHP file (according to the $_REQUETS['function_name']) go to your function, the function will echo a JSON with the values that you want to send back
$_REQUEST is a super global variable which is widely used to collect data after submitting html forms.
function activity_submitted() {
.
.
.
$res = array('articleid'=>$articleid);
$resBack = (json_encode($res, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
}
?>

How to pass Array from Javascript to PHP

I have a function which saves an array each time the button is clicked to localStorage.The button will be clicked multiple times and I need to put this Array list into PHP somehow which is on another page from this file.
Thanks
a.js
(this function listens onLoad of the page)
function doFirst(){
var button = document.getElementById("button");
button.addEventListener("click", save, false);
var buttons = document.getElementById("clear");
buttons.addEventListener("click", clear, false);
var buttonss = document.getElementById("submittodb");
buttonss.addEventListener("click", toPHP, false);
$.ajax({
method: 'post',
dataType: 'json',
url: 'edit.php',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
}
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'num': document.getElementById("num").value,
'methv': document.getElementById("methv").value,
'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value,
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
edit.php
$parsed_array = json_decode($_POST['items']);
and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9
In order to pass this array to PHP you need to:
JSon-encode it
Make an AJAX or POST request to PHP
Parse the passed array into PHP array
If you're using jQuery (if you're not you should start - it is really handy tool) steps (1) and (2) is as simple as
$.ajax({
method: 'post',
dataType: 'json',
url: 'the URL of PHP page that will handle the request',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
In PHP you can parse the passed array with just
$parsed_array = json_decode($_POST['items']);
There is a direct connection between { items: oldItems } and $_POST['items']. The name of variable you give to the parameter in javascript call will be the name of key in $_POST array where it ends up. So if you just use data: oldItems in javascript you'll have all your entities scattered around the $_POST array.
More on $.ajax, and json_decode for reference.
You can create an AJAX function (use jQuery) and send the JSON data to the server and then manage it using a PHP function/method.
Basically, you need to send the data from the client (browser) back to the server where the database hosted.
Call JSON.stringify(oldItems); to create the json string
Do a Do a POST request using AJAX.
Probably the simplest way is using jQuery:
$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
// it worked.
});

Sending data with AJAX to a PHP file and using that data to run a PHP script

I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.

arrays in $.ajax jquery and then sends it to a php page

jQuery(document).ready(function(){
// Set the data text
var dataText = "
{
name: 'John',
time: '2pm'
}";
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
</script>
hello im still learning ajax. how can we push a array of $_POST?
1.im trying to do something like
var dataText['name'] = 'Jhon';
var dataText['time] = '2pm';
then somehow turns it into
$_POST['name'] = 'Jhon';
$_POST['time'] = '2pm';
then send it to the url..
2.is there a way to debug this ? what im doing now is im writing
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
# ok heres how i debug it right now.
ob_start();
// write content
$content = $_POST;
ob_end_clean();
file_put_contents('CACHE',$content);
in to a file, i hope there is a better solution for this..
Thankyou for looking in.
Adam Ramadhan
I'm not entirely sure what you're doing. You seem to be building JSON manually (and not doing it correctly) and then passing that (in the JSON-serialised string form) to your file. You then seem to expect it to be parsed by PHP automatically.
It would be better to send it as key-value pairs. You can let jQuery do this for you if you pass in an object. This won't look much different to your existing code:
var dataText =
{
name: 'John',
time: '2pm'
};
Note that I have removed the double quotes. This is primarily because it is illegal to have a JS string covering more than one line without escaping the line breaks. It is also because you want the object to pass into your $.ajax call.
These should be available as $_POST['name'] and $_POST['time'] now.
file_put_contents('CACHE',serialize($content));
or
foreach($_POST as $k => $v) $content .= $k .'='.$v;
jQuery(document).ready(function(){
// Set the data text
var dataText =
{
name: 'John',
time: '2pm'
};
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
# ok heres how i debug it right now.
ob_start();
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
$content = ob_get_contents();
ob_end_clean();
file_put_contents('CACHE',$content);

Cannot populate form with ajax and populate jquery plugin

I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/

Categories