Always back to index page using tinymce with ajax - php

I want to add data using textarea tinymce with ajax post. but when I click the button and I see in firebug I look at the network tab after calling the ajax page to save the data and then automatically call to the index page. But this problem only happens when I publish to hosting with web domain. everything went smoothly while on localhost. please check my code below and give me explanation and code improvement. Thank you very much.
add.php
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<textarea class="tinymce" id="contentblog" name="contentblog"></textarea><br/>
<button type="button" id="AjaxSubmit" name="submit">Submit</button>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="plugin/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: "textarea.tinymce"
});
$(document).ready(function () {
$('#AjaxSubmit').click(function (){
var contentblog = tinymce.get("contentblog").getContent();
var form_data = new FormData();
form_data.append('contentblog', contentblog);
$.ajax({
url: 'add-ajax.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert("Success !");
return true;
}
});
});
});
</script>
</body>
</html>
add-ajax.php
<?php
include_once('connection.php');
$contentblog = $_POST["contentblog"];
$data = array(
"contentblog" => $contentblog
);
$jsondata1 = json_encode($data);
$jsondata2 = json_decode($jsondata1, true);
$contentblog = $jsondata2['contentblog'];
$GetContentBlog = addslashes($contentblog);
$result = mysqli_query($mysqli, "INSERT INTO t_test(iscontents) VALUES('$GetContentBlog')");
if($result){
echo 'is success';
}
?>

You need to block the normal form submit of the html form:
$('#AjaxSubmit').click(function (event ){
event.preventDefault();
Without this the html form is submitting the form via normal http post and gets redirected!
See https://api.jquery.com/event.preventdefault/ for more information!

Related

Simple php ajax html issue

simple question for most of you but for me, being a newbie in php and jquery+ajax, not really: how to replace my index.html with some other html code, requested by ajax call from a php file?
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Login page</h1>
<button id="btn_login">Login</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
javascript.js
$('#btn_login').click(
function(){
$.ajax({
url: "login.php",
type: "GET",
success: function(data){
// what to do here?
}
});
}
)
login.php
<?php
echo '<div>Succesful login</div>';
?>
TLDR: I want to replace the "Login page" + login button screen to "Succesful login" when clicked the button.
Thank you
you need to identify -or classify- your <h1> tag to be easily able to change
it's contents ,
<h1 id='title'>Login page</h1>
then , within your ajax call, if success you can change the content like that:
success: function(data){
// what to do here?
if (data) {
$('#title').html(data);
$('#btn_login').remove();
}
}
Take a look: ( https://www.w3schools.com/xml/tryit.asp?filename=tryajax_first : w3schools )
...
You can try this:
$('#btn_login').click(
function(){
$.ajax({
url: "login.php",
type: "GET",
success: function(data){
document.body.innerHTML = ""; // remove all content from the document
document.write(data); // write the returned div to the document
}
});
}
)

How to pass data from a PHP file back to the original without page refresh?

I am trying to have the output from a PHP file display in the original page containing the form, without having to refresh the page.
I am currently using AJAX to do so but I am not able to pass the value of the submitted PHP file back to the index.php page - this needs to be done without having the page refreshed.
Overall
User enters some data and submits the form
That data is passed to a PHP file through AJAX
Some pieces of data, which were manipulated through the PHP file, are then echoed out onto the original index.html file without the page refreshing
Below you will find the code that I am currently using to try and achieve this.
index.php
<form>
<input type="text" name="hi">
<input type="submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
});
});
});
</script>
post.php
<?php
echo "Hello";
$name = $_POST['hi'];
echo $name . "This is a test";
?>
I would appreciate any help, thanks!
How about this simple solution. Just copy and paste this code into a file called index.php and whatever text you enter in the input field will be outputted by PHP. Hope it helps!.
<?php
$data = array();
if(isset($_POST['userText']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'The data you entered is: ' . $_POST['userText'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="hi" id = "someID">
<input type="submit" id = "sendInfo">
</form>
<div id = "random"></div>
<script type = "text/javascript">
$("#sendInfo").click(function(){
var someText = document.getElementById("someID").value;
var userText = JSON.stringify(someText);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {userText: userText},
success: function (result) {
console.log(result);
$("#random").html(result);
}
});
return false;
});
</script>
</body>
</html>
Add 'success' to your object and pass in a parameter to the function. That will hold the results from the php file.
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(results) {
console.log(results);
}
});
What this does is, on a successful ajax call, stores all of the content sent from the post.php file into the results variable.' In this case it will be whatever $name is and 'This is a test.'

jQuery AJAX method not working

I'm going to create a page that user can input something in textarea (index.php). When user click on Tweet, it will get all text that user typed to page tweet.php (I used jQuery Ajax method). After that, it will redirect to page show.php
Here is my code
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Tweet</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function save_tweet(text_tweet){
$.ajax
({
type: "POST",
url: "tweet.php",
data: "text="+text_tweet,
success: function(msg)
{
if(msg==1){
window.location.href="show.php";
}else{
alert("Error");
}
}
});
}
$("#tweet").bind('click', function(){
var text_tweet = $("#text_tweet").val();
if(text_tweet==""){
$("#show").html("Blank text");
return;
}else{
$("#show").html("");
save_tweet(text_tweet);
}
});
});
</script>
</head>
<body>
<center>
<textarea name="text_tweet" cols="61" rows="5" id="text_tweet"></textarea>
<br/>
<div id="show"></div>
<br/>
Tweet
</center>
</body>
</html>
tweet.php
<?php
session_start();
if(isset($_POST['text'])){
$_SESSION['text_tweet'] = $_POST['text'];
}
?>
show.php
<?php
session_start();
echo $_SESSION['text_tweet'];
?>
The problem is when i input some text in textarea and click Tweet, it will alert Error. Can anyone know what is the problem?
Thank in advance.
Why are you checking if msg is 1 ? Are you returning 1 in your response body ? Looking at the JQuery docs it the success function callback is described as:
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
You could log the value of msg and see what is actually contains.
Try changing your code to:
$.ajax
({
type: "POST",
url: "tweet.php",
data: {text: text_tweet},
success: function(msg)
{
if(msg==1 || msg=="1"){
window.location.href="show.php";
}else{
alert("Error");
}
}
});
tweet.php
<?php
session_start();
if(isset($_POST['text'])){
$_SESSION['text_tweet'] = $_POST['text'];
echo 1;
}
?>
try
if(msg.length){
window.location.href="show.php";
}else{
alert("Error");
}
Add the dataType in your ajax:
dataType: 'text',
Add above line in your ajax code.
And change your below line:
var text_tweet = $("#text_tweet").val();
with the:
var text_tweet = $("#text_tweet").text();
And in your tweet.php file add this line:
echo "1";

Pass javascript variable to php with ajax and the result doesn't show anything

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

$.ajax data not posting specified value to $_POST

Okay, what have I done wrong here?
I'm trying to .POST data from a Form with JQuery $.ajax function and return json data. But every time the post data is null.
Here is the HTML/JQuery Part
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
</head>
<body>
<form action="testform" method="post">
OLD ID:
<input id="OldID" name="OldID" type="text"><br>
NewID:
<input id="NewID" name="NewID" type="text"><br>
<input id="do" name="do" type="button" value="Get New ID">
</form>
<script type="text/javascript">
var CID = $('#OldID').val();
$(document).ready(function(){
$('#do').click(function(){
sendValue();
});
function sendValue(CID){
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>
</body>
</html>
Here's the PHP page
<?php
if (isset($_POST['OldID'])){
$value = $_POST['OldID'];
}else{
$value = "ELSE VALUE";
}
echo json_encode(array("NewID"=>$value));
?>
I'm sure this is a simple mistake on my part but I'm just going in circles at this point.
Thanks in advance!
$('#do').click(function(){
sendValue();
});
should be:
$('#do').click(function(){
sendValue("VALUE TO SEND TO THE SERVER");
});
because
function sendValue(CID){
takes the scope of CID which it seems you might think should be this var CID = $('#OldID').val();
Your mistake is that you are getting the value of the OldID field in your script, and not on some event handler method. This causes when the script is loaded (when the page is being viewed), the value of the text input is kept on variable CID. and when the user clicks on the #do button, then the value of CID is still the same as the one when the page was loaded. So no value is stored in CID variable, so no value is sent via AJAX.
Define another function (Say sendOldID) that reads the value of the text input in the CID variable, and then calls the sendValue() method with CID paramter. The use that function as the event handler of the #do button clicked.
<script type="text/javascript">
$(document).ready(function(){
$('#do').click(function(){
sendOldID();
});
function sendOldID() {
var CID = $('#OldID').val();
sendValue(CID);
}
function sendValue(CID) {
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>

Categories