Menu
  • HOME
  • TAGS

How can I properly test PHP scripts that have been POSTed to using AJAX?

Tag: php,ajax

I'm struggling to work out how to test my code.

I have a script in PHP which takes values from a string and puts them together into a message to be mailed.

The form is submitted using AJAX as follows:

$.ajax({
    type: "POST",
    url: "actions/sendForm.php",
    data: dataString,
    success: console.log('Success!')
});

The data is supposed to be passed to the PHP script. The var dataString looks like this:

var dataString = 'name='+name+'&company='+company+'&email='+email+'&phone='+phone+'&message='+message+'&signup='+signUp;

I am then trying to access these vars as such:

parse_str($dataString);

echo $name;
echo $company;
echo $email;
echo $phone;
echo $message;
echo $signUp;

My issue is that something is not happening, and I cannot test my PHP script any more because I am submitting via AJAX, so I never actually hit the script with the correct data.

How can I test a script working/echo variables etc when the form is submitted via AJAX?

Best How To :

As the method is POST, just echo the $_POST value:

print_r($_POST);

Or, like in your example, but instead of parse_str use extract:

extract($_POST);

echo $name;
echo $company;
echo $email;
echo $phone;
echo $message;
echo $signUp;

And in your ajax function change success to:

success: function( msg ) {
    console.log(msg);
}

to see what was printed in PHP script.

Click on link next link should be display on same page

javascript,php,jquery,html,css3

Ok, so i tried to decypher what you meant with your Question. To Clarify: He has this one page setup. inside the div Our Project, there are two Buttons or links Visit more. When clicked, he wants the About Section to be shown. All in all it is impossible for...

Composer dump-autoload gives preg_match error

php,composer-php,autoload

autoload should be moved out of require-dev: { "require-dev":{ "phpunit/phpunit":"4.5.*" }, "autoload":{ "psr-0":{ "Yii\\":"yii-1.1.14.f0fee9/" } } } You can test your composer.json file using composer validate. Your original file returned: ./composer.json is invalid, the following errors/warnings were found: require-dev.autoload : invalid value, must be a string containing a version constraint...

how to escape php code in echo with javascript

javascript,php

You are mixing inline PHP with a PHP command (echo). When you are echoing a string, you do it just like normal, this means you can mix literal strings (the js you are manually typing) and the output of functions (like a json in this case): echo "<script type='text/JavaScript'> var...

MySQL Query returning strange values

php,mysql

You need to join by account_id and also question_id SELECT * FROM `quiz_questions` INNER JOIN `quiz_answers` ON `quiz_questions`.`account_id` = `quiz_answers`.`account_id` AND `quiz_questions`.`question_id` = `quiz_answers`.`question_id` WHERE `quiz_questions`.`account_id` = '1840979156127491' ORDER BY `quiz_questions`.`question_id` ASC LIMIT 5 ...

PHP Regular Expressions Counting starting consonants in a string

php,regex

This is one way to do it, using preg_match: $string ="SomeStringExample"; preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches); $count = strlen($matches[0]); The regular expression matches zero or more (*) case-insensitive (/i) consonants [b-df-hj-np-tv-z] at the beginning (^) of the string and stores the matched content in the $matches array. Then it's just a matter...

Trying to rewrite mysql_* to pdo

php,mysql,pdo

I don't know the source of the array $arr = array();, but it is assigned to null before the insert query. So it means, literally you are inserting nothing into the database. So check your array well, maybe it was to be like $arr = array('name'=>'My Name', 'url'=>'url', 'email'=>'my email',...

WooCommerce: How to display Category Name in single-product.php

php,wordpress,woocommerce

Try this : global $post; $terms = get_the_terms( $post->ID, 'product_cat' ); foreach ($terms as $term) { echo $term->name .' '; $thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true ); $image = wp_get_attachment_url( $thumbnail_id ); echo "'{$image}'"; } ...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

How to modify CodeIgniter calendar to handle multiple events per day?

php,codeigniter,calendar

If you want to show all four boxes for the dates which has data, try to change the get_calendar_data() foreach as below, $content = ""; $lastDay = -1; $index = 0; foreach ($query->result() as $row) { if($lastDay != intval(substr($row->date_cal, 8, 2))){ if($index > 0 ){ if($content != ''){ $cal_data[$lastDay] =...

Automatically calling server side class without

javascript,html,ajax

Trigger the click event like this: $('._repLikeMore').trigger('click'); ...

Pull information from SQL database and getting login errors

php,sql,database

change $username = "'rylshiel_order"; to $username = "rylshiel_order"; and you should be through. You are passing on an extra single quote here. ...

$http.get returns actual php script instead of running it (yeoman, grunt)

php,angularjs,pdo,gruntjs

Change $http.get('/scripts/php/articles.php') to $http.get('http://YOURDOMAIN.COM/scripts/php/articles.php') Off course you need to replace YOURDOMAIN.COM with localhost or any other domain you are using....

Wordpress log out using URL and redirect to specify page

javascript,php,wordpress

Try wp_logout() function use the funtion . if($_GET['logout'] == 1) { ob_start(); error_reporting(0); wp_logout(); $redirect = wp_logout_url(); wp_safe_redirect( $redirect ); } ...

Laravel 4.2 Sending email error

php,email,laravel,laravel-4

Closures work just like a regular function. You need to inject your outer scope variables into function's scope. Mail::send('invoices.mail', array($pinvoices,$unpinvoices), function($message) use ($email) { $message->to($email , 'Name')->subject('your invoices '); }); ...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

how to multiply two column names using codeigniter validation rule

php,codeigniter,validation

You done need to do anything with your controller. Add this change your view to <script> function calculate() { var myBox1 = document.getElementById('crop_quantity').value; var myBox2 = document.getElementById('per_rate').value; var result = document.getElementById('income_amount'); var myResult = myBox1 * myBox2; result.value = myResult; } window.onload = calculate(); </script> <div class="control-group"> <label class="control-label">Crop Quantity</label>...

Laravel Interfaces

php,laravel,interface,namespaces

In my recent laravel 5 project, I'm used to prepare my logics as Repository method. So here's my current directory structure. For example we have 'Car'. So first I just create directory call it libs under app directory and loaded it to composer.json "autoload": { "classmap": [ "database", "app/libs" //this...

Unable to configure Symfony (3rd party) bundle

php,symfony2,rss

I havent tried this bundle yet, but i think you need to tell doctrine that you want to save your newly created feed into the database: $feeds = new Feed; $reader->readFeed($url, $feeds, $date); $em = $this->getDoctrine()->getManager(); $em->persist($feeds); $em->flush(); return $this->render('default/index.html.twig'); UPDATE According to the docs if you want to use...

When I click to the next page on pagination,it goes to 404 error in codeigniter

php,codeigniter,pagination

in config.php $config['base_url'] = ''; $config['index_page'] = ''; in your router $route['news/(:any)'] = 'news/$1'; $route['news'] = 'news'; $route['default_controller'] = 'news/create'; $route['(:any)'] ='pages/view/$1'; and place .htaccess <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> EDIT 01 <?php $data['title'] = 'Database Details'; $count = $this->news_model->record_count()...

How to pass a value from a page to another page in PHP

php

Only values that are sent by a form will be in the GET or POST array. From what you are showing I conclude that you don't want to show the field in your form, so make it hidden. Add this inside your form tag: <input name="price" type="hidden" value="'.$price.'" class="inputClass"> Also,...

Php Mysql Query not working properly

php,mysql

No need to use union as it will give a lots of duplicate data What you want to achieve can be done with simple left join or inner join SELECT m.issue_name ,m.issue_type , m.priority ,m.status,m.description , m.start_date,m.end_date,m.duration, s.name as server_name,p.name as product_name from mod_networkstatus as m LEFT JOIN tblservers as...

Cant submit form

javascript,php

Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement. If you want to check if the form was posted then you should instead check for: if (!empty($_POST))...

Dynamically select from a dynamically generated dropdown

php,html,select,drop-down-menu

It is because you aren't ending the value attribute, so your selected option becomes <option value="optionvalueselected" -- 'optionvalue' being the value of your selected option, and 'selected' being the attribute you want to set, but won't be set because you never ended value The following should work: <select name="course_id" id="course_id">...

How to register global variable for my Laravel application?

php,laravel,laravel-5

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

Identifier starts immediately after numeric literal

jquery,ajax,razor

I think you have to include it with the ' mark Like this : var userID = '@User.Identity.GetUserId()';...

How to secure configuration file containing database username and password

php,security

As @Darkbee stated, the simplest way is to have the file outside your website root. This would be accessible on the server, but not to the public under any circumstances. The alternative is to set the permissions to 400 on the file. .htaccess could block access, but not blocking access...

Mixing

php

Set short_open_tag=On in php.ini And restart your Apache server...

Codeigniter PHP Mailer, Sender Info

php,email,codeigniter-2,phpmailer,contact-form

Don't do that. It's effectively forging the from address and will fail SPF checks. Instead, use your own address as the From address, and add the submitted address as a reply-to address. In PHPMailer: $mail->From = '[email protected]'; $mail->addReplyTo($POST['emailfrom']); ...

Is it a good practise store the checkout steps fields in php $_SESSION?

php,session,e-commerce,checkout

Create an Class that uses $_SESSION to store the data so you can use something simple like this: // start checkout $checkout = new checkout(); // to add data $checkout->AddName = $_REQUEST['name_name']; // retrieve name $name_name = $checkout->Name; // empty checkout session on success $checkout->reset(); ...

php include capitalization on files

php

Your local host must be Windows, that doesn't differentiate between upper and lower case in file names and your web server Unix Based which does, simple as that.

compare today's date with unix timestamp value in database

php,mysql

If I understand correctly you have a unix timestamp in a varchar field and you can't change this. If you compare the unix timestamp directly you will only get results that match the exact second of the timestamp. You can use FROM_UNIXTIME() to convert the timestamp in a date value...

Include both local and server at the same time

php

file_exists: http://php.net/manual/en/function.file-exists.php is_dir: http://php.net/manual/en/function.is-dir.php Best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether unix of windows format. Then we use realpath() which conveniently returns false if file does not exist. All you have to do is specify a relative...

Why am getting this error?: Unknown column 'firstname' in 'field list'

php,database,mysqli

$query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; you need single quote around text feilds in sql queries change above query to $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname','$username','$password')"; ...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)

php,mysql,mysqli,sql-injection,sql-insert

In the New PHP code snippet, you are still vulnerable to injections. You are using a prepared statement in the insert part, but you are not actually using the preparations strengths correctly. When creating a prepared statement, you create a query in which you add placeholders instead of the raw...

How do I display my mysql table column headers in my php/html output?

php,html,mysql,table,data

Note: You can just make a single file out of it to achieve your wanted output Use mysql_real_escape_string() to sanitize the passed-on value to prevent SQL injections You should use mysqli_* instead of the deprecated mysql_* API Form them in a single file like this (display.php): <html> <form method="post" name="display"...

Rewrite url not working in htaccess

php,apache,.htaccess,mod-rewrite,url-rewriting

QUERY_STRING is only used to match query string without URI. You need to use: Options -MultiViews RewriteEngine On RewriteBase /mywbsite/ RewriteCond %{THE_REQUEST} /search_data\.php\?keywords=([^&]+)&f=([^\s&]+) [NC] RewriteRule ^ search/%1/%2? [R=301,L] RewriteRule ^search/([^/]+)/([^/]+)/?$ search_data.php?keywords=$1&f=$2 [QSA,L,NC] ...

mysql_real_escape_string creates \ in server only not in local

php,sql

Your server has magic quotes enabled and your local server not. Remove it with the following sentence set_magic_quotes_runtime(0) As this function is deprecated and it will be deleted in PHP 7.0, I recommend you to change your php.ini with the following sentencies: magic_quotes_gpc = Off magic_quotes_runtime = Off If you...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

Jquery parsley validate not working

javascript,php,jquery,ajax,parsley.js

Make sure this line: $('#remarks').parsley( 'addConstraint', { minlength: 5 }); is called before you check isValid()....

php redirection working in chorme but not on firefox

php,google-chrome,mozilla

have you tried using header('location') function? example : <?php if (isset($_POST['putonline'])) { $query = "UPDATE user SET status= '1' WHERE id= '$new_id'"; $result = $cid-> query($query); if ($result== TRUE) { header("location:EidEmp.php"); die(); } else { echo "Failed"; } } ?> Edited : Maybe Change Your header function with javascript function...

What are correct permissions for Linux Apache2 PHP 5.3 log file?

php,linux,apache,logging,permissions

I'd simply set its owner to apache user. This will give you the name of apache user : ps aux | grep httpd In my case (CentOS), it's 'apache' but sometimes it's 'www-data'... chown apache:apache /var/log/httpd/php_errors.log chmod 600 /var/log/httpd/php_errors.log ...

How to Match a string with the format: “20959WC-01” in php?

php,regex

$pattern = '! ^ # start of string \d{5} # five digits [[:alpha:]]{2} # followed by two letters - # followed by a dash \d{2} # followed by two digits $ # end of string !x'; $matches = preg_match($pattern, $input); ...

How can I replace the white rectangle within an image using ImageMagick?

php,image-processing,imagemagick

I think you can locate the shape pretty accurately with a simple threshold, like this: convert image.jpg -threshold 90% result.jpg and you can then do a Canny edge detection like this: convert image.jpg -threshold 90% -canny 0x1+10%+30% result.jpg The next things I would be looking at are, using the -trim...

Time format conversion with PHP

php,time

<?php $duration="1H10M5S"; $display=str_replace(array('H','M','S'), array(' Hour(s) ',' Minute(s) ',' Seconds'), $duration); echo $display; Output 1 Hour(s) 10 Minute(s) 5 Seconds Fiddle...

Error connecting to MSSQL using PHP

php,sql-server,pdo,odbc,sqlsrv

Change it to: $this->link = new PDO( "sqlsrv:Server={$this->serverName},{$this->port};Database={$this->db};", $this->uid, $this->pwd ); The default SQL Server port is 1433. Note the curly brackets, they allow for class variables....

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

How to send current page number in Ajax request

javascript,jquery,ajax,spring-mvc,datatables

DataTables already sends parameters start and length in the request that you can use to calculate page number, see Server-side processing. If you still need to have the URL structure with the page number, you can use the code below: "ajax": { "data": function(){ var info = $('#propertyTable').DataTable().page.info(); $('#propertyTable').DataTable().ajax.url( "${contextPath}/admin/getNextPageData/"+(info.page...

RecursiveIteratorIterator to fetch subdirectories

php

I would change if ( $dir->isDir() ) to if ( $dir->isDir() && $dir != $root) to remove the root directory...