How to save my data to Mysql without page refresh - javascript

code in my view is bellow:
<?php echo $form->create( "ChatForm", array("id" => "chat_form", "type" => "post",'class'=>'form_chat',"url" => array( "controller" => "qasamples", "action" => "quick_request" ) ) );
echo $form->hidden( 'ChatForm.pid', array('class'=>'chat_input_hidden') );
echo $form->hidden( 'ChatForm.uid', array('class'=>'chat_input_hidden') );
echo $form->textarea('ChatForm.text',array('id'=>'text_input','rows'=>'14','cols'=>'400','style'=>'resize:none;width:907px;border:0px;','onkeyup'=>"onTextChange()")); ?>
<p style="text-align:center;margin-top:20px;"><button type=submit id="chat_send">Send</button></p>
<?php $form->end(); ?>
here is the controller code:
public function quick_request(){
if(!empty($this->data))
{
$fields=array('QasampleAnswer.uid','QasampleAnswer.pid','QasampleAnswer.text');
$data=array(
'uid'=>$this->data['ChatForm']['uid'],
'pid'=>$this->data['ChatForm']['pid'],
'text'=>$this->data['ChatForm']['text']);
if($this->QasampleAnswer->save($data))
{
$data_update=array(
'id'=>$this->data['ChatForm']['pid'],
'status'=>'0');
if($this->Qasample->save($data_update))
$this->render('text2');
}
}
}
Can I just send the message and without fresh my page?
I heard that CakePHP and AJAX can make it work, but I'm a new learner of CakePHP and Javascript also. I hope you guys can help me with it. Thank you very much. The page text2 is to turn the page back to where I was,but it not working well.So I hope I could send my message and just stay this page without refreshing.

Post your data with Ajax, jquery gives you a lot of options to do that... you can also implement a JavaScript and make it call when the for. is submitted (this can be achieved when you add in the array at $form->create array('onsubmit'=>'return yourFunction()') then you have to red your form data in this function, post it via ajax and very important return false in this function (it will prevent the form submitting) you can also make a button instead of the submit button that calls this function but then you have to implement in the text-field that when the user presses enter it should send the data... it is more comfortable with the onsubmit thing.
If you need an example I can also provide a practical code for this...
I will use a cake-less example of the JavaScript
<?php echo $form->create( "ChatForm", array("id" => "chat_form", "type" => "post",'class'=>'form_chat',"url" => array( "controller" => "qasamples", "action" => "quick_request", "onsubmit"=>"return performPostRequest(this)") ) );
this is the part you use to create the form
<script type="text/javascript">
function performPostRequest(form) {
parameters="";
for(var i=0;i<form.elements.length;i++) {
if(parameters!="")
parameters+="&";
if(form.elements[i].checked==true || !(form.elements[i].type=="radio" || form.elements[i].type=="checkbox"))
parameters+=form.elements[i].name+"="+encodeURIComponent(form.elements[i].value);
}
$.ajax({
url: form.action,
data: parameters,
type : 'POST',
});
return false;
};
</script>
and this is the JavaScript function, I use it myself so it should work without a Problem :) It simulates your post request, but uses Ajax and therefore your page will not reload...

You need a simple Ajax Call like the following and modify the form create so that it does not post automatically.
$ajax->form(array('type' => 'post',
'options' => array(
'model'=>ChatForm,
//'update'=>'UserInfoDiv',
'url' => array(
'controller' => 'chatforms',
'action' => 'quick_request'
)
)
));

Related

Keeping a live log while looping through PHP in an AJAX call

I am creating a Wordpress plugin to call an API and create new Wordpress posts for each object returned in the response. Here is the PHP for my function that loops over the API response to create new Wordpress posts:
add_action('wp_ajax_sync_posts', 'sync_posts_from_api' );
function sync_posts_from_api() {
// MAKING API CALL HERE
foreach ($data as $post) {
$new_post = array(
'post_type' => 'post',
'post_title' => $post->title,
'post_status' => 'publish',
'post_author' => 1,
'post_content' => $post->description,
);
$wp_post = wp_insert_post($new_post);
echo '<pre>Post ID ' . $wp_post->ID . ') has been created.</pre>';
}
}
And then I have my Javascript like this:
jQuery(function($) {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'sync_posts'
},
}).done(function(response) {
$('.log').html(response);
});
});
});
This works after the AJAX call is completely finished, but I am hoping to be able to append each echo to the .log container as it goes, instead of all at once when the call is finished. How would I go about making that change?
You can only access the ajax request response after the request finishes. The proper way of accomplishing what you want is using web sockets.
In the old days we used to create an iframe loading with something like this:
foreach ($data as $post) {
echo "
<script>
window.parent.postMessage({message: '".$post."'}, 'http://localhost/');
</script>
";
flush();
}
The browser executes the js in real time when loading the page and the js sends a message to the parent frame. You'll also need the proper js code on the parent frame to receive and process those posts. Even though this may still work, it's very sketchy and not recommended.

How to save a post and custom fields values with ajax in front end in wordpress?

p.s. had placed this simply to share the solution.
I'd like to save a post in front end if we click a button using ajax in js:
var title = $("#portfolioTitle").val();
var customFieldValues = $("#customfieldValue").val();
$("#btnClick").on("click", function() {
$.ajax({
url : ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'data_Publish', portfolioTitle: title, fieldValues: customFieldValues
},
success: function(data) {
if(data == "exists") {
console.log("Add a different title");
} else {
console.log("post added");
console.log(data["link"]);
console.log(data["title"]);
}
}
});
});
Placing my own answer but wondering if there is there any speed or security improvements?
For example we could add a caching system, or define our own ajax (Maybe a help could be answering: How to implement the code in the link using the case scenario we have on this question?) in order not to have wordpress loading all the files but here we are doing a http request, anyway, if any of you would want to give their 2 cents to make it faster, It'd be great.
Let's say we want to add posts via ajax in frontEnd in wordpress and we want to check if the title is unique in the database otherwise tell the user to add a different title:
We have a button to click:
<button type="button" id="btnClick">Load</button>
We have an input for the title and a custom field:
<input type="text" id="portfolioTitle" name="portfolioTitle" value="" placeholder="Your title...">
<input type="text" id="customfieldValue" name="customfieldValue" value="" placeholder="Your customFieldvalue...">
The JS. Firstly you need to load wordpress ajax (This is the bit that could be improved if anyone fances to):
var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
Then your javaScript:
var title = $("#portfolioTitle").val();
var customFieldValues = $("#customfieldValue").val();
$("#btnClick").on("click", function() {
$.ajax({
url : ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'data_Publish', portfolioTitle: title, fieldValues: customFieldValues
},
success: function(data) {
if(data == "exists") {
console.log("Add a different title");
} else {
console.log("post added");
console.log(data["link"]);
console.log(data["title"]);
}
}
});
});
Then in function.php:
function data_Publish() {
$post_title = $_POST['portfolioTitle'];
$post_custom_field = $_POST['fieldValues'];
$post = array(
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'page',
'page_template' => 'portoflio.php'
);
if ( get_page_by_title( $post_title ) === null ) {
// the title is unique, we can add the new page
$post_id = wp_insert_post( $post );
add_post_meta($post_id, 'customField', $post_custom_field], true);
$link = get_permalink( get_page_by_title( $post_title ) );
$title = get_the_title($post_id);
$newPostAttributes[] = array("link"=>$link, "title"=>$title);
echo json_encode($newPostAttributes);
} else {
// that title already exists, tell the user to change it
echo json_encode("exists");
}
wp_die();
}
add_action('wp_ajax_data_Publish', 'data_Publish');
Basically that function is a normal wordpress query. Therefore you could use the same logic to retrieve post values if You'd want to, for example you won't be using $post_id = wp_insert_post( $post ); but maybe to get the tittle back to the user you'd use $postTile = get_the_title();.
Let's break it down:
In ajax we use action: 'data_Publish', portfolioTitle: title where data_Publish is our php function, and portfolioTitle: title is what we are sending.
In function we can see: $post_title = $_POST['portfolioTitle']; that's our title that we have sent via ajax. With 'page_template' => 'portoflio.php' we can add our own template to that page.
Then we need to use if ( get_page_by_title( $_POST['portfolioTitle'] ) === null ) { to check if that title exists or not, if it doesn't exist, we add the posts to the database with $post_id = wp_insert_post( $post );
Once we added it we use the following to add any other values to our custom field in the newly created postadd_post_meta($post_id, 'customField', $_POST['customfieldValue'], where customField is the name of the custom field we want to create in the new post we just added.
So if the posts doesn't exist, we save it and we can send back to ajax its title and its link so that we could shows it to the user as a response if We'd ever want to.
So we define title and link like this and we create a multidimentional array to send the data back to the front end:
$link = get_permalink( get_page_by_title( $post_title ) );
$title = get_the_title($post_id);
$newPostAttributes[] = array("link"=>$link, "title"=>$title);
If the title exists we send back a response echo json_encode("exists");
We need to die the query for safeness wp_die();
If We'd ever want to make ajax available to no logged user, remember wordpress ajax is only available to admin, so we need to add:
add_action('wp_ajax_data_Publish', 'data_Publish');
add_action( 'wp_ajax_nopriv_data_Publish', 'data_Publish' );
Basically in function.php wordpress uses wp_ajax_ +"name of our function" and wordpress has wp_ajax_nopriv_ to make ajax available if not logged.
I hope It helps anyone and if any of You could improve it, It'll be better for all.

http400 Bad Request from AJAX code for WordPress

I am new to website development and am developing a WordPress site. Although similar to another question on SO, that question does not use jQuery.AJAX but rather jQuery.post with a request type of 'category'. I have some sort of syntax problem when trying to use AJAX. I have created a simple plugin to enter a name, send it to the server, and have it echoed back. Following is the php file, my-ajax-test.php:
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'my-script-handler', plugins_url( '/my-ajax-test.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'my-script-handler', 'ajax_test', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
function my_ajax_test() {
/**** Create Input Form ****************************/
?>
<h2>Select Persons You Wish to Register</h2>
<form action="">
<input type="text" id="ajax_guest_name" name="guest_name">
<p id="ajax_guest_text">Enter Guest Name</p>
<br><br>
<input type="button" id="ajax_rsvp" name="ajax_guest" value="Register Guest">
</form>
<?php
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
function my_ajax_callback() {
$guest_name = $_POST[ajax_guest_name];
echo $guest_name;
die();
}
};
add_shortcode('My-AJAX-Test', 'my_ajax_test');
The JS file, my-ajax-test.js looks like this:
// use wordpresses version of script
var $jq = jQuery.noConflict();
$jq(document).ready(function(){
$jq("#ajax_rsvp").click(function(){
/* Send guest name to server via AJAX */
var g_name = document.getElementById("ajax_guest_name").value;
alert("RSVP Button was clicked with Guest Name: " + g_name);
$jq.ajax({
url : ajax_test.ajax_url,
type : 'post',
data : {
action: 'my-ajax-test',
ajax_guest_name : g_name
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
}); // End of button click function
}); // End of Main Document Ready Function
All seems well, but nothing is being sent to the server with the button click. The Console log has an error:
HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
(XHR)POST - http://localhost:81/wordpress/wp-admin/admin-ajax.php
I keep going over the code to see what I have wrong and can not find it. Any suggestions would be appreciated.
Hello LCSF and welcome to StackOverflow.
You have multiple errors in your code. You are posting your data to a my-ajax-test function (which doesn't exist. Your main plugin function is my_ajax_test) when what you should be doing is posting it to your my_ajax_callback function. That is the function you registered via the wp_ajax action hook. That is why Wordpress cannot find you action. In addition to that, your callback function is encapsulated inside your main plugin function, which is why even if you change the Ajax request the function will not be found due to it's scope. To solve this do the following:
In your JavaScript file change the action in your Ajax function to my_ajax_callback
Extract the my_ajax_callback function out of the my_ajax_test function. Your code structure will then look like this:
function my_ajax_test(){
//content
}
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
function my_ajax_callback(){
//content
}
Action my-ajax-test is not what you need to pass as action parameter.
Replace:
action: 'my-ajax-test',
with:
action: 'my_ajax_callback',

How to pass results from jQuery function to PHP

I have a list of dropdown options for a survey, and am counting their choices using jquery. The counting code works fine and has been confirmed. The trouble comes with passing the variable to PHP (from what I've read, I'll need to use the POST function but am having trouble) in order to modify the user's meta data based on the survey responses.
Here's the jquery / counting code which works fine:
$('select').change(function() {
// get all selects
var eSelects = $('select.e');
// set values count by type
var eyes = 0;
// for each select increase count
$.each(eSelects, function(i, s) {
// increase count
if($(s).val() == '1') { eyes++; }
});
// update count values summary
$('.cnteyes').text(eyes);
});
And here's the PHP which is not working (don't understand how to use the POST function, so left that out):
<?php
$response = 'cnteyes';
if ( ! add_user_meta( get_current_user_id(), 'survey', $response, true )) {
update_user_meta ( get_current_user_id(), 'survey', $response );
}
echo get_user_meta( get_current_user_id(), 'survey', true );
?>
Any help would be greatly appreciated! I'm completely stuck and do not understand how to pass jquery to PHP. Thanks for your time.
You can pass data through POST using jQuery.ajax
**JS File**
$.ajax({
url: "path/to/php/file.php",
type: "POST",
data: {
'someData': 'someData' //you pass your results here
},
datatype: "json",
success: function (result) {
}
});
**PHP File**
<?php
$someDate = $_POST['someData']; // you access your results here
?>
// update count values summary
$('.cnteyes').text(eyes);
Above Code should be changed to
// update count values summary
$('.cnteyes').val(eyes);
text() function just fills the input with the text provided but not the value. But Val() function will set the value of the input object to the provided one.
Also on the php snippet the $response should be set to $_POST['cnteyes']
<?php
$response = $_POST['cnteyes'];
if ( ! add_user_meta( get_current_user_id(), 'survey', $response, true )) {
update_user_meta ( get_current_user_id(), 'survey', $response );
}
echo get_user_meta( get_current_user_id(), 'survey', true );
?>
What you want is AJAX, which is asynchronous JavaScript and XML. The answer by #marcus-ekwall here should point you in the right direction, but the short of it is that POST and GET are ancient pre-JavaScript methods that (among other things) result in page refreshes.
Tutorials Point introduces AJAX as follows:
Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
You may want to begin by looking at their PHP and AJAX Example.
You can try this.
js code
$('select').change(function() {
// get all selects
var eSelects = $('select.e');
// set values count by type
var eyes = 0;
// for each select increase count
$.each(eSelects, function(i, s) {
// increase count
if($(s).val() == '1') { eyes++; }
});
$.post(
"result.php",
{ eye: eyes },
function(data) {
$('.cnteyes').val(eyes);
}
);
});
result.php
<?php
if( $_REQUEST["eye"] ) {
$response = $_REQUEST['eye'];
//write your code here.
}

How to get data from AJAX in PHP without using a function

NOTE: No more down-votes please, just because you cannot answer the question/ or cannot understand the problem doesn't mean you have to down-vote. I clearly said I can provide more information/be more specific if you need me too.
Edited title for clarification
I am using javascript to validate the form client side, then using ajax to pass 3 arrays worth of data to a separate PHP page for processing. Just trying to perform a basic query with one of arrays before i begin.
the ajax request says it's working, and when I go into the network tab, then click response, it shows all the arrays with the correct values/indexes.
But on the PHP side nothing is happening. I have no idea how to debug the PHP because it's on a different page. I'm assuming this has something to do with my syntax, as I have got this too work before, but i used ajax in a function. I am very new to ajax, so I am not too sure if I am doing this correctly. I have tried a valid $wpdb query on the page and nothing is happening. How do i properly structure my PHP page to work with the ajax? Any way I can debug my PHP when ajax fires?
If you need additional information please let me know.
AJAX CALL:
$.ajax({
type: "POST",
url: "?page_id=251",
data: { vData: videoData, tsData: tsValues, dData: tsDescriptions},
success: function(){
$("#errorMessage").text("ajax success.");
}});
?page_id=251 (PHP page)
<?php
$videoData = $_POST['vData']; // i have also tried $_GET['vData'];
$vSRC = $videoData[0];$vTIT = $videoData[1];$vDES = $videoData[2];$vPDF = $videoData[3];$vDAT = $videoData[4];
$uID = get_current_user_id();
global $wpdb;
$wpdb->insert( $wpdb->prefix."uservideo", array(
"user_id" => $uID,
"video_src" => $vSRC,
"video_title" => $vTIT,
"video_description" => $vDES,
"pdf_file" => $vPDF,
"video_date" => $vDAT
));
?>
I found the solution to the issue.
I needed to call a function with the ajax, cannot just call a page. I'm sure you can just call the page but no one knows how apparently.
AJAX
<script type="text/javascript">
function insert_data(vidData,timesData,descData){
$.ajax({
url: '?page_id=251',
type: 'POST',
data: {action: 'insert_video', vData: vidData, tsData: timesData, dData: descData },
dataType: 'json',
success: function(response){
alert('dhsdhjsdjhsjhdjhsd');
}
});
}
</script>
PHP
<?php
function insert_video($videoData,$tsValue,$tsDesc){
$videoData = $_POST['vData'];
$vSRC = $videoData[0];$vTIT = $videoData[1];$vDES = $videoData[2];$vPDF = $videoData[3];$vDAT = $videoData[4];
$tsValue = $_POST['tsData'];
$tsDesc = $_POST['dData'];
$uID = get_current_user_id();
global $wpdb;
$wpdb->insert( $wpdb->prefix."uservideo", array(
"user_id" => $uID,
"video_src" => $vSRC,
"video_title" => $vTIT,
"video_description" => $vDES,
"pdf_file" => $vPDF,
"video_date" => $vDAT
));
}
echo insert_video($_POST['vData'], $_POST['tsData'], $_POST['dData']);
?>

Categories

Resources