My Ajax Form Submission script isn't working - javascript

I've got all my form areas setup correctly and my Javascript received them. I've tested this with "alert", but for some reason, I don't know why, my form either isn't submitting or the PHP is wrong.
Here's my JavaScript:
//Main Content
var ed = tinyMCE.get('content');
var doc = document.getElementById("docid").value;
//Post Area
ed.setProgressState(1); // Show progress
$.ajax({
type: 'POST',
data: {'docid':document.getElementById("docid").value, 'content':tinyMCE.get('content').getContent()},
url: 'save.php',
success: function () {
ed.setProgressState(0);
$("#notice").fadeIn("slow").fadeOut(3000);
}
});
return false;
Here's save.php:
$id = $_POST['docid'];
$cn = $_POST['content'];
require_once("scripts/php/rq/connect.docs.php");
mysqli_query=($con, "UPDATE wordit_documents SET main_document='".$cn."' WHERE id='".$id."'");

1. ensure client is sending correct data.
Try using the inspector in Google Chrome, and activate the network tab.
Under form data you can see the data sent to the server (the picture shows the text of this answer being sent to stackoverflow to be saved as a draft.).
If not:
Make sure your script is wrapped in a jQuery.ready function.
jQuery(document).ready(function($){
// goes in here
});
Test the output of
console.log(document.getElementById("docid"));
console.log(tinyMCE.get('content'));
console.log(tinyMCE.get('content').getContent());

I Found The Problem it was because of an "=" In The mysqli_query, Thanks For Answers

Related

document.form.submit() is too slow to complete before window.close()

I am having an issue with saving a form. The form itself has about 40 rows with around 12 inputs for each row in this style:
On save, it should POST and then close the window. However, it never truly saves it. This makes me think that it is closing the window before it saves. Here's the code in question:
$('#save-btn').click(function() {
document.form.submit();
window.close();
};
If I remove the window.close() and use the inspector than I see in the parameters field that all the values save correctly. This is again what lead me to think that the window is closing to early.
I have tried using the following in the above #save-btn function:
setTimeout('window.close()',5000)
Yet this never seemed to execute the window.close() after the 5 seconds and all around seems like bad programming to force it to wait 5 seconds and then close when it could take any amount of time.
I then attempted to use an AJAX request like:
var _url = 'submit?nameParam="+nameParam+"&com=editlist&'+$('form').serialize();
console.log(_url); //just to see what its pushing out
$.ajax({
url: _url,
error: function(){
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
This resulted in 414 Request-URI Too Long. I know the case for this is it should be a POST to begin with, but I was just trying to make it work.
Just because, this is how our form is set up:
<form name="form" action="submit" method="post">
Our solution was to close the page from our action page
Remove the serialized data from your _url and instead pass it through the .ajax() request with the data setting:
var _url = 'submit?nameParam="+nameParam+"&com=editlist';
$.ajax({
url: _url,
method: "POST",
data: $('form').serialize(),
error: function() {
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
Your ajax approach is correct because you can understand that form submit done correctly with code, on success post it is easy to close the window.
For sending a POST request, you have to make some small changes in your code...
Don't serialize your form and add URL, it is not safe (not working for your situation).
Post your values as "post data".
Here is documentation about it.
https://api.jquery.com/jquery.post/
Please try and update your question if you cannot understand how.

issue using $.ajax with php effectively

I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function

Ajax is switching the contents of the Data variable

I contacted the tech support about a problem with Ajax where Ajax wouldn't execute due to Access-Control-Allow-Origin problems. He fixed the issue be adding a file called .htaccess containing the code Header set Access-Control-Allow-Origin "*" . I'm saying this because I'm not entirely sure if it's relevant. The issue is that Ajax is switching the value of the Data variable from the input contents to copying the entire script and using that as the value. I have absolutely no idea why this is happening or how but after debugging a bit it seems that this is happening only within Ajax. I checked and JavaScript is correctly taking the value of the input but as it is passed through Ajax the value of the form_data variable is replaced with a copy of the script.
<script type="text/javascript">
$(document).ready(function() {
$("#my_form").submit(function(event){
//alert ("submited");
event.preventDefault("#my_form");
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
//var form_data = $('#submit_post').val(),
alert (post_url + "" + request_method + " " + form_data);
$.ajax({
type: request_method,
url: post_url,
data: form_data,
//crossDomain: true,
success: function( html ) {
alert (html);
$('#server-results').html(html);
},
});
});
});
And here is the screen shot of alert (html);
Thanks
I figured it out guys, the link in the form was the webpage itself! It was originally a second webpage but I changed it to send to itself to see what would happen when I was debugging it and forgot to change it back! For some reason that made ajax output the script of the webpage

Use Javascript array in PHP

I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.
Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.
Now I want to pass that JS array to PHP, so I can create tables with it.
Here's what I have done.
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
elements: enc
},
success: function(data) {
console.log(enc);
}
});
});
And in my calc.php I got this to get the values to PHP.
<?php
$data = json_decode($_POST['elements'],true);
echo $data;
?>
Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:
Undefined index: elements
I am sure I am looking at this the wrong way, interpreting it wrong.
Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.
With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.
You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.
So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?
In JavaScript:
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
"elements="+enc;
},
success: function(data) {
console.log(data);// You can use the value of data to anywhere.
}
});
});
In PHP:
<?php
if(isSet($_POST[elements]))
{
$data = json_decode($_POST['elements'],true);
echo $data;
}
else
{
echo "Elements not set";
}
?>

Auto refresh with ajax/jQuery after initial form submit then change page title

I have a form set up that, when submitted, uses an ajax call to retrieve data via a PHP file that in turn scrapes data from a given URL based on the input field value.
Everything is working perfectly, but what I'd like to do now is implement a couple of additional features.
1) After the initial form submission, I'd like it to auto-update the query at set intervals (Chosen by the end user). I'd like to append the new results above the old results if possible.
2) When new results are returned, I'd like a notification in the title of the page to inform the user (Think Facebook and their notification alert).
Current jQuery/Ajax code:
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'jobSearch.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.val('Searching....'); // change submit button text
},
success: function(data) {
$('#container').css('height','auto');
alert.html(data).fadeIn(); // fade in response data
submit.val('Search!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
I'm not too sure how I'd go about this, could anyone give me an insight? I'm not after somebody to complete it for me, just give me a bit of guidance on what methodology I should use.
EDIT - jobSearch.php
<?php
error_reporting(E_ALL);
include_once("simple_html_dom.php");
$sq = $_POST['sq'];
$sq = str_replace(' ','-',$sq);
if(!empty($sq)){
//use curl to get html content
$url = 'http://www.peopleperhour.com/freelance-'.$sq.'-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}else{
$url = 'http://www.peopleperhour.com/freelance-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}
$html = file_get_html($url);
$jobs = $html->find('div.job-list header aside',0);
echo $jobs . "<br/>";
foreach ($html->find('div.item-list div.item') as $div) {
echo $div . '<br />';
};
?>
Question 1:
You can wrap your current ajax code in a setInterval() which will allow you to continue to poll the jobSearch.php results. Something like:
function refreshPosts(interval) {
return setInterval(pollData, interval);
}
function pollData() {
/* Place current AJAX code here */
}
var timer = refreshPosts(3000);
This has the added benefit of being able to call timer.clearInterval() to stop auto-updating.
Appending the data instead of replacing the data is trickier. The best way, honestly, requires rewriting your screen scraper to return JSON objects rather than pure HTML. If you were to return an object like:
{
"posts": [
// Filled with strings of HTML
]
}
You now have an array that can be sorted, filtered, and indexed. This gives you the power to compare one post to another to see if it is old or fresh.
Question 2:
If you rewrote like I suggested above, than this is as easy as keeping count of the number of fresh posts and rewriting the title HTML
$('title').html(postCount + ' new job postings!');
Hope that helps!
If i understand correctly. . .
For updating, u can try to do something like this:
var refresh_rate = 2500
function refresh_data() {
// - - - do some things here - - -
setTimeout (refresh_data(),refresh_rate); // mb not really correct
}
You can read more about it here
Hope, i helped you

Categories

Resources