Pass Ajax Variable value to html element in different page - javascript

How can I pass data from a query in php and set it's result using an ajax method.
Here is what I have so far in a file called file1.php:
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
I wanna put the contents in this html element in the php file file2.php:
<p id ="resultFromFile1" name = "results">No Results</p>
Many stack overflow posts haven't been any help. Could someone point me in the right direction?

It's wrong approach.
You should rather create php script which will save your ajax request data in let's say database and then in file2.php load this data from DB, not directly update file

First of all what kind of content is query.php returning? Is it a JSON Object or are you just "echoing" the output as a string?
Next Question: Are you using jQuery, AngularJS or something in that direction?
Usually what you want to do is get the information from the "query.php" and pass it as a JSON formatted ajax result...
Now to your actual Problem: You want to get the element called "resultFromFile1" that's inside file2.php but you aren't adding anything to the "visible scope" yet since Load only loads the content but it doesn't add the content to any element you have to define an element holding your "file2.php". If i were you to avoid all these Problems i would use AngularJS for displaying your data in to a view and just include your "result" template via ng-include and let the ajax fill the document..
To solve your Problem:
<script type = "text/javascript">
// Your Solution
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
// My Solution for this problem using native js
// Load the "file2" contents in to the file2Holder element
LoadUrlToElement('file2.php','file2Holder',function(data){
/* When the first loading of file2.php is done, load the results from the query.php and put it in to the element called "resultFromFile1" which we just loaded and placed in to the dom before. But i would recommend you to use AngularJS to avoid this Callback hell and get many cool features that webdevelopers don't want to miss these days.... */
LoadUrlToElement('query.php','resultFromFile1',function(){
alert('Content of resultFromFile1 is => '+document.getElementById('resultFromFile1'));
});
});
function LoadUrlToElement(url,elementID,done) {
$.ajax( { type : 'POST',
data : { },
url : url,
success: function ( data ) {
if(document.getElementById(elementID) === undefined){
alert("Can't proceed cause the content holder"+elementID+" is not found");
return; // Abort here cause there is no container with this id...
}
document.getElementById(elementID).html = data;
if(done !== undefined && typeof done === 'function') done(data);
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<div id="file2Holder"></div>

Related

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );

magento getting the whole page instead of just variables value via controller

I expect the controller to return variable's value from efund_2.phtml when the ajax request is made via controller but its returning the initiator's(efund.phtml) entire html.
/**
* Called using AJAX POST method.
*/
public function getEfundAction()
{
// Get post data.
$PostData = $this->getRequest()->getPost();
$Param1 = $PostData['param1'];
$Param2 = $PostData['param2'];
$ModelLayout = new Pteb_System_Model_Layout_Backend();
$ModelLayout->LoadLayout();
$Block = $ModelLayout->SetContentBlock( 'efund-block', 'Pteb_System_Block_Cms' );
$Block->setTemplate('adminpteb/efund/efund_2.phtml');
// Passing parameters to template file.
$Block->setData( 'MyPostData1', $Param1 );
$Block->setData( 'MyPostData2', $Param2 );
$ModelLayout->ShowLayout();//this getting the whole page html. But I just need the value returned by the variables in the page(efund_2.phtml).
}
PHP function in efund.phtml page.
function GetEFund()
{
var url='http://emall.3pteb.my/adminpteb/efund/getEfund';
var DivResult=jQuery('#DivResult');
var data = {
"action": "test"
};
$.ajax({
type:'GET',
url:url,
dataType: "html",
data: data,
success: function(data) {
alert(data);
DivResult.append(data);
}
});
}
And the above function is initiated by :
$('a').bind('click', function(){
GetEFund();
});
I'm getting this error:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
In the network tab (Chrome console), I see the call is made to the
function getEfund(). However when clicked on it, it shows the entire
html of efund.phtml page , in fact that was what returned by the
controller. How can I make efund_2.phtml return its variables?
Seems like you need to set JSON headers in your controller:
// Set our return json.
$sJson = json_encode( $aDataArray, 1 );
// Send it back to our ajax call.
$this->getResponse()->setHeader( 'Content-type', 'application/json' );
$this->getResponse()->setBody( $sJson );

How to use ajax to save re-ordered node in Drupal 7?

I use the Jquery .sortable() function to let the site admin re-order some list elements on the start page on a Drupal 7 site. Then I want the admin to be able to save the node to keep this new sort order. In order to do this I added a Save button with js on the client side. When clicked on I have this so far:
$('a.save').on('click', function () {
// get the current nid
var nid = Drupal.settings.mymodule.currentNid;
var data = [];
// copy the re-ordered html list
data['body'] = $('.field-name-body').clone()
$.ajax({
// after reading the ajax api documentation I am more than confused about the url to use
url: '??',
type: 'post',
dataType: "html",
data: {
nid: nid,
body: data['body'].html()
},
success: function(data) {
if (data == false) {
alert('Not saved, access denied.');
} else {
alert('Changes saved');
}
}
});
So in the normal world I would write a php script that saves the data in the node with the specified node id. And the url should point to that script... But I am stuck in the Drupal 7 documentation on how to do this... All examples i can find describes how to pull html from the server side to the client side, but I want to copy html from the client side and save it in the specfied node on the server side. Should I write a function to recieve the ajax request in a custom module? Can anyone point me in the right direction?
PARTIALLY SOLVED:
I finally found the solution about the url which became like this:
url: Drupal.settings.mymodule.ajaxUrl + "/" + nid,
I have now written a custom module where I successfully can save content in a certain node field with this code:
function save_node_init() {
drupal_add_js(array('save_node' => array('ajaxUrl' => url('save_node/ajax'))), 'setting');
drupal_add_js(drupal_get_path('module', 'save_node') . '/save_node.js');
}
function save_nod_menu() {
$items['save_node/ajax/%'] = array(
'page callback' => 'save_node_ajax_callback',
'access callback' => 'user_access',
'access arguments' => array('administer users'),
);
return $items;
}
function save_node_ajax_callback() {
$html = isset($_POST['body']) ? $_POST['body'] : null;
$nid = isset($_POST['nid']) ? $_POST['nid'] : null;
$node = node_load($nid);
$node->body['und'][0]['value'] = $html;
node_save($node);
//ajax_deliver($html);
drupal_exit();
}
As you can see I put the html in the body of the node and then saves it. My final problem is now that I don't want to replace the whole content in the body field. Just the ul and its list elements. Any suggestions would be much appreciated!

Use one ajax call for different page and div?

I use this code to make ajax call to change the content of div in main page without reloading the page :
function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}
and I call it like that :
<p><a onclick="ajaxcall()" >Create</a></p>
The issue is very complicated because I have to call 4 pages in the same div :
create.hmtl ; update.html; delete.html ; read.html
Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :
create.html :
<div id="container">
....
</div>
<div id="container-1">
....
</div>
So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?
Edit
To explain more my problem, I have 4 options (create/update/delete/read) with 4 pages, and in every page they are 2 div and 2 contents for 2 forms, I should change div content of every option(CRUD) for every form in webpage!
form -> ajax call content -> create.html -> div:container
form-1 -> ajax call content -> create.html -> div:container-1
form-1 -> ajax call content -> update.html -> div:container-1
You can add those as parameters to the function and make it like below
function ajaxcall(url, data, targetDivId)
{
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
$("#"+targetDivId).html( returnedData );
}
});
}
For your scenario:
I assume that even the AJAX url may change as currently it's pointing to create.php. In case it's same then you can avoid tht parameter.
<p><a onclick="ajaxcall('/create.php', {} , 'container-1')" >Create</a></p>
<p><a onclick="ajaxcall('/update.php', object2 , 'container-2')" >update</a></p>
<p><a onclick="ajaxcall('/delete.php', object3, 'container-3')" >Delete</a></p>
Following mohamedrias' answer, if you also needed to process each alternate path in the CRUD use case differently, you can use global event handlers.
Don't handle when making the request:
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
}
});
Do handle seperatley for each alternate path in CRUD
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var url = settings.url;
if (url.match(/create.php/) && query.match(/container1/)){
$("#container1").find(".form-1").html( xhr.responseText );
}
});
You should also notice that the selector in my example implies that "form-1" is a Class and not an ID.
IDs must be unique but Classes can occur many times.
Following this rule, if you wanted to reuse the same form for each alternate path you can do so by addressing discrete elements in the form using unique class names for each element. The container Div must have a unique ID (as you have already done). But you must give that element context by chaining the selectors to first select the div using ID and then select the element using class.
If I understood it correcyly you want to provide an argument to the ajax calling function to apply the return content from "/create.php" to a different div.
function ajaxcall(id, path)
{
$.ajax({
type: "POST",
url: path,
success: function( returnedData ) {
$("#"+id).html( returnedData );
}
});
}
And in html you can set the id like
<p><a onclick="ajaxcall(this.id, "/create.php")" >Create</a></p>
var xhr = new XMLHttpRequest();
xhr.onload = function(){
var document = xhr.response;
var container = document.getElementById('container');
var container-1 = document.getElementById('container-1');
console.log(container, container-1);
// or
// var containers = document.querySelectorAll("#container, #container-1" );
//console.log(containers);
}
xhr.open('POST','/create.php');
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.responseType = 'document';
xhr.send();

Javascript get current page html (after editing)

I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.
I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.
I can get the copy of the file using this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
Which works fine and gets me the html I expected and see when viewing the page in notepad.
The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:
origPage.getElementById('editor').innerHTML = e.html;
But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:
alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);
But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?
EDIT:
Complete page html below:
<!DOCTYPE html>
<html>
<body>
<div id="editor">
<h1>This is editable.</h1>
<p>Click me to start editing.</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="snapeditor.js"></script>
<script type="text/javascript">
var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
var isSuccess = true;
//var origPage = e.html;
var origPage;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
// Actually perform the save and update isSuccess.
// Javascript:
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
//origPage shows expected html as this point
//alert($(origPage).getElementById('editor').innerHTML);
//alert($(origPage).html().getElementById('editor').innerHTML);
$(origPage).getElementById('editor').innerHTML = e.html;//fails here
alert(origPage);
//alert(newHtml.getElementById('editor').innerHTML);
$.ajax({
data: {html: origPage, docName: 'example1.html'},
url: 'savePage.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
isSuccess = true;
}
});
return isSuccess || "Error";
},
onUnsavedChanges: function (e) {
if(confirm("Save changes?")) {
if(e.api.execAction("save")){
//location.reload();
}
} else {
e.api.execAction("discard");
}
}});
</script>
</body>
</html>
It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited
Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?
If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.
Code to send the data:
javascript/jQuery:
alert(e.html); //you should see the user-edited HTML
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'userStuff=' + e.html, //var_name = var_contents
success: function(d){
window.location.href = ''; //redisplay this page
}
});
another_php_file.php:
<?php
$user_edits = $_POST['userStuff']; //note exact same name as data statement above
mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());
echo 'All donarino';
The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.
The data is received as $user_edits, and then inserted into your MySQL db
Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?
This is where you haven't provided enough information, and why I wanted to see all your code.
ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?
You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:
https://phpacademy.org/videos/php-and-mysql-with-mysqli
https://phpacademy.org/videos/oop-loginregister-system
If all you need to do is insert the contents of e.html to replace the #editor div, then try this:
$('#editor').html(e.html);
HOWEVER, you need an event to trigger that code. Are you able to do this?
alert(e.html);
If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.

Categories

Resources